Godfryd Godfryd - 2 months ago 8
HTML Question

How to pass JavaScript function result to html when using onchange?

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);
}

Answer

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.