Data Science Data Science - 1 month ago 6
HTML Question

Use JS var value only after a button click

I want to show which menu value was selected using JavaScript, like this:

<script>
document.writeln(value);
</script>


Where the JS variable called
value
gets defined by jQuery when a button is clicked:

$('#submit').click(function(){
var value = $('#model').val();

});


The problem being that the code tries to render
value
before it has been created by the button.

I know I can show/hide a
div
based on the button click, but even if the section with
writeln
is hidden it still has the same problem. I also need to be able to change my selection, click submit, and have the value update properly.

Here's a jsFiddle illustrating the problem:

https://jsfiddle.net/f3n7uq14/4/

Answer
<span id="result"></span>
<script>
$('#submit').click(function(){
    var value = $('#model').val();
    $('#result').text(value);
});
</script>
Comments