Rafi Ki
Rafi Ki

Reputation: 131

extract text from select button using JavaScript

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

Answers (2)

Ankit Agarwal
Ankit Agarwal

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

A. Bandtock
A. Bandtock

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

Related Questions