Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change content of a span based on Drop down selection

I have a select box and a label with a span, I want to replace span content as users change their selection on the drop down box.

<select class="text_select" id="field_6" name="field_6">    
<option value="- Select -">- Select -</option>  
<option value="Option One">Option One</option>  
<option value="Option Two">Option Two</option>  
<option value="Option Three">Option Three</option>  
</select>

<label class="form_field">Your selected <span id="aggregator_name"></span>?</label>

I'm using this script

<script type="text/javascript">
function notEmpty(){

var e = document.getElementById("field_6");
var strUser = e.options[e.selectedIndex].value;
document.getElementById('aggregator_name').innerHTML = strUser;

}
notEmpty()
</script>

Problem with this is, whenever I refresh the page, span is replace with "- Select -" but when I change the dropdown to another option, it doesn't change content of the span? Please help guys.

like image 481
user1074803 Avatar asked Jan 16 '23 03:01

user1074803


1 Answers

You need to call your function from the change event of the drop-down:

document.getElementById("field_6").onchange = notEmpty;

Demo: http://jsfiddle.net/Mj4Vj/

Or, since you've used the "jquery" tag, the following replaces all of your JS:

$(document).ready(function() {
    $("#field_6").change(function() {
        $('#aggregator_name').html($(this).val());
    }).change();
});

Demo: http://jsfiddle.net/Mj4Vj/1/

(Note: if the above is included in a script block that appears after the "field_6" element, e.g., if your script is at the end of the body, then you don't need to wrap the code in a document ready handler.)

like image 184
nnnnnn Avatar answered Jan 18 '23 23:01

nnnnnn