Reputation: 35
I am creating a survey that is conducted each year. To make it fast, i want to have a button that will automatically select the answer in a dropdownlist from the previous year's survey (this answer is available as a span in a preceding cell (same row) in a table). Because this table can be hundreds of rows, i can't use specific id/name selectors. What i am trying to do is store the span located before the hyperlink in a variable, and then use that to select an option in the cell following the hyperlink
Jquery:
<script type="text/javascript">
$(function () {
$("[id$='lbCopy']").click(
function () {
var $prevReason = $(this).parent().prev().children().text();
$(this).parent().next().children('select > option:contains("' + $prevReason + '")').prop("selected", true);
})
});
</script>
HTML:
<td>
<span id="ctl00_body_gvBacklog_ctl02_lblPrevYearReason">Recalcitrant RP</span>
</td>
<td>
<a id="ctl00_body_gvBacklog_ctl02_lbCopy">Copy</a>
</td>
<td>
<select name="ctl00$body$gvBacklog$ctl02$ddlReasonNotClosed" id="ctl00_body_gvBacklog_ctl02_ddlReasonNotClosed">
<option value=""></option>
<option value="Contamination Above Standards">Contamination Above Standards</option>
<option value="Recalcitrant RP">Recalcitrant RP</option>
<option value="Remediation Ongoing">Remediation Ongoing</option>
<option value="SMAC Eligible">SMAC Eligible</option>
<option value="SMAC Eligible w/MW Closure">SMAC Eligible w/MW Closure</option>
<option value="SMAC Eligible w/Notice">SMAC Eligible w/Notice</option>
</select>
</td>
For whatever reason this does not work. I get no errors, but the dropdownlist does not get modified. I know my selector is solid, because i can use it to change the option of all dropdowns, just not the adjacent dropdown. Thanks for the help!
Upvotes: 2
Views: 434
Reputation: 359
There are many ways to do it, as for me, I'll try to avoid having variable inside the selector
$(function () {
$("[id$='lbCopy']").click(
function () {
var $prevReason = $(this).parent().prev().children().text();
$(this).parent().next().find('option').filter(function(){
return $(this).html() == $prevReason;
}).prop("selected", true);
})
});
Upvotes: 0
Reputation: 74420
This works with the HTML code of your question:
$(function () {
$("[id$='lbCopy']").click(
function () {
var $prevReason = $(this).prev().text();
$(this).next().find('option:contains("' + $prevReason + '")').prop("selected", true);
})
});
Upvotes: 0
Reputation: 97672
children
only selects elements one level down, you're trying to select descendants so use find
instead.
$(this).parent().next().find('select > option:contains("' + $prevReason + '")').prop("selected", true);
Upvotes: 1