Victor
Victor

Reputation: 136

On Change Getting Option Value

I have a on change for my select statement, which I can access properties like this.value etc.

 $('select[name="ceremony"]').on('change', function(){
                    console.log( this )
    });

I need to somehow get the selected value text. None of the this.options stuff works

One I get it I want to display it like so:

$('.title').html( <here> )

Upvotes: 0

Views: 31

Answers (3)

Ele
Ele

Reputation: 33726

  • You can find the selected option using the selector :selected
  • Use the function $.text to get the visible text.
  • Use the function $.val to get option's value.

$('select').on('change',function(){
  var $selected = $(this).find(":selected");
  $('.title').html("Text: " + $selected.text() + ", Value: " + $selected.val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
  <option value="1">Opt 1</option>
  <option value="2">Opt 2</option>
  <option value="3">Opt 3</option>
</select>
<h1 class="title">
</h1>

Upvotes: 0

this.value gets the current selected option

 $('select[name="ceremony"]').on('change', function(){
                    $('.title').html(this.value)
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<h1 class="title"></h1>

<select name="ceremony">
  <option>hi</option>  
  <option>there</option>

</select>

Upvotes: 0

Zenoo
Zenoo

Reputation: 12880

To get the selected option text (not value), you can use $('option:selected',this).text() :

$('select').on('change',function(){
  console.log($('option:selected',this).text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
  <option>Test</option>
  <option>Test 2</option>
  <option>Test 3</option>
</select>

Upvotes: 1

Related Questions