简体   繁体   中英

Linking checkbox's checked state to a value of a textbox

Would like to know how to link a checkbox's checked state to a value on a textfield returned from an sql query. The textbox value is updated after a user selects a value from a select/menu on the form. The value of the select menu option is used as a filter in the query, which is working fine.

if ($('#textbox').val("TRUE")
    { $('#mycheckbox').prop('checked',true);}
else
    {
     $('#mycheckbox').prop('checked',false);
   }

The problem is that the if statement works for the previous value the user selected. So its always one click behind even though the textbox value is current. Although the value of the textbox is current on the form, when I make an alert box displaying the textbox's value, it too is behind. So the if statement is ok, its just its using the textbox's previous value and not the current one. Any way to make this current?

Your if statment is not testing the value of #textbox it is actually setting a value.

Try changing your if statement to read:

if ($('#textbox').val() == "TRUE")

Here's another SO post that might help.

First, you have syntax error in your code, assuming that is a typo.

What you are doing by $('#textbox').val("TRUE") is setting the value of textbox to TRUE .

So whenever your code block will execute you will end-up with checked check box, and textbox with TRUE value.

If your goal is to update the checkbox as per the value of text box. you can put the following one liner code instead of your four line, when you are actually setting/updating the value of text box.

$('#mycheckbox').prop('checked',$('#textbox').val() == "TRUE")

Update

As you mentioned you are setting the new value after a ajax call and didn't included your code sample, I'm guessing, your code is something like:

$.ajax({
  url: "your/url"
}).done(function(data) {
  $('#textbox').val(data)
});

If so, update your code to

$.ajax({
  url: "your/url"
}).done(function(data) {
  $('#textbox').val(data);
  $('#mycheckbox').prop('checked',$('#textbox').val() == "TRUE");
});

The response is based on guess.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM