Shahrukh
Shahrukh

Reputation: 45

jQuery Loop for checkboxes

Currently I've two input fields which updates automatically when I press Update button and I want to add more inputs... but problem is I have to add my input field name in jquery script manually. Can we add any loop for this? Please help!!

Type Comment: <input name="mainComment" type="text" value="" />
<input type="button" name="updateComment" value="Update" />

<hr />

<input type="checkbox" class="myCb" name="cb[1]" /><input type="text" name="inv[1]" value="" /><br />
<input type="checkbox" class="myCb" name="cb[2]" /><input type="text" name="inv[2]" value="" />


<script type="text/javascript">
    $(document).ready(function() {
        $("input[name='updateComment']").live("click", (function(){
            if($("input[name='cb[1]']").is(":checked")) {
                $("input[name='inv[1]']").val($("input[name='mainComment']").val());
            } else {
                $("input[name='inv[1]']").val("");
            }

            if($("input[name='cb[2]']").is(":checked")) {
                $("input[name='inv[2]']").val($("input[name='mainComment']").val());
            } else {
                $("input[name='inv[2]']").val("");
            }
        }));
    });
</script>

Upvotes: 0

Views: 4280

Answers (1)

Saumya Rastogi
Saumya Rastogi

Reputation: 13709

You can use input's class name (.myCb) to select the inputs from the DOM and use jQuery's .each() method to loop through each inputs.

You can do it like this:

$(document).ready(function() {
        $("input[name='updateComment']").on("click", (function(){
        		var val = $("input[name='mainComment']").val();
            $('input.myCb').each(function(i) {
            	if($(this).is(':checked')) {
                $(this).next().val(val);
              } else {
                $(this).next().val('');
              }
            })
        		
        
        }));
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Type Comment: <input name="mainComment" type="text" value="" />
<input type="button" name="updateComment" value="Update" />

<hr />

<input type="checkbox" class="myCb" name="cb[1]" /><input type="text" name="inv[1]" value="" /><br />
<input type="checkbox" class="myCb" name="cb[2]" /><input type="text" name="inv[2]" value="" /><br>
<input type="checkbox" class="myCb" name="cb[3]" /><input type="text" name="inv[2]" value="" />

Hope this helps!

Upvotes: 1

Related Questions