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?

3
  • Please clarify yor question, it it not clear what your problem is. Does the form submit? what errors are you getting? Commented Aug 14, 2014 at 12:17
  • Where is your #ongoing element in the code? Do you mind adding that snippet? Commented Aug 14, 2014 at 12:24
  • <div style="margin-left:5px;"> <label for="ongoing"> On going Alerts </label> <input type="checkbox" name="ongoing" id="ongoing" style="display:inline-block;vertical-align:middle" <?php if ($_POST['going'] == "1") echo "checked"; ?>> </div> this is the #ongoing element.. and I don't get any errors, but the page submited successfully to the page test.php Commented Aug 14, 2014 at 13:14

2 Answers 2

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(); }); 
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.