javascript - 页面加载时根据单选按钮选择或值显示文本框

标签 javascript php jquery

因此,当我加载页面时,我会从数据库检索信息,并根据其值检查单选按钮...

我需要最初显示文本框 - 基于已选中的单选按钮

当我执行点击事件时工作正常,但我需要在页面加载时显示文本框,因为第一个单选按钮是从数据库中检查的...

  <p>
  Show textboxes <input type="radio" name="radio1" value="Show" checked="checked">
  Do nothing <input type="radio" name="radio1" value="Nothing">
  </p>

  Wonderful textboxes:

  <div class="text"><p>Textbox #1 <input type="text" name="text1" id="text1" maxlength="30"></p></div>

  <div class="text"><p>Textbox #2 <input type="text" name="text2" id="text2" maxlength="30"></p></div>

这是我的 FIDDLE - 演示 http://jsfiddle.net/rbla/5fq8q2bj/

这里是使用toggle的jquery

 $(document).ready(function() {
     $(".text").hide()
     $('[name=radio1]').on('change', function(){
        $('.text').toggle(this.value === 'Show');
     }).trigger('change');
 });

任何想法...

最佳答案

您的解决方案不起作用的原因是您正在检查所有 radio 输入,然后根据其值切换元素 - 无论是否选中。因此,在运行时,您的脚本将执行以下操作:

  1. 遇到第一个 radio 元素,触发 onchange 事件,触发 onchange 回调,并显示 .text 元素
  2. 遇到第二个 radio 元素,触发 onchange 事件,触发 onchange 回调,并再次隐藏 .text 元素

如果您将控制台日志放入回调中,您将意识到 .text 元素会快速连续地显示和隐藏。

您真正想做的只是在检查时执行切换。因此,您的示例只需在执行切换之前强制检查 this.checked 是否为真即可工作:

$('[name=radio1]').on('change', function() {
  if (this.checked) {
    $('.text').toggle(this.value === 'Show');
  }
}).trigger('change');

请参阅下面的工作示例:

$(document).ready(function() {
  $(".text").hide()
  $('[name=radio1]').on('change', function() {
    if (this.checked) {
      $('.text').toggle(this.value === 'Show');
    }
  }).trigger('change');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
  Show textboxes
  <input type="radio" name="radio1" value="Show" checked="checked"> Do nothing
  <input type="radio" name="radio1" value="Nothing">
</p>

Wonderful textboxes:

<div class="text">
  <p>Textbox #1
    <input type="text" name="text1" id="text1" maxlength="30">
  </p>
</div>
<div class="text">
  <p>Textbox #2
    <input type="text" name="text2" id="text2" maxlength="30">
  </p>
</div>

关于javascript - 页面加载时根据单选按钮选择或值显示文本框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46850788/

相关文章:

jquery - 在 mouseenter 和 mouseleave 上添加 animate.css 类

javascript - KendoUI 自动完成提交表单

javascript - 如何删除angularjs中的数据?

javascript - 从 GoMobile 调用 JS 包?

php - Mysql:基于数组的多对多查询

php - 当我在 while 循环中有 mysql 查询时出现 "No data received"错误

php - 即使我的用户名和密码正确,仍获取 "Warning: mysqli_connect(): (2800/1045)"

javascript - JS 异常 : animate is not a function

javascript - “文档”在 Greasemonkey 中未定义

javascript - 如何使用 Jest 来监视 prop 内的方法并将其传递给组件?