Selecting the next tag using jQuery
I have a select
and 2 td
tags as below.
<select name="accesslevel"><option value="A1">A1</option>
<option value="A2">A2</option></select>
<td id="Level3">
<td id="Level4">
I need to hide the td
with Level3 id if A1 is selected in the select and show the td with Level4 id, and vice-versa.
The combination is repeated many times in the ht开发者_如何转开发ml so, i have to find the next td
's only after the select
tag using jQuery.
Can anyone help?
Assuming your Select is also inside a TD of the same TR
$("#accesslevel").change(function(){ //give an id to your select box
if(condition){
$(this).parent().nextAll("#Level3").hide();
$(this).parent().nextAll("#Level4").show();
}
});
This just gives you an idea. You can obviously optimize the code by storing the parent in a variable and then searching for other nodes.
The idea is to find the parent TD and then use nextAll to find the other TDs. You could also find the parent row TR and then use TR.children("#Level3")
$(document).ready(function(){
$("select[name='accesslevel']").change(function(){
if($(this).val()=="A1")
{
$(this).parent().next().find("td[id='Level3']").show();
$(this).parent().next().find("td[id='Level4']").hide();
}
if($(this).val()=="A2")
{
$(this).parent().next().find("td[id='Level3']").hide();
$(this).parent().next().find("td[id='Level4']").show();
}
});
});
See a working example here
Without seeing all your markup, I wonder if your <select>
should be wrapped in a <td>
?
<td><select>...</select></td>
<td class="level3">
<td class="level4">
In which case, you could do something like
$('select#someId').change(function() {
var $nextTds = $(this).parents('td:first').nextAll('td:lt(2)');
//manipulate $nextTds
]
If your <td>
elements have IDs, this is not 'repeated' throughout the code as an ID is unique to every element - the :lt(2)
filter will only retrieve td
elements of index 0
and 1
.
精彩评论