我需要将console.log复选框的值作为JSON对象。我是Javascript和Jquery的新手,因此将不胜感激。 我有以下代码:
jQuery(document).ready(function() {
jQuery("input[type='button']").click(function() {
var doorType = [];
jQuery.each(jQuery("input[name='app']:checked"), function() {
doorType.push(jQuery(this).val());
});
jQuery.each(jQuery("input[name='app-sol']:checked"), function() {
doorType.push(jQuery(this).val());
});
console.log(doorType.join(", "));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<h4>Тип дверей:</h4>
<label><input class="derevo-app" type="radio" value="derevo" name="app"> Дерево</label>
<label><input class="metal-app" type="radio" value="metal" name="app"> Метал</label>
<label><input class="pvh-app" type="radio" value="pvh" name="app"> ПВХ</label>
<label><input class="sklo-app" type="radio" value="sklo" name="app"> Скло</label>
<h4>Продукція:</h4>
<label><input class="zamky-app" type="checkbox" value="zamky" name="app"> Замки</label>
<label><input class="cylindry-app" type="checkbox" value="cylindry" name="app"> Циліндри</label>
<label><input class="dostup-app" type="checkbox" value="dostup" name="app"> Контроль доступа</label>
<label><input class="antipanic-app" type="checkbox" value="antipanic" name="app"> Антипаніка</label>
<label><input class="dovodchyk-app" type="checkbox" value="dovodchyk" name="app"> Доводчики</label>
<h4>Рішення:</h4>
<label><input class="elektronne-app" type="radio" value="elektronne" name="app-sol"> Електронне</label>
<label><input class="mexanichne-app" type="radio" value="mexanichne" name="app-sol"> Механічне</label>
<h4>Відеокамери:</h4>
<label><input class="vnutr-app" type="checkbox" value="vnutr" name="app"> Внутрішні</label>
<label><input class="zovn-app" type="checkbox" value="zovn" name="app"> Зовнішні</label>
<br>
<input type="button" value="ПРОДОВЖИТИ">
</form>
You need to move your
doorType
variable declaration outside of the event handler so it retains its value across function calls and then useJSON.stringify()
to convert your array to a JSON string.You need to use
JSON.stringify(doorType)
. And also, as Chris mentioned, you cannot use the same names.