单选按钮名称和值的if条件

jQuery if condition for radio button name and value

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

我有一个单选按钮,像

<input type="radio" name="user-type" value="Store">
<input type="radio" name="user-type" value="Brand">

我试着写jQuery脚本像

if($("input[name=user-type]:checked").val()) == "Brand"){
     $(".showstore").hide();
     $(".showbrand").show();
}

和also tried

if($("input[name=user-type]:checked").val()) == "Brand").click(function(){
       $(".showstore").hide();
     $(".showbrand").show();
});

和also tried

if ( $("input[name=user-type]:radio").val() == "Brand"){
     $(".showstore").hide();
     $(".showbrand").show();
}

这些都不起作用,任何纠正都是赞赏的。谢谢。

Update1

I tried in this way and this hide both

if($("input[name=user-type]:checked").val() == "Brand"){
     $(".showstore").hide();
     $(".showbrand").show();
}
else if($("input[name=user-type]:checked").val() == "Store"){
     $(".showstore").show();
     $(".showbrand").hide();
}

试试下面的代码-它基本上监听name=user-type上的click,并根据单击哪个单选按钮进行切换。

$(function () {
    $('.showstore').hide();
    $('.showbrand').hide();
    $("input[name=user-type]:radio").click(function () {
        if ($('input[name=user-type]:checked').val() == "Brand") {
            $('.showstore').hide();
            $('.showbrand').show();
        } else if ($('input[name=user-type]:checked').val() == "Store") {
            $('.showstore').show();
            $('.showbrand').hide();
        }
    });
});

一个工作小提琴:http://jsfiddle.net/FpUSH/1/

这是简短的

$('input:radio').change(
function(){
    if($(this).val() == 'Store'){
        $('.showbrand').hide();
        $('.showstore').show();
    }
    else{
        $('.showstore').hide();
        $('.showbrand').show();
    }
}
);  

有一些语法错误:

$("input[name='user-type']:checked").each(function(){
    if($(this).val() == "Brand"){
        $(".showstore").hide();
        $(".showbrand").show();
    }
});

您需要这样检查:

if($('input[name="user-type"]:checked').val() === "Brand")
{
       alert("Test");
       // do something here
}

工作小提琴示例

您有一个语法错误,您错误地关闭了parenthesis属于if语句

if($("input[name=user-type]:checked").val() == "Brand"){
     $(".showstore").hide();
     $(".showbrand").show();
}

演示
$("input[name=user-type]").change(function(){
  $(".showstore").toggle(this.value === "Store"); 
  $(".showbrand").toggle(this.value === "Brand"); 
});
<<h2>新演示/h2>

demo try this,

if(jQuery("input:radio[name='user-type']:checked").val()=="Brand"){
   //do your stuff
}

显然@karthikr有一个很好的和实用的方法。

这里有一个是/否单选按钮的例子,如果你想禁用一个元素取决于单选按钮的选择

$("input[name=button-name]:radio").click(function () {
    if ($('input[name=input-radio-name]:checked').val() == "Yes") {
        $( "element" ).removeClass('btn-display-none');
        $( "element" ).prop('disabled', false);
    } else {
        $( "element" ).addClass('btn-display-none'));
        $( "element" ).prop('disabled', true);
    }
});

来源:用于自己的项目