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 thedisabled
property.. – Phylogenesis Commented Jul 20, 2017 at 10:45
3 Answers
Reset to default 12You 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
评论列表(0条)