text

special text

Get next item with jquery / js

I have elements like

<div id="myDiv"> <p><input type="checkbox" />text</p> <p>special text</p> <p><input type="checkbox" />text</p> <p><input type="checkbox" />text</p> </div> 

My goal is to check the input fields under the "special text". So I created the variable findText to find the "special text"

 var findText = $("#myDiv:contains('special text')"); 

I check if "special text" exists, and if so, I want the following input elements to be checked. .nextAll() , unfortunately, just gets the following siblings. But how can I name the following elements?

  var findText = $("#myDiv:contains('special text')"); if(findText.length > 0) { findText.nextAll("input").attr("checked",true) } 

Thanks for your time and help.

+4
source share
2 answers

nextAll with find should do this:

 findText.nextAll("p").find("input").attr("checked",true); 

It finds the following paragraphs and their descendants. (Or use children rather than find if the entries are guaranteed to be immediate children of paragraphs.)

... but I think your selector for findText wrong, try:

 var findText = $("#myDiv p:contains('special text')"); // ^^^---- change here 

Putting it all together:

 var findText = $("#myDiv p:contains('special text')"); if(findText.length > 0) { findText.nextAll("p").find("input").attr("checked",true) } 

Live copy

Separately, you can limit the search to only :checkbox using custom :checkbox jQuery:

 var findText = $("#myDiv p:contains('special text')"); if(findText.length > 0) { findText.nextAll("p").find(":checkbox").attr("checked",true) // ^^^^^^^^^^^-- Change here } 

Live copy

+4
source

You can do it as follows:

 $("#myDiv p:contains('special text')").next().children('input').prop('checked',true); 

Example: http://jsfiddle.net/HVSyE/3/

Edit: if you want all the checkboxes after checking the text, then:

 $("#myDiv p:contains('special text')").nextAll('p').children('input').prop('checked',true); 

Example: http://jsfiddle.net/HVSyE/4/

+2
source

All Articles