javascript - Shorten jQuery if else condition - Stack Overflow

How can we improve following if-else code: $(".rdo_confirm").change(function(){if($(this).v

How can we improve following if-else code:

$(".rdo_confirm").change(function(){  
    if($(this).val() == "Y") {
      $("#btn_save").attr("disabled",false);
    } else {
        $("#btn_save").attr("disabled",true);
    }
});

How can we improve following if-else code:

$(".rdo_confirm").change(function(){  
    if($(this).val() == "Y") {
      $("#btn_save").attr("disabled",false);
    } else {
        $("#btn_save").attr("disabled",true);
    }
});
Share Improve this question edited Jul 20, 2017 at 10:54 Mohammad Usman 39.4k20 gold badges98 silver badges100 bronze badges asked Jul 20, 2017 at 10:43 ioffChanatsananioffChanatsanan 496 bronze badges 2
  • 1 try $("#btn_save").attr("disabled",$(this).val() == "Y"); – Carsten Løvbo Andersen Commented Jul 20, 2017 at 10:43
  • 2 You should use .prop() rather than .attr() for the disabled property.. – Phylogenesis Commented Jul 20, 2017 at 10:45
Add a ment  | 

3 Answers 3

Reset to default 12

You could use the check for the value directly, as it returns a boolean

$(".rdo_confirm").on('change', function(){  
    $("#btn_save").prop("disabled", this.value !== "Y");
});

The check for $(this).val() == "Y" returns either true or false.
It seems you want to pass false if the check returns true, meaning you just negate the check.
Using native javascript it turns out to be something like this.value !== "Y".
As disabled is a property, you also want to use prop()

You can press this conditional code into 1 Line of code into two ways, Have a look:

By using ternary operator:

$(".rdo_confirm").change(function(){  

$(this).val() == "Y")? $("#btn_save").attr("disabled",false):$("#btn_save").attr("disabled",true);

});

OR

By using simple condition:

$(".rdo_confirm").change(function(){  
var cond=(this.value !== "Y");
$(this).val() == "Y")? $("#btn_save").attr("disabled",cond);

$(".rdo_confirm").on('change',function(){  
   $("#btn_save").prop("disabled",!($(this).val()=="Y"));
});
$("#btn_save").on('click',function(){  
   alert("test");
});
span{
padding-right:20px
}
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="rdo_confirm" type="radio" name="rdo_confirm" value="Y"/><span>Yes</span>
<input class="rdo_confirm" type="radio" name="rdo_confirm" value="N"/><span>No</span>
<input id="btn_save" type="button"  value="Click"/>

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745388801a4625563.html

相关推荐

  • javascript - Shorten jQuery if else condition - Stack Overflow

    How can we improve following if-else code: $(".rdo_confirm").change(function(){if($(this).v

    3小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信