0

I'm trying to submit a form to a PHP page, but the data is not accessible from this page, This is my code:

Html code:

<form method="post" id="formid" action="test.php">
    <input type="hidden" name="going" id="going" value="" /> 
</form>

Javascript:

$("#ongoing").change(function() {
    var ongoing = $(this).attr('checked');
    var input = document.getElementById('going');
    var form = document.getElementById('formid');

    if (ongoing)
        input.value = "1";
    else
        input.value = "0";

    form.submit();
});

test.php

if(isset($_POST['going']))
      echo $_POST['going'];

What am I doing wrong?

Roham Rafii
  • 2,929
  • 7
  • 35
  • 49
Omar Taha
  • 265
  • 2
  • 14
  • Please clarify yor question, it it not clear what your problem is. Does the form submit? what errors are you getting? – Steve Aug 14 '14 at 12:17
  • Where is your #ongoing element in the code? Do you mind adding that snippet? – rolling_codes Aug 14 '14 at 12:24
  • > this is the #ongoing element.. and I don't get any errors, but the page submited successfully to the page test.php – Omar Taha Aug 14 '14 at 13:14

2 Answers2

1

use this

   $("#ongoing").change(function() {
        var input = document.getElementById('going');
        var form = document.getElementById('formid');

       if($(this).is(':checked'))
       {
          input.value = "1";
       }
       else
       {
          input.value = "0";
       }

        form.submit();
    });
Satish Sharma
  • 9,547
  • 6
  • 29
  • 51
0

Try this! It does what you want with much less code. You were having issues because the checked attribute returns a string not a boolean value.

$("#ongoing").change(function() {
    var form = document.getElementById('formid');
    form.going.value = $(this).attr('checked').toLowerCase() == "checked" ? "1" : "0";
    form.submit();
});

The longer way looks like:

$("#ongoing").change(function() {
    var form = document.getElementById('formid');
    var input = document.getElementById('going');
    var isChecked = $(this).attr('checked').toLowerCase() == "true";
    if(isChecked)
        input.value = "1";
    else
        input.value = "0";
    form.submit();
});

Additionally! It is good practice when writing html attributes to always type checked="true" (or "false") even though just checked is synonymous with the previous. Unpaired markup attribute-values could be mistaken by amateur coders as tag names.

See here for more Checkboxes in Jquery

Community
  • 1
  • 1
rolling_codes
  • 15,174
  • 22
  • 76
  • 112