简体   繁体   中英

jquery - next() won't work but siblings() will

I'm trying to create a form which has multiple sections with 'yes/no' radio buttons and a textarea. When the page loads, the textareas are disabled and all the 'no' radio buttons are checked by default. I'm trying to get it so that once the user selects a 'yes' radio button, the disabled attribute is removed from the relevant textarea.

I'm trying to this using next('textarea'), but this doesn't seem to work. What's weird is that siblings does work (using the same selector) but obviously it targets all the textareas rather than just the relevant one.

Any ideas?

Here's my code (simplified):

<input type="radio" value="Yes" name="rdo" />Yes
<input type="radio" value="No" name="rdo" checked/>No
<br />
<textarea rows="4" cols="50" disabled></textarea>

$(document).ready(function(){
    $(":radio[value=Yes]").click(function(){
        if ($(this).attr('checked','true')) {
            $(this).next('textarea').removeAttr('disabled');
        }
    });
});

See JSFiddle: http://jsfiddle.net/AThomas92/Ry2fX/

Cheers,

Ash

As stated by jQuery doc :

.next()

Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.

So the next of $(":radio[value=Yes]") is input no.

Here 2 other options (1 as been already stated) :

Yeah that is an obvious result, since .next('textarea') will only search for the next sibling immediately after to the current element with the supplied selector. But unlike .next() , .siblings() will search for all the siblings around the current element by the supplied selector and return the matched one.

You need to wrap the input so it can work

<div class="wrapper">
   <input type="radio" value="Yes" name="rdo" />Yes
   <input type="radio" value="No" name="rdo" checked/>No
   <br />
   <textarea rows="4" cols="50" disabled></textarea>
</div>
$(document).ready(function(){
    $(":radio[value=Yes]").click(function(){
        if ($(this).attr('checked','true')) {
            $('textarea', $(this).parent()).removeAttr('disabled');
        }
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM