0

I have an editable ajax table , and have a "unlock" field with a checkbox for every row.

When I check the chekbox I need to get the value 1 ( I'm ok for this part ! :)

My code to get the value of the cheked box:

( $("#unlock_input_" + ID).val(); ) )

But when I uncheck one of any checkbox , I need to get the value 0 ( I need help for this part)

So.... How can I do that in jquery ? Thx

4 Answers 4

3

You could throw on a :checked selector. Then you'll get back undefined when the box is unchecked, which is falsey, so:

var result = $("#unlock_input_" + ID + ":checked").val() || 0;

result will end up with the value of the checkbox if it's checked, or 0 if not, because of the way JavaScript's curiously-powerful || operator works.

Live example

Another way to write it:

var result = $("#unlock_input_" + ID).filter(":checked").val() || 0;

Or of course, the rather more direct:

var cb = $("#unlock_input_" + ID)[0],
    result = cb.checked ? cb.value : 0;
Sign up to request clarification or add additional context in comments.

3 Comments

@user1029834: My initial answer had an error in it, I've fixed it now (I left off the :checked selector).
Very much like the shortness of this ... I'd have probably gone down the ? : route :)
@CD001: There are upsides and downsides. Using :checked is definitely going to perform worse than my last alternative above, but of course, unless you're in a tight loop, it doesn't matter. So it's horses for courses... :-) (What I do in my projects is use an extension method I add called checkedVal, which returns the value if checked using an efficient means or returns undefined if unchecked.)
1

change your code to this (using prop to ask for the checked-property):

var result = $("#unlock_input_" + ID).prop('checked')?1:0;

EDIT:
if you explicitly need the value instead of 1, just do:

var element = $("#unlock_input_" + ID);
var result = element.prop('checked')?element.val():0;

Comments

1

You can use the checked property of the checkbox to decide whether 1 or 0. Try this

if($("#unlock_input_" + ID)[0].checked){
    alert("1");
}
else{
    alert("0");
}

Alertnatively you can use jQuery is method to check whether the checkbox is checked or not.

if($("#unlock_input_" + ID).is(":checked")){
    alert("1");
}
else{
    alert("0");
}

1 Comment

.is(":checked") shudder ;-) If you're going to branch, I'd definitely branch your first way unless there's some possibility the checkbox won't exist.
1

You could check if it's chekced

if($("#unlock_input_" + ID).is(':checked')){
    myVal = "1";
}
else{
    myVal = "0";
}

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.