-2

I have this code:

JS

 var a = document.getElementById("quantity");
   var quantity = a.value;

HTML

<select id="quantity" name=''>
  <option title='Option 2' value='2 people'>2 people</option>
  <option title='Option 3' value='3 people'>3 people</option>
  <option title='Option 4' value='4 people'>4 people</option>
  <option title='Option 3' value='5 people'>5 people</option>
  <option title='Option 4' value='6 people'>6 people</option>
</select>

I can't change the HTML only the JS. How do I get it to output the first char, so what I am actually getting out is a number (either 2,3,4,5 or 6).

I tried this but it broke the script:

var a = document.getElementById("quantity");
var quantity = a.substring(0,1);
Jimmy
  • 12,087
  • 28
  • 102
  • 192
  • 4
    Possible duplicate of [How to get first character of string?](https://stackoverflow.com/questions/3427132/how-to-get-first-character-of-string) – WillardSolutions Jan 31 '18 at 19:55
  • 1
    because you are referencing the element! Look how you do `quantity` in the first bock vs the last. – epascarello Jan 31 '18 at 19:56
  • @epascarello I don't really know what that means :( – Jimmy Jan 31 '18 at 19:57
  • Why not just make the value the number without the string people? Seems like that would make more sense. – epascarello Jan 31 '18 at 19:57
  • The question isn't really how to get the first letter, you have that part right. The question should be how do I get the value of the selected item. – Herohtar Jan 31 '18 at 19:57
  • You do not see the difference between `var quantity = a.value;` vs `var quantity = a.substring(0,1);` – epascarello Jan 31 '18 at 19:58
  • Possible duplicate of [Get selected value in dropdown list using JavaScript?](https://stackoverflow.com/questions/1085801/get-selected-value-in-dropdown-list-using-javascript) – Herohtar Jan 31 '18 at 19:58

2 Answers2

4

You were close. You want to use substring() with value:

var a = document.getElementById("quantity");
a.addEventListener("change", function() {
  var quantity = a.value.substring(0, 1);
  console.log(quantity);
});
<select id="quantity" name=''>
  <option title='Option 2' value='2 people'>2 people</option>
  <option title='Option 3' value='3 people'>3 people</option>
  <option title='Option 4' value='4 people'>4 people</option>
  <option title='Option 3' value='5 people'>5 people</option>
  <option title='Option 4' value='6 people'>6 people</option>
</select>
j08691
  • 204,283
  • 31
  • 260
  • 272
1

A slightly more robust and extensible solution than j08691's answer would be to use a regex to grab the first number in the value:

var a = document.getElementById("quantity");
var pattern = new RegExp(/([0-9]+)\s.*/);
a.addEventListener("change", function() {
  var quantity = pattern.exec(a.value)[1];
  console.log(quantity)
});

This would account for the html changing to allow for 10+ people.

Figgynewts
  • 51
  • 2