Reputation: 113
I have a default one checkbox and the other checkboxes will appear after I click an add button. I need to check whether a checkbox is checked or not. But the problem here is my jquery only works on the default checkbox only. The code are as follow:
HTML:
<form_answer>
<input type="hidden" class ="" id="correct_hidden" name="correct_hidden[][correct]" value="0"/>
<input type="checkbox" class ="" id="correct" name="correct[][correct]"/>
<button class="" id = "btn_add"> Add</button>
</form_answer>
JS:
<script>
$(document).ready(function(){
$('#btn_add').click(function(){
add_row();
});
});
function add_row(){
var id = $("#row").val();
id++;
var html = '<div class=""> ' +
'<input type="hidden" class ="" id="correct_hidden" name="correct_hidden[][correct]" value="0"/> ' +
'<input type="checkbox" class ="" id="correct" name="correct[][correct]"/>' +
'</div>' ;
$("form_answer").append(html);
$("#row").val(id);
}
$(document).ready(function(){
$("#correct").click(function () {
if ($(this).prop("checked")) {
$("#correct_hidden").val("1");
}else{
$("#correct_hidden").val("0");
}
});
});
</script>
The script above only works on the default checkbox only. I need the script to work on all the new append checkbox. How can I solve this?
Upvotes: 0
Views: 810
Reputation: 5122
Id's should be unique in Html. So change this to a class. Also you are adding new elements to the DOM. So you should add a eventlistener on the document and not on the element itself.
Drop the id and place it in class:
<input type="checkbox" class ="correct" id="" name="correct[][correct]"/>
Then change your js so it doesn't add id's
var html = '<div class=""> ' +
'<input type="hidden" class ="correct_hidden" id="" name="correct_hidden[][correct]" value="0"/> ' +
'<input type="checkbox" class ="correct" id="" name="correct[][correct]"/>' +
'</div>' ;
At last change the eventlistener to document and trigger it on this class
$(document).on('click', '.correct', function () {
if ($(this).prop("checked")) {
$("#correct_hidden").val("1");
}else{
$("#correct_hidden").val("0");
}
});
Upvotes: 1
Reputation: 14228
You can store the previous value id
as local variable like below.
var id = 0;
$(document).ready(function(){
$('#btn_add').click(function(){
add_row();
});
});
function add_row(){
id++;
var html = '<div class=""> ' +
'<input type="hidden" class ="" id="correct_hidden" name="correct_hidden[][correct]" value="0"/> ' +
'<input type="checkbox" class ="" id='+ id +' name="correct[][correct]"/>' +
'</div>' ;
$("form_answer").append(html);
console.log("Id value: " + id);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form_answer>
<input type="hidden" class ="" id="correct_hidden" name="correct_hidden[][correct]" value="0"/>
<input type="checkbox" class ="" id="0" name="correct[][correct]"/>
<button class="" id = "btn_add"> Add</button>
</form_answer>
Upvotes: 1