Godfryd
Godfryd

Reputation: 479

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

Upvotes: 1

Views: 35

Answers (2)

Aleksandar Đokić
Aleksandar Đokić

Reputation: 2343

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>

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337580

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.

Upvotes: 1

Related Questions