Jquery changing hidden input value when a checkbox

2019-05-22 23:07发布

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条回答
2楼-- · 2019-05-22 23:29

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

查看更多
看我几分像从前
3楼-- · 2019-05-22 23:31
$('.year').click(function(){
    $('#carsearch').val( $(this).is(':checked') ? 'True' : 'False' );
})

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

查看更多
登录 后发表回答