Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
146
rated 0 times [  149] [ 3]  / answers: 1 / hits: 18941  / 11 Years ago, wed, may 29, 2013, 12:00:00

I am trying to create a small reusable function that will, when checked, disable a text field and insert a default value of '160', and when unchecked, enable the field and remove the value. I have it mostly finished but the unchecking part is throwing me off.



$('#chkIsTeamLead').change(function(){


if ($('#chkIsTeamLead').checked = true){
$('#txtNumHours').val('160').attr('disabled', 'disabled');
console.log('checked');
}

if ($('#chkIsTeamLead').checked = false){
$('#txtNumHours').val('').removeAttr('disabled');
console.log('unchecked');
}

});


I had it setup as a reusable function with arguments passed to it but that was giving me more trouble, I would like the arguments to be checkbox, target, and value preferably
link to my current code: http://codepen.io/AlexBezuska/pen/bwgsA
Thanks for any help you can provide!


More From » jquery

 Answers
36

Working jsFiddle Demo




  1. Use .is(':checked').

  2. You must compare two values with ==.

  3. When you are working with attribute like disabled, it's better to use .prop() method instead of .attr().






$('#chkIsTeamLead').change(function(){
if ($('#chkIsTeamLead').is(':checked') == true){
$('#txtNumHours').val('160').prop('disabled', true);
console.log('checked');
} else {
$('#txtNumHours').val('').prop('disabled', false);
console.log('unchecked');
}
});





References:




  • .attr() - jQuery API Documentation

  • .prop() - jQuery API Documentation

  • .is() - jQuery API Documentation


[#77955] Tuesday, May 28, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
yaquelina

Total Points: 517
Total Questions: 101
Total Answers: 96

Location: Egypt
Member since Tue, Jul 6, 2021
3 Years ago
yaquelina questions
;