简体   繁体   English

将复选框的选中状态链接到文本框的值

[英]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. 想知道如何将复选框的选中状态链接到从sql查询返回的文本字段上的值。 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. 问题在于if语句适用于用户选择的先前值。 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. 因此,如果if语句正常,则仅使用文本框的上一个值而不是当前值。 Any way to make this current? 有什么办法使这种潮流?

Your if statment is not testing the value of #textbox it is actually setting a value. if您的陈述并未测试#textbox的值,则实际上是在设置值。

Try changing your if statement to read: 尝试将您的if语句更改为:

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 . $('#textbox').val("TRUE")所做的工作是将textbox的值设置为TRUE

So whenever your code block will execute you will end-up with checked check box, and textbox with TRUE value. 因此,无论何时执行代码块,您都将选中复选框,文本框为TRUE值。

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") $('#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调用之后设置新值的,并且没有包含您的代码示例,我想您的代码是这样的:

$.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. 响应基于猜测。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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