1

I wonder how do I place user selected option somewhere in HTML as text. I get user selection using JavaScript but I don't know how to pass it back to HTML.

My current code looks like this. HTML:

<select id="profile" onchange="myFunction()">
    <option>One</option>
    <option>Two</option>
    <option>Three</option>                              
</select>

Javascript:

function myFunction() {
    var user_selection = $( "#profile option:selected" ).text();
    alert(user_selection);
}
0

2 Answers 2

1

You can use jQuery create a new element and add it to the DOM like this:

function myFunction() {
    var user_selection = $("#profile option:selected").text();
    $('<div>' + user_selection + '</div>').insertAfter('#profile');
}

Also note that using the on* event attributes is considered outdated. You should use unobtrusive event handlers. As you're already using jQuery, here's how to do that:

$('#profile').change(function() {
    var user_selection = $(this).find('option:selected').text();
    $('<div>' + user_selection + '</div>').insertAfter(this);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="profile">
    <option>One</option>
    <option>Two</option>
    <option>Three</option>                              
</select>

I would suggest you familiarise yourself with the methods jQuery has for creating elements in the DOM around, inside and outside existing elements.

Sign up to request clarification or add additional context in comments.

Comments

1

You can create new div and place it where you want. Just add this as html of that div or append to it, do whatever you like.

function myFunction() {
    var user_selection = $( "#profile option:selected" ).text();
    $('#somediv').html(user_selection);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="profile" onchange="myFunction()">
    <option>One</option>
    <option>Two</option>
    <option>Three</option>                              
</select>
<br/>
<div id = 'somediv'> </div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.