简体   繁体   中英

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}} ??

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]

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM