2

I am using Jquery to change the value of a hidden input to True when the user checks a checkbox in a different form field. It looks like this:

$(function(){
    $('.year').click(function(){
        $('#carsearch').val('True');
    });

It works great except if the user changes their mind and unchecks the box, the hidden input keeps the value of True. I want to make it so that if they change their mind and uncheck the .year input that it changes the value of #carsearch back to False.

I would really appreciate any input on how this is accomplished.

2 Answers 2

7
$('.year').click(function(){
    $('#carsearch').val( $(this).is(':checked') ? 'True' : 'False' );
})

You might be better off listening to 'change' instead of 'click' though.

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

5 Comments

Remember that this.checked is the same thing as $(this).is(':checked') and requires no jQuery overhead.
Worked like a charm. Thanks a million John!
@Jasper -While at the same time, dealing with the DOM objects directly destroys the abstraction layer and is a really bad way to interact with the code. If one of my devs checked in that code I'd reject it and have him fix it.
@JohnGreen-PageSpike Could you expand on dealing with the DOM objects directly destroys the abstraction layer? I don't quite follow. What does not using .val() break? Thanks for your reply in advance.
jQuery acts as an abstraction layer for the DOM. With it, there should be few, if any reasons to ever deal directly with any DOM object. By going directly to the object and querying its 'checked' property, you're mixing apples (jquery abstracted object) with oranges (vanilla object). It'd take me half a book to explain all of the reasons that this is bad practice, and really... the currently implementation of the sizzle engine just looks for 'elem.checked === true'. That being said... things change, and I know I'd rather have jQuery stay up to date on iterative DOM & quirks than myself.
1

Try this.

$('.year').click(function(){
    $('#carsearch').val( this.checked ? 'True' : '' );
});

Edited based off of Jasper's suggestion.

Assuming that True is the value for checked and empty if not.

This is called the ternary operator, more information on it can be found here - http://en.wikipedia.org/wiki/Ternary_operation

1 Comment

+1, but you could make this faster by changing $(this).is(':checked') to: this.checked.

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.