4

I'm trying to add script to my html form that will remove all unchecked checkboxes and replace them with a hidden field and a value of "no". If checkboxes are checked, they will show a value of "yes".

Please note, I can not add this hidden field into the form because the site I host it on does not allow two form fields with the same name, as I've seen suggested before: Post the checkboxes that are unchecked

For some reason, the script only works when I load the page, submit the form with all checkboxes unchecked, then submit the form again. If I reload the page, I have to do the same thing again. This shows what I'm referring to: https://gfycat.com/HarshWaterloggedKestrel

Is it because I'm adding the event listener after the first form submission?

Here is a fiddle with sample code: https://jsfiddle.net/gvd1jr0o/6/

Here is my script:

$("#foo").submit(
  function() {
    var formEl = $(this);//get the reference of the form
    debugger;
    // Add an event listener on #foo submit action...
    // For each unchecked checkbox on the form...
    formEl.find("input:checkbox:not(:checked)").each(

      // Create a hidden field with the same name as the checkbox and a value of 0
      // You could just as easily use "off", "false", or whatever you want to get
      // when the checkbox is empty.
      function(index) {
        var input = $("<input>");
        input.attr('type', 'hidden');
        input.attr('name', $(this).attr("name")); // Same name as the checkbox
        input.attr('value', "no"); // or 'off', 'false', 'no', whatever

        // append it to the form the checkbox is in just as it's being submitted
        formEl.append(input); //$("#foo") is referring to the form

      } // end function inside each()
    ); // end each() argument list

    return true; // Don't abort the form submit

  } // end function inside submit()
);                         
Community
  • 1
  • 1
cgrouge
  • 177
  • 2
  • 16
  • 1
    Your fiddle is submitting the form on clicking the first time.. Am I missing something. – Rajshekar Reddy Aug 31 '16 at 13:46
  • The form does submit, but the value for unchecked check boxes should be "no" on the first form submission. It's not doing that. Wasn't sure how to show that through fiddle. So, I just used fiddle to show simple form with script – cgrouge Aug 31 '16 at 13:56
  • I still see the values "no" posted in the network tab.. But only difference is the inner fucntion is executed only on the second time of submission.. – Rajshekar Reddy Aug 31 '16 at 14:29
  • Check this fiddle... I have added a alert of form data that's submitted.. it looks fine https://jsfiddle.net/gvd1jr0o/8/ – Rajshekar Reddy Aug 31 '16 at 14:33
  • I added the alert to my form and the pop up shows the script working but when checking the data file I'm still getting the same result as before. The first submission shows all undefined and the second submission shows checkboxes working... – cgrouge Aug 31 '16 at 14:41
  • Ok so you say the issue is when you receive the data in your server side? may be then its because the form has both the actual elements and the hidden elements from the script and hence the confusion.. – Rajshekar Reddy Aug 31 '16 at 14:47
  • @reddy If that is the case, why would this only happen on the very first submission? After submission the page does not reload. I can submit the form again and the script works fine. But if I reload the form, the first submission does not have values for unchecked checkboxes. – cgrouge Aug 31 '16 at 15:19

3 Answers3

1

I think you're going about this the whole wrong way.

First, add an onLoad event handler to your form or page that creates checkboxes for all unchecked checkboxes. Then, create an event handler on your checkbox elements that creates or deletes the relevant input element for that checkbox when their checked state changes. that way, your checkboxes are already created when you submit the form. I think you currently got a race condition where your form is being submitted before your checkboxes are created.

You can consult the jQuery documentation for more information on how to add event handlers to checkboxes or a form/page.

Nzall
  • 3,439
  • 5
  • 29
  • 59
  • So I can add the event handler and if it's checked, do nothing. If it's not checked, create the hidden input field that replaces the unchecked input and gives it a value of "no"? Here is what I drafted up quickly, something like this? :https://jsfiddle.net/qj8Lzsg7/ – cgrouge Sep 01 '16 at 15:06
  • Or should I run two functions here? The first will give all unchecked checkboxes a hidden input field when the page is loaded. Then create the second function that will remove it when clicked? – cgrouge Sep 01 '16 at 15:37
  • @cgrouge as yuou say in your first comment, yes. – Nzall Sep 01 '16 at 19:14
  • @cgrouge I updated my answer to fix a bug that might arise. Essentially, when the page loads, you need to create the new checkboxes as well, or any elements that weren't changed won't be processed. – Nzall Sep 01 '16 at 21:31
0

Your fiddle working correctly (as i understood). You can wrap all into document.ready() or (it`s stupid) you forget about debugger when console is open.

Sasha
  • 19
  • 4
0

i had changed add the input tag and preventDefault for submit , check below code and let me know if you require.. There is no code written to set yes when checked..

$(function() {
$("#foo").submit(
  function(e) {
    e.preventDefault();
   var formEl = $(this);//get the reference of the form
    debugger;
    // Add an event listener on #foo submit action...
    // For each unchecked checkbox on the form...
    formEl.find("input:checkbox:not(:checked)").each(

      // Create a hidden field with the same name as the checkbox and a value of 0
      // You could just as easily use "off", "false", or whatever you want to get
      // when the checkbox is empty.
      function(index) {
        var input = $("<input/>");
        input.attr('type', 'hidden');
        input.attr('name', $(this).attr("name")); // Same name as the checkbox
        input.attr('value', "no"); // or 'off', 'false', 'no', whatever

        // append it to the form the checkbox is in just as it's being submitted
        formEl.append(input); //$("#foo") is referring to the form

      } // end function inside each()
    ); // end each() argument list

    return true; // Don't abort the form submit

  } // end function inside submit()
);                                                 
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="foo">
  <input type=checkbox name="c1"/>
  <input type=checkbox name="c2"/>
  <input type=checkbox name="c3"/>
  <input type=submit value=submit />
</form>
CNKR
  • 568
  • 5
  • 19
  • This solution, like the other is working great but for some reason it only works on the second submission. I can't get the first submission to input "no" for unchecked boxes. I've set the value for the check boxes as yes when checked, so this does not need to be included in the script – cgrouge Aug 31 '16 at 16:33
  • check now , i added `$(function(){}` – CNKR Aug 31 '16 at 16:45
  • Unfortunately, I'm still getting "undefined" on the first submission: https://gfycat.com/BothAridBlackandtancoonhound – cgrouge Aug 31 '16 at 17:31
  • I'm unsure how to provide that to you, can you explain further? – cgrouge Aug 31 '16 at 18:19
  • I want to know the code fully to help you better... Can you create a fiddle with the sample data.. and fields or mimic the scenario on it.. – CNKR Aug 31 '16 at 18:29