0

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>
2
  • .live() is deprecated and removed in newer jQuery versions. I would recommend updating your scripts to .on() Commented Dec 15, 2016 at 14:41
  • Thankyou @empiric Commented Dec 15, 2016 at 14:45

1 Answer 1

1

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!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.