user3633186
user3633186

Reputation: 1540

Text of select Menu inside of a span

I have a select dropdown

   <select id="select_domain">
   <option value="1">Jon Doe</option>
   <option value="2">Max Mustermann</option>
   </select>

And a span

<span id="domain"></span>

Inside this span there should be the text of the selected option of my select menu.

How can i do this with jQuery ?

Upvotes: 1

Views: 102

Answers (5)

Roger
Roger

Reputation: 3256

Here is an explained example, along with the extra effect of triggering the event on page load.

/*Binds a change event to your select*/
$('#select_domain').change(function () {
    /*sets the text to the selected option of THIS select box*/
    set_text($('option:selected', this).text());
});
/*Creates a function to set the text of domain
This function can be used elsewhere as well*/
function set_text(text){
    $('#domain').text(text);
}

/*This triggers the function and sets the text 
to the currently selected text on page load*/
set_text($('#select_domain option:selected').text());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select_domain">
    <option value="1">Jon Doe</option>
    <option value="2">Max Mustermann</option>
</select>
<span id="domain"></span>

Upvotes: 0

Lucas
Lucas

Reputation: 479

The "when" is kind of important, but if you want your span to update when you select a new value, use something like this:

    $( "#select_domain" ).change(function() {
       $('#domain').html($('select_domain').val());
    });

If you want the default value to show in the span on load, you can do that with your server side code or add this line to your generic function:

    $('#domain').html($('select_domain').val());

Upvotes: 2

Magicprog.fr
Magicprog.fr

Reputation: 4100

You can use to get the text :

$("#select_domain option:selected").text();

and to get the value :

$("#select_domain").val()

JSFiddle: http://jsfiddle.net/ghorg12110/eqd22pca/1/

Upvotes: 2

mrciga
mrciga

Reputation: 57

Please check this answer,

$(function() {
    $('#select_domain').change(function(){
        $("#domain").text($("#select_domain option:selected").text());
    });
});

Upvotes: 2

roshan
roshan

Reputation: 2510

May be this is what you expected:

 $("#select_domain").on("change", function() {
   $("#domain").text($("#select_domain option:selected").text());
 })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="select_domain">
  <option value="1">Jon Doe</option>
  <option value="2">Max Mustermann</option>
</select>
<span id="domain"></span>

Upvotes: 2

Related Questions