How do I make a input field active after I tick a checkbox, using JQuery?
-
14-11-2019 - |
Pregunta
I have this code I wrote but it doesnt seem to be working, see below:
$('#Reserve, #BuyItNowPrice, #featureplate').attr('disabled','disabled');
$('.fake-fieldset .fake-input').css({'background-color':'#e1e1e1'});
$('.enable').click(function(){
if($('.enable:checked')){
$(this).closest('input').removeAttr('disabled');
}
else{
$(this).closest('input').attr('disabled','disabled');
}
});
This HTML structure is repeated 3 times in my code, see below
<strong><input type="checkbox" class="enable" /> Specify Buy It Now Price</strong>
<div class="fake-fieldset">
<div class="fake-input">
<span>£ </span>
<input type="text" id="BuyItNowPrice" name="BuyItNowPrice" value="" />
</div>
</div>
What I'd like to happen is when I check .enable
the closest input should become active so the user can type a value
Any help would be greatly appreciated, Thanks
Solución
One thing to change: I don't think you can do
if($('.enable:checked'))
as a selector always returns a jQuery object (rather than true or false); instead try
if($('.enable).is(:checked'))
Second, since closest
is looking for an ancestor, you need a better way to connect the checkbox with the related input
; maybe put them both into a wrapper div? Then you can go up to the parent (the wrapper) and do a find from there.
Otros consejos
Jquery's closest looks for an ancestor element which the input
you are trying to change is not.
You probably need to change your HTML a bit to make this work. One suggestion is to create a parent element to wrap both elements and add a class to the 2nd input. Something like this:
<div class='enablearea'>
<strong><input type="checkbox" class="enable" /> Specify Buy It Now Price</strong>
<div class="fake-fieldset">
<div class="fake-input">
<span>£ </span>
<input type="text" id="BuyItNowPrice" name="BuyItNowPrice" value="" class='enablechange' />
</div>
</div>
</div>
Then you can find that 2nd input like this:
$(this).parent('.enablearea').find('.enablechange')