jQuery - Change hidden value based on input field

2019-08-25 20:09发布

问题:

I am using a form field to capture stats of a particular situation. I need the value of a hidden field to change based on the input of two text fields. I will describe the function in plain English. Help translating this to a functioning jQuery script would be greatly appreciated.

Hidden field equals 'yes' where the value of field_1 equals 4 && field_2 equals 2 or Hidden field equals 'yes' where the value of field_1 equals 3 && field_2 equals 1 or Hidden field equals 'yes' where the value of field_1 equals 2 else Hidden field equals 'no'

As indicated by the structure of the statement, I'm a php developer first. It is my assumption that this can be done via jQuery. If not, provide me with an alternative. Thanks!

回答1:

Hope this helps. Check out jQuery api incase your fields are different some how (like if they are checkboxes)

var field1 = parseInt($('#field_1').val());
var field2 = parseInt($('#field_2').val());

if((field1 == 4 && field2 == 2) || (field1 == 3 && field2 == 1) || field1 == 2){
   $('#hidden').val('yes')
} else {
   $('#hidden').val('no')
}


回答2:

The following use the keyup event handler to modify the hidden input value based on the input value of field_1 and field_2 (assuming they are text input).

$('#field1 #field2').keyup(function() {
    var field_1 = parseInt($('#field_1').val());
    var field_2 = parseInt($('#field_2').val());

    if (field_1 == 4 && field_2 == 2) {
        $('#hidden').val('yes');
    }
    else if (field_1 == 3 && field_2 == 1) {
        $('#hidden').val('yes');
    }
    else if (field_1 == 2) {
        $('#hidden').val('yes');
    }
    else {
        $('#hidden').val('no');
    }
});