问题
I have a drop-down menu with a list of school subjects in it, the last option is "Add New Subject" so when the user selects that option, I need a text box to appear.
My HTML form looks like this: (I have only included the relevant bits, there is a bit more stuff on it.
<form method="post" action="createQuestion.php" name="cq"> <select name="subject" id="subject"> <option value="biology">Biology</option> <option value="maths">Maths</option> <option value="economics">Economics</option> <option value="newSub" <?php if($subject == "newSub1") { echo "SELECTED"; } ?>> Add New Subject </option> </select> <input type="text" name="newSubtxt" ID="newSubtxt" style="visibility:hidden"> </form>
I have spent ages trying to get this to work with javascript, and I just can't get it to work at all.
This is the js I wrote, but doesn't work
function addSubject(){
newSub = document.getElementById('newSub').name
selectedSubject = document.getElementById('subject').value
if (selectedSubject == newSub){
document.getElementById(newSubtxt).style.display = 'block';
}}
I would be so grateful if someone could help me out with the javascript, so that it will work. Thanks in advance :)
回答1:
Change your invisible input to:
<input type="text" name="newSubtxt" id="newSubtxt" style="display: none" />
and your js:
function addSubject() {
var selectedSubject = document.getElementById('subject').value;
if (selectedSubject == 'newSub') {
document.getElementById('newSubtxt').style.display = 'block';
}
}
Also see my jsfiddle.
回答2:
Change the style of textbox with
<input type="text" name="newSubtxt" ID="newSubtxt" style='display:none;'>
I have used jQuery (javascript library) to solve your problem.
$(document).ready(function () {
$('#subject').change(function (){
if($('#subject').val()=='newSub')
$('#newSubtxt').show();
else
$('#newSubtxt').hide();
});
});
See my jsfiddle
来源:https://stackoverflow.com/questions/7940235/how-to-change-a-text-box-to-visible-depending-on-what-item-is-selected-in-a-drop