I have a simple drop down and I want to have it so that if the user selects Have a Baby the message changes to Have a Baby, but for any other selection. The message stays the same (nothing), but this isn't working. Can someone please help. Please play with my jsfiddle.
http://jsfiddle.net/Z9YJR/
Here is the html
<select id="leave">
<option value="5">Get Married</option>
<option onchange="changeMessage()" value="100">Have a Baby</option>
<option value="90">Adopt a Child</option>
<option value="15">Retire</option>
<option value="15">Military Leave</option>
<option value="15">Medical Leave</option>
</select>
<div id="message"></div>
Here is the js
function changeMessage() {
document.getElementById("message").innerHTML = "Having a Baby!!";
}
Something like this should do the trick
<select id="leave" onchange="leaveChange()">
<option value="5">Get Married</option>
<option value="100">Have a Baby</option>
<option value="90">Adopt a Child</option>
<option value="15">Retire</option>
<option value="15">Military Leave</option>
<option value="15">Medical Leave</option>
</select>
<div id="message"></div>
Javascript
function leaveChange() {
if (document.getElementById("leave").value != "100"){
document.getElementById("message").innerHTML = "Common message";
}
else{
document.getElementById("message").innerHTML = "Having a Baby!!";
}
}
jsFiddle Demo
A shorter version and more general could be
HTML
<select id="leave" onchange="leaveChange(this)">
<option value="5">Get Married</option>
<option value="100">Have a Baby</option>
<option value="90">Adopt a Child</option>
<option value="15">Retire</option>
<option value="15">Military Leave</option>
<option value="15">Medical Leave</option>
</select>
Javascript
function leaveChange(control) {
var msg = control.value == "100" ? "Having a Baby!!" : "Common message";
document.getElementById("message").innerHTML = msg;
}
It does not work because your script in JSFiddle is running inside it's own scope (see the "OnLoad" drop down on the left?).
One way around this is to bind your event handler in javascript (where it should be):
document.getElementById('optionID').onchange = function () {
document.getElementById("message").innerHTML = "Having a Baby!!";
};
Another way is to modify your code for the fiddle environment and explicitly declare your function as global so it can be found by your inline event handler:
window.changeMessage() {
document.getElementById("message").innerHTML = "Having a Baby!!";
};
easy
<script>
jQuery.noConflict()(document).ready(function() {
$('#hide').css('display','none');
$('#plano').change(function(){
if(document.getElementById('plano').value == 1){
$('#hide').show('slow');
}else
if(document.getElementById('plano').value == 0){
$('#hide').hide('slow');
}else
if(document.getElementById('plano').value == 0){
$('#hide').css('display','none');
}
});
$('#plano').change();
});
</script>
this example shows and hides the div if selected in combobox some specific value