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);
}
});
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 compress 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.com/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"/>