Khirad Zahra
Khirad Zahra

Reputation: 893

How to change the input fields name in a row on checkbox click

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>

Upvotes: 0

Views: 41

Answers (2)

frick
frick

Reputation: 166

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.

Upvotes: 0

Milan Chheda
Milan Chheda

Reputation: 8249

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>

Upvotes: 2

Related Questions