jQuery accessing form array
I have a php form and I want to display or hide certain fields dependant on what I select in a drop down. I have code below which works:
$(document).ready(function() {
$('div.pupname').hide();
$('div.pupnid').hide();
if ($("#perpetrator").val == "1") {
$('div.pupname').hide();
$('div.pupid').show();
else {
$('div.pupid').hide();
$('div.pupname').show();
}
$("#perpetrator").change(function() {
if ($("#perpetrator").val() == "1") {
$('div.pupname').hide();
$('div.pupid').show();
else {
$('div.pupid').hide();
$('div.pupname').show();
}
});
});
I now want to have a multi row block which I am generating using php so I can generate the divs as pupid1, pupid2 etc. and the field $m_perpetrator
as an array. I've tried a few ways of accessing the array but can't get anything to work. I thought he following might be along the correct lines for accessing the elements of the array but it does nothing.
if ($("#m_perpetrator[1]").val == "1") {
$('div.pupname1').show();
$('div.pupid1').hide();
}
else {
$('div.pupid1').show();
$('div.pupname1').hide();
}
Added
Here is a snippet of the HTML
<td><select name="m_perpetrator[1]" id="m_pe开发者_如何学Gorpetrator[1]">
<option value="1">Current</option>
<option value="2" selected>Former</option>
<option value="3">Parent/Carer</option>
</select>
</td>
<td>Name</td>
<td>
<div class="pupname1">
<input type="text" size=60 name="m_pupil_name[1]" value="JOHN SMITH">
</div>
<div class="pupid1">
<select name="m_pupil_id[1]" onchange="getXtras(this)">
<option value="">Select .....</option>
So basically this is a multi row form and on each row if Current is selected then I want to display pupil_id if anything else is selected then I want to display pupil name. For processing the input I run round the array m_perpetrator[] using php Jim
Not completely sure what you need. Do you have multiple elements with the same id m_perpetrator?
Use class instead you should do it this way
if ($($(".m_perpetrator")[1]).val() == "1") {
$('div.pupname1').show();
$('div.pupid1').hide();
}
else {
$('div.pupid1').show();
$('div.pupname1').hide();
}
Otherwise what is m_perpetrator in html?
You can't use "[" or "]" in the id attribute. I'd suggest you output a list element like this:
<ul id="whatevers">
<li><input name="whatever1" /></li>
<li><input name="whatever2" /></li>
<li><input name="whatever3" /></li>
<ul>
You can then access them with jquery like this:
var ws = $("#whatevers input");
for(var i=0; i< ws.length; ++i){
ws.eq(i).doSomething();
}
精彩评论