0

I have the following post request. It's sending all other fields successfully. However, whatever I try it simply does not pick up the check box. I've tested the id with a click event and alert and it's definitely referencing the checkbox ok.

$.post("http://" + window.location.host + "/exec_messages_send.php",
{
    receiver : $("#messages_receiver").val(),
    title : $("#messages_title").val(),
    body : $("#wysi_textarea_message_body").val(),
    urgent : $("#messages_urgent").checked
}

This is the html, rendered with php:

echo "<input type=\"checkbox\" id=\"messages_urgent\"> Mark as <span class=\"label label-important\">Urgent</span>";

How do I get the value of the checkbox? I've already tried .val() and .attr('checked') and .checked and a few other methods...

2
  • .checked only works on regular javascript elements, not jQuery elements Commented Jun 17, 2013 at 12:35
  • Where is the value in check box ? If no value then you can get true or false Commented Jun 17, 2013 at 12:37

6 Answers 6

3

use -

urgent : $("#messages_urgent")[0].checked

Or

urgent : $("#messages_urgent").is(':checked');
Sign up to request clarification or add additional context in comments.

Comments

0

Have you tried with

$("#messages_urgent").is(':checked').val();

or you can directly like

$("#messages_urgent:checked").val();

and also give some value to checkbox

echo "<input type=\"checkbox\" value=\"my_value\" id=\"messages_urgent\"> Mark as <span class=\"label label-important\">Urgent</span>";

Comments

0

Not sure i understand your problem here, but maybe just use .prop():

urgent : $("#messages_urgent").prop('checked')

2 Comments

Or urgent : $("#messages_urgent")[0].checked
Or urgent : $("#messages_urgent").get(0).checked. Using .prop() is just the jquery way to do it
0

I'm presuming you want to serialize a form in some way. In your example you pick the fields in JS but unless you have need to change where the data is coming from dynamically, you'd get the same results far more easily by using the default behavior of submitting a form.

There doesn't seem to be a name attribute on the input element. Inputs without name are ignored by default, as are checkboxes with value false. But you can work around it with reading the checked-property as indicated in the other answers.

Normally serializing form also ignores checkboxes if they are not checked. Eg. How can I serializeArray for unchecked checkboxes?

Comments

0

$('#messages_urgent').is(':checked') will do.. :-)

Comments

0

Try this

$("#messages_urgent").is(':checked'); // it returns true of false

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.