【问题标题】:Selecting radio button in js在js中选择单选按钮
【发布时间】:2015-04-26 23:11:56
【问题描述】:

我的代码有问题,我想在单击其中一个单选按钮时显示输入文本表单。 Ajax 代码:

<script type="text/javascript">
$(document).ready(function(){
$('#macam').click( function() {
    var value = $(this).val();
        if(value == "0"){
            $("#hilang").html("<input name='' value='tes' type='text'  />");
        }
        else{
            $("#hilang").html("");
        }
}); 
}); 
</script>

HTML 代码:

<input id="macam"  type="radio" name="radio" value="1" checked></input>
<input id="macam"  type="radio" name="radio" value="0"></input>
    <div id="hilang"></div>

【问题讨论】:

  • 你是否包含了 jQuery 库?

标签: html ajax forms radio


【解决方案1】:

不要重复使用 ID

JS

$(document).ready(function(){
$('input[name="radio"]').click( function() {
    var value = $(this).val();
        if(value == "0"){
            $("#hilang").html("<input name='' value='tes' type='text'  />");
        }
        else{
            $("#hilang").html("");
        }
}); 
}); 

HTML

<input id="macam1"  type="radio" name="radio" value="1" checked></input>
<input id="macam0"  type="radio" name="radio" value="0"></input>
<div id="hilang"></div>

【讨论】:

  • 代码运行良好。 jsfiddle.net/kfvuhhno 包括 jquery 吗?您的问题是 ajax,但您没有显示 ajax 代码。
  • 天啊...非常感谢:*
【解决方案2】:

跳出的第一个问题是您有两个相同的 ID。声明你的两个收音机 class="macam" 而不是 id="macam" 并使用 $(".macam") 来选择这些类而不是 $("#.maca")

改用这个

var value = $('input[name="radio"]:checked').val();

使用这个

<script type="text/javascript">
  $(document).ready(function(){
   $('.macam').click( function() {
    var value = $('input[name="radio"]:checked').val();
    if(value === "0"){
        $("#hilang").html("<input name='' value='tes' type='text'  />");
    }
    else{
        $("#hilang").html("");
    }
   }); 
 }); 
</script>

<input class="macam"  type="radio" name="radio" value="1" checked></input>
<input class="macam"  type="radio" name="radio" value="0"></input>
    <div id="hilang"></div>

【讨论】:

  • 请给我完整的脚本,我很困惑..帮助我:'(
【解决方案3】:

ID 应该是唯一的。将其更改为类。

HTML

<input class="macam"  type="radio" name="radio" value="1" checked></input>
 <input class="macam"  type="radio" name="radio" value="0"></input>
<div id="hilang"></div>

jQuery

$('.macam').click( function() {
var value = $(this).val();
    if(value == 0){
        $("#hilang").html("<input name='' value='tes' type='text'  />");
    }
    else{
        $("#hilang").html("");
    }
}); 

【讨论】:

  • value == "0" 仍然可以工作,因为它会尝试将其转换为 int。 value === "0" 不会起作用
  • 我的立场是正确的。返回的值是一个字符串....所以 (value === "0") 有效,但 (value === 0) 无效
猜你喜欢
  • 2016-06-17
  • 1970-01-01
  • 1970-01-01
  • 2017-07-24
  • 1970-01-01
  • 2011-09-22
  • 1970-01-01
相关资源
最近更新 更多