Reputation: 131
Hi guys I am trying using Javascript to extract the name
<div class="dropdown-container">
<form>
<select id="pick-chart" class="form-control pick-chart">
<option value="0">Compare with</option>
{% for i in team_list_pop %}
<option value="{{i.id}}">{{i.first_name}} {{i.last_name}}</option>
{% endfor %}
</select>
</form>
</div>
In my JS I tried :
$(".pick-chart").change(function(e) {
e.preventDefault();
var val = $(this).val();
var name2 = $("option value=" +'"'+val+'"').text();
}
and I got the error :Uncaught Error: Syntax error, unrecognised expression: option value="52"
How could I extract {i.first_name}} ??
Upvotes: 0
Views: 145
Reputation: 30739
You have incorrectly written the code for var name2 = $("option value=" +'"'+val+'"').text();
, replace that with var name2 = $('option[value='+val+']').text();
and it will work. You also have a missing )
error for the change
function so add a closing parenthesis there. For the working snippet I have removed the dynamic option
elements:
$(".pick-chart").change(function(e) {
e.preventDefault();
var val = $(this).val();
var name2 = $('option[value='+val+']').text();
var fName = name2.split(' ')[0];
console.log('first name is ', fName);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dropdown-container">
<form>
<select id="pick-chart" class="form-control pick-chart">
<option value="0">Compare with</option>
<option value="someVal">John Cena</option>
</select>
</form>
</div>
Upvotes: 1
Reputation: 1241
Your JQuery text is wrong, try this:
const name2 = $(`option[value='${val}']`).text();
Then to get just the first name (assuming the first name contains no spaces):
const firstName = name2.split(' ')[0]
Upvotes: 1