Reputation: 169
I am using a loop to display data in table and I would like a way to extract two elements specific to which dropdown option the user is clicking on. Firstly I would like to get the text value from within the selected tags. Secondly I would like to get the accompanying url which is the value of the hidden input field (#"lead_path").
Here is my table below. For example I would like a way to save both "/leads/50" and "Agent 456" into separate variables if a user clicked on this dropdown option. For brevity only the first table row in the loop is displayed, but each table row looks exactly the same as the one below.
<td>
<a href="/leads/50">Mellie Price IV</a></td>
<p><input type="hidden" name="lead_path" id="lead_path" value="/leads/50" /></p>
<td>12:24 am 03-09-2015</td>
<td>
<strong>Count:</strong> 0<br />
<strong>Most recent:</strong> $100,000+, Hamillburgh
</td>
<td> 9:24 am 03-16-2015</td>
<input type="hidden" name="agent_id" id="agent_id" value="6" />
<td><select name="agent[lead]" id="agent_lead">
<option value="1">Jeff Manson</option>
<option value="2">Kevin McCarthy</option>
<option value="3">Warsama Gabriel</option>
<option value="4">Chris Sass</option>
<option value="5">Agent123</option>
<option selected="selected" value="6">Agent456</option>
<option value="7">Agent789</option></select>
</td>
</td>
Here is my effort to try to solve this problem. My code gets me the text of the selected option but only displays the first url "/leads/50" and not any of the other ones. Any help would be greatly appreciated. Thanks!
$(document).ready(function() {
$("table").delegate("#agent_lead", "change", function(){
var agent_name = $("option:selected", this).text();
alert($('#lead_path').val());
});
Upvotes: 0
Views: 285
Reputation: 2916
How about the following:
$(document).ready(function () {
$("#agent_lead").on('change',function (event) {
// var id = this.val();
var elem = $('#agent_lead option:selected');
alert(elem.val() + '/' + elem.text()+" "+$('#lead_path').val());
});
});
Here is the jsfiddle https://jsfiddle.net/oqjvw25n/1/
Upvotes: 0
Reputation: 388416
Since you have the same elements in each tr, you should not use IDs like that since ID of an element must be unique, use class to select them.
So remove the id and assign the id values as class then, you need to find the tr
of the changed agent_lead
and find the lead_path
inside it
<input type="hidden" name="lead_path" class="lead_path" value="/leads/50" />
<select name="agent[lead]" class="agent_lead">
then
$("table").delegate(".agent_lead", "change", function () {
var agent_name = $("option:selected", this).text();
alert($(this).closest('tr').find('.lead_path').val());
});
Also it looks like the hidden input is not inside a td
, so move it inside the first td
<td>
<a href="/leads/50">Mellie Price IV</a>
<input type="hidden" name="lead_path" id="lead_path" value="/leads/50" />
</td>
Upvotes: 1