【问题标题】:Get the value in an input text box, the id from side server获取输入文本框中的值,来自侧服务器的 id
【发布时间】:2021-10-13 09:58:29
【问题描述】:

朋友。

我有以下输入,在这种情况下来自服务器端的值是“Y”,想法是当它是“Y”时复选框更改为选中,但脚本对我不起作用。

谢谢

<input type="checkbox" name="choice-animals" id="choice">

var variable = $('#choice').val();
       console.log("----+++" + variable);

       $(document).ready(function () {
           $('input[id="choice"]').each(function (index) {
             
               


               if ($(this).val()=="Y")
                   ($(this).prop('checked', true));
               else
                   ($(this).prop('checked', false));

           });
       });

Console.log return on

【问题讨论】:

标签: javascript c# html jquery


【解决方案1】:

在你的代码中修复几个问题:

  1. 如果您碰巧有多个复选框,请确保它们具有唯一索引。在 HTML 语法中,一个 id-attribute 值应该只在该页面上出现一次,因此它不应该用于为该类选择多个元素,或者 data-attribute 更好。我提供了替代代码来选择所有复选框-

  2. 要检查输入是否真正具有 .val(),它需要具有值属性。

  3. If else 语法使用 () 作为条件,并且您的代码应该在 {}

var options = $('input[type="checkbox"]')

options.each(function(e){
  if($(this).val() === "Y") {
    $(this).prop('checked', true)        
  } else {
    $(this).prop('checked', false)
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<label>
  Choice 1
  <input type="checkbox" name="choice-animals" value="Y">
</label>

<label>
  Choice 2
  <input type="checkbox" name="choice-animals" value="X">
</label>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-04
    • 2012-02-11
    • 1970-01-01
    • 1970-01-01
    • 2013-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多