0

I have a javascript that needs to grab the value of a checkbox when its checked and ignore its value when its not checked.

Right now i'm grabbing the value of the checkbox with:

$("input[name='tos']:checked").val()

It works when you check the box and submit the form, but if you uncheck it and resubmit the form the old value of "agree" is given. So i'm wondering how to I grab the value of a checkbox only when its checked?

4 Answers 4

2

http://jsfiddle.net/dqy5H/

Here is an example fiddle. Sorry for the bad first response.

Sign up to request clarification or add additional context in comments.

3 Comments

I tried $("input[name='tos']").val() but that didn't work. Maybe I need to manually check if its checked?
interesting site but I had to manually check and set values accordingly but thanks anyways.
+1 because accepted answers should always also have an upvote :)
2

Don't forget that unchecked checkboxes don't travel in form submission. Your code is ok, but you may have the old value stored on server side.

A workaround is tht you could have an <input type="hidden"/> that changes its value when you check/uncheck the checkbox, and read this hidden on the server. Or simply, ask if the checkbox arrived to the server, if it didn't it means it was unchecked.

Hope this helps. Cheers

Comments

0

Two things, in order of least to most helpful :)

  1. A checkbox should never return a value of "agree"! I'm hoping you misspoke.
  2. I'm not sure the jQuery selector you used there is actually valid. As the other fellow mentions, it is but it only ever sets the value when it's checked. Oof, my bad. In any case, I'd still recommend giving the checkbox an ID/unique class, and then do:

    var checked = $('#toscheckbox').val();

You can add IDs without messing up the form's submission data, and I prefer them - names are so fiddly.

2 Comments

It still keeps the old value when I assign it an ID.
@Kerin - Why should a checkbox never return a value of "agree"? That seems a rather arbitrary restriction. Can you please provide an explanation? (I'd most often code them to return "Y" or "true" or "1" or some other more boolean sounding value, but I wouldn't say never to other values.)
0

Try giving it an id and calling .is(':checked') like in this article to see if it is checked or not.

http://jquery-howto.blogspot.com/2008/12/how-to-check-if-checkbox-is-checked.html

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.