Reputation: 4028
I have multiple checkbox
<input value="78" name="download_category[]" id="in-download_category-78" type="checkbox">
<input value="84" name="download_category[]" id="in-download_category-84" type="checkbox">
....
<input value="93" name="download_category[]" id="in-download_category-93" type="checkbox">
and I have input type text
<input class="fes-name-value" name="option[0][description]" id="options[0][description]" rows="3" value="" type="text">
<input class="fes-name-value" name="option[1][description]" id="option[1][description]" rows="3" value="" type="text">
I want to write jQuery for below task:
If user check on first option, the value of the option is automatically inserted to 1st textbox. If user uncheck on first option, the 1st textbox is hide.
If user continue to check second option, the 2nd textbox is added and the value of the option is inserted to 2nd textbox. If user uncheck, 2nd textbox is hide.
What is your best solution? Thanks.
Upvotes: 0
Views: 254
Reputation: 8858
Try this:
$('input:checkbox').on("click",function()
{
if($(this).is(":checked"))
{
$(this).next('input').show();
$(this).next('input').val($(this).val());
}
else
$(this).next('input').hide();
});
Example : https://jsfiddle.net/DinoMyte/sj910khv/5/
Upvotes: 0
Reputation: 1483
On click of checkbox, first check if it is checked or not. If checked than add input, else remove the relevant input....I am not sure how you are setting the name for inputs so just giving an example. Hope it will help you
$("input[type='checkbox']").on('click', function(){
var checkBox_value = $(this).val();
if($(this).is(':checked')){
$('div').append('<input type="text" name="input_'+checkBox_value+'" value="'+checkBox_value+'"');
}
else{
$("input[name='input_"+checkBox_value+"']").remove();
}
});
Upvotes: 1