1

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);
    }
});
Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95

3 Answers3

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()

adeneo
  • 312,895
  • 29
  • 395
  • 388
1

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);
Adeel Siddiqui
  • 210
  • 1
  • 4
0

$(".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"/>
Farhad Bagherlo
  • 6,725
  • 3
  • 25
  • 47
  • Can you please tell us what improvement you have done in OP code? – Mohammad Usman Jul 20 '17 at 10:55
  • Firstly, code only answers are useless. The idea of this site is to educate, which simply dumping code does not do. Secondly, how does this achieve the goal of making the code shorter? It's *longer* than the original. Lastly, @adeneo already nailed this one 10 minutes before you even answered... – Rory McCrossan Jul 20 '17 at 10:58