1

I am trying to change the name to null/empty of all checkboxes which is unchecked on onchange event and on ondocumentready event using jquery.

this is my code

<div id="tab_4">
 <div class="col-xs-12">
  <input type="text" name="txtbox1" value="1">
  <input type="checkbox" name="chkbox1" value="1">
  <input checked type="checkbox" name="chkbox2" value="2">
  <input type="checkbox" name="chkbox3" value="3">
 </div>
</div>

<script type="text/javascript">
    $(document).ready(function(){
      $('#tab_4 input[type=checkbox]').each(function(i){
       if($(i).not(':checked'))
        {
         $(this).attr('name', '');
        }
       });
    });
    $('#tab_4 input[type=checkbox]').change(function(){
    $('#tab_4 input[type=checkbox]').each(function(i){
        if($(i).not(':checked'))
        {
         $(this).attr('name', '');
        }
       });
    });
</script>

But it makes all name attribute to null even checked ones.

I used this answer Changing input name using JQUERY

2
  • 1) Why exactly do you want this to happen? Commented Dec 1, 2019 at 9:20
  • to send only checked input values into database Commented Dec 1, 2019 at 9:23

1 Answer 1

1

You don't need to remove uncheckbox checkbox elements name to exclude it from form data. It is excluded by default. Check the following demonstration:

const tell = () => console.log([... new FormData($('form').get(0)).entries()])

$(() => {
  tell()
  $('input').on('change', tell)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form>
<div id="tab_4">
 <div class="col-xs-12">
  <input type="text" name="txtbox1" value="1">
  <input type="checkbox" name="chkbox1" value="1">
  <input checked type="checkbox" name="chkbox2" value="2">
  <input type="checkbox" name="chkbox3" value="3">
 </div>
</div>
</form>

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.