Jquery changing hidden input value when a checkbox is checked and reverse when unchecked?

走远了吗. 提交于 2019-12-22 13:10:19

问题


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



来源:https://stackoverflow.com/questions/9712340/jquery-changing-hidden-input-value-when-a-checkbox-is-checked-and-reverse-when-u

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!