我正在尝试实现以下内容:当用户从visibility:
中选择<input>
时,使用javascript函数更改<option>
代码的CSS属性<select>
。
到目前为止,这是我的代码:
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;
}
请参阅jsfiddle
答案 0 :(得分:2)
选项不响应onClick
。您必须使用change
select
事件
$('select').change(function(){
if( $(this).val() == "CLICK THIS TO CHANGE VISIBILITY" ){
$('#the_input').css({ 'visibility': 'visible' });
}else{
$('#the_input').css({ 'visibility': 'hidden' });
}
});
并删除点击
答案 1 :(得分:2)
你有两个问题
<select onchange='change_css()' name="billing_method" id="billing_method">
<option>-- SELECT AN OPTION --></option>
<optio>CLICK THIS TO CHANGE VISIBILITY</option>
</select>
答案 2 :(得分:1)
保存一些jQuery并用纯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;
答案 3 :(得分:0)
我看到你正在使用jQuery,这可能会简单得多:
$('#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');
}
});
答案 4 :(得分:0)
$(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';
});
});
});
<小时/> 参考