Jquery changing hidden input value when a checkbox

2019-05-22 23:37发布

问题:

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.

回答1:

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

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



回答2:

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