0

Change the input field name of the checked check box row

Note: Type field may or may not exist in every row.

Like if name[] and type[] fields exists,change both name to name1[] and type1[]. or just change the name of name[] field if type[] does not exists.

$(document).ready(function() {
$(".click1").on('change', function() {
            if($(this).is(":checked")) {          
               alert('checked')
            }        
        });
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li id="row_3">
   <div class="col-md-6">
      <input type="text"  name="name[]">
       <input type="text"  name="type[]">
       <input type="checkbox" name="click" class="click1">
      </div>
   </div>
</li>

2 Answers 2

2

You should .find('input[name^="type"]') and check if it exists, if yes, change the name of other input element to name1. Below is the updated code:

$(document).ready(function() {
  $(".click1").on('change', function() {
    if ($(this).is(":checked")) {
      if ($(this).parent().find('input[name^="type"]').length) {
        $(this).parent().find('input[name^="name"]').prop('name', 'name1[]');
      }
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li id="row_3">
  <div class="col-md-6">
    <input type="text" name="name[]">
    <input type="text" name="type[]">
    <input type="checkbox" name="click" class="click1">
  </div>
</li>

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

1 Comment

Thank you for the answer.this is what i was looking for. Excellent
0

Add ids to both elements so that you can easily access them within your code.

<input type="text" id="name" name="name[]">
<input type="text" id="type" name="type[]">

And, within your jQuery, change the names like this:

$(document).ready(function() {
  $(".click1").on('change', function() {
    if($(this).is(":checked")) {          
      $("#name").attr("name", "name1[]");
      $("#type").attr("name", "type1[]");
    }        
  });
});

The good thing is, if you remove the #type field, $("#type") will return an empty set, and you will not do anything to it.

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.