Dhanush
Dhanush

Reputation: 49

How to print the name of corresponding value of select tag?

We can print the value of select option using document.querySelector(".choose").value; but I need the name of it's corresponding value Ex: If the value of select is "VAR CHAR" but you need to print the name as text

<select name='choose' class='choose'>
  <option name='text'>VAR CHAR</option>
  <option name='number'>NUMBER</option>
  <option name='radio'>RADIO</option>
  <option name='checkbox'>CHECK BOX</option>
  <option name='email'>EMAIL</option>
  <option name='file'>FILE</option>
  <option name='date'>DATE</option>
  <option name='password'>PASSWORD</option>
  <option name='range'>RANGE</option>
  <option name='tel'>TELEPHONE</option>
  <option name='submit'>SUBMIT</option>
  <option name='button'>BUTTON</option>
  <option name='reset'>RESET</option>
</select>

Upvotes: 0

Views: 181

Answers (3)

Mustafa Poya
Mustafa Poya

Reputation: 3027

You select element has a class by the name of "choose" and you can use the following code which was written by jquery.

$('.choose').on('change', function() {
    var selectedOption = $(this).find('option:selected');
    name = selectedOption.attr('name');
});

Upvotes: 1

shotgun02
shotgun02

Reputation: 784

just tried something..

document.querySelector('.choose').selectedOptions[0].getAttribute('name');

Upvotes: 1

Jiakan Wang
Jiakan Wang

Reputation: 1

Looks like you know how to select the element already. Now all you need to do is

var name = element.getAttribute("name");

and then print it.

Upvotes: 0

Related Questions