单选按钮选中时会打开文本框,但不会'未选中时不要关闭它

Radio button opens textbox when checked, but won't close it when unchecked

本文关键字:文本 单选按钮      更新时间:2023-09-26

我正在尝试创建一个动态表单,用户可以选择上传和图像或嵌入youtube剪辑。

我已经尝试过使用无线电输入:

<script type="text/javascript">
$(".youtube").change(function () {
    //check if radio button is checked.
    if (this.checked && this.value === "youtube") {
        //show a text box 'embedbode' when radio 'youtube' is checked
        $("#embedcode").show();
    } else if (!this.checked && this.value === "image"){
        //hide the text box when 'image' is checked
        $("#embedcode").hide();
    }
});
</script>

这是html:

<input type="radio" value="image" id="type" name="type" checked='checked' autocomplete="off" />
<label>Image</label>
<input type="radio" value="youtube" id="type" name="type" class="youtube" />
<label>Video</label>
<input id="embedcode" placeholder="embed code" name="embedcode" type="text"/>

默认情况下,单选按钮image处于选中状态。当我点击视频单选按钮时,会打开一个文本框,我可以在其中输入视频的嵌入代码。然而,当我点击返回image时,如果我改变主意要上传什么,嵌入文本框仍然存在。我看了JS,看不出哪里出了问题。我尝试调整术语并添加一个额外的else if,但当我单击返回图像时,文本框不会隐藏。我哪里错了?

<script type="text/javascript">
    $(document).ready(function(){
          $("#embedcode").hide();
          $("input[name='type']").change(function () {
               if($(this).val() == "youtube")
                    $("#embedcode").show();
               else
                    $("#embedcode").hide();
          });
    });
</script>

当他们检查另一个时,你会这样做(在这里修复你的代码,成为jQuery):

 if (!$(this).prop('checked') && $(this).val() === "image")

现在已检查。。。所以它不会隐藏它。你所需要做的就是检查值,因为他们点击了它,它是一个收音机,所以它总是会被检查的。

if ($(this).val() === "image")

一个更简单的方法就是:

$(".youtube").change(function () {
    $("#embedcode").toggle($(this).val() == "youtube");
});
<script type="text/javascript">
$(document).ready(function(){
    $("#embedcode").hide();
    $("input:radio").change(function () {
        if($(this).val() == "youtube")
        {
            $("#embedcode").show();
        }
        else
        {
            $("#embedcode").hide();
        }
    });
});
</script>