Reputation: 1228
I am trying to implement the following: change the CSS property visibility:
of an<input>
tag using a javascript function when the user selects an <option>
from a <select>
.
Here's my code so far:
main.js:
function change_css(){
if( $('#billing_method').val() == "CLICK THIS TO CHANGE VISIBILITY" ){
$('#the_input').css({ 'visibility': 'visible' });
}else{
$('#the_input').css({ 'visibility': 'hidden' });
}
}
page.html:
<select name="billing_method">
<option onClick='change_css()'>-- SELECT AN OPTION --></option>
<option onClick='change_css()'>CLICK THIS TO CHANGE VISIBILITY</option>
</select>
<input type="text" id="the_input" value="" placeholder="I AM THE INPUT" />
styles.css:
#the_input{
visibility: hidden;
}
See jsfiddle
Upvotes: 1
Views: 144
Reputation: 913
Save yourself some jQuery and write it in plain JavaScript:
var select = document.querySelector('select[name=billing_method]');
var input = document.querySelector('#the_input');
var changeCSS = function () {
var val = this.options[this.selectedIndex].value;
if (val.toLowerCase() === 'click this to change visibility') {
input.style.visibility = 'visible';
} else {
input.style.visibility = 'hidden';
}
};
select.onchange = changeCSS;
http://jsfiddle.net/toddmotto/UNL4k
Upvotes: 1
Reputation: 57095
$(document).ready(function () {
$('select[name="billing_method"]').change(function () {
var that = $(this);
$('#the_input').css('visibility', function () {
return (that.find('option:selected').text() === "CLICK THIS TO CHANGE VISIBILITY") ? 'visible' : 'hidden';
});
});
});
Upvotes: 0
Reputation: 97707
You have two issues
.
<select onchange='change_css()' name="billing_method" id="billing_method">
<option>-- SELECT AN OPTION --></option>
<optio>CLICK THIS TO CHANGE VISIBILITY</option>
</select>
Upvotes: 2
Reputation: 21769
I see you are using jQuery, this could be much simplier:
$('#billing_method').change(function() {
if ($(this).val('CLICK THIS TO CHANGE VISIBILITY')) {
//first option:
$('#the_input').show();
//second option:
$('#the_input').css('visibility', 'visible');
} else {
//first option:
$('#the_input').hide();
//second option:
$('#the_input').css('visibility', 'hidden');
}
});
Upvotes: 0
Reputation: 29
Option does not respond to onClick
. You have to use the change
event from select
$('select').change(function(){
if( $(this).val() == "CLICK THIS TO CHANGE VISIBILITY" ){
$('#the_input').css({ 'visibility': 'visible' });
}else{
$('#the_input').css({ 'visibility': 'hidden' });
}
});
and remove the on click
Upvotes: 2