[英]javascript dropdown menu onclick
I've been working at this for a while now, but don't understand what's wrong with my code. 我已经在这方面工作了一段时间,但不明白我的代码有什么问题。 I'm sure it's something simple - it always is!
我确信这很简单 - 它总是如此!
Basically, I have a drop down menu, with some options. 基本上,我有一个下拉菜单,有一些选项。 I want it to go to a web page when the third option, plumber, is selected.
我希望它在选择第三个选项管道工时进入网页。 When any of the others are clicked, nothing should happen.
点击其他任何一个时,什么都不应该发生。
My code so far is: 到目前为止我的代码是:
<select id = 'search'>
<option value="1">Carpenter</option>
<option value="2">Electrician</option>
<option value="3">Plumber</option>
<option value="4">Tiler</option>
<option value="5">Boiler Installation</option>
</select>
Go 走
And my javascript is: 我的javascript是:
<script>
function go_button {
if (search.value=="3") {
location="search_results.htm"
}
}
</script>
But it's not working. 但它不起作用。 Could someone tell me what's wrong?
有人能告诉我什么是错的吗?
Thanks. 谢谢。
C. C。
You can either put a change event on your control via script or add it directly to your control.. 您可以通过脚本在控件上添加更改事件 ,也可以将其直接添加到控件中。
Direct Method: 直接法:
<select id="search" onChange="OnSelectedIndexChange()">
This is the function you need to put in your Script: 这是您需要在脚本中添加的功能:
//function for changed selection
function OnSelectedIndexChange()
{
if (document.getElementById('search').value == "3"){
location.href="search_results.htm";
}
}
Add Change event using Script (either JavaScript or JQuery): 使用脚本(JavaScript或JQuery)添加更改事件:
I suggest JQuery for doing so (the onSelectedIndexChange function is obsolete here) 我建议JQuery这样做(onSelectedIndexChange函数在这里已经过时了)
$('#search').change( function() {
if(this.val() == "3"){
location.href="search_results.htm";
}
});
If you don't want to use JQuery just add the following code: 如果您不想使用JQuery,只需添加以下代码:
var yourdropdown = document.getElementById('search');
yourdropdown.Attributes.Add("onChange", "return OnSelectedIndexChange();")
You need to tell javascript which element it is you are interested in. 你需要告诉javascript你感兴趣的是哪个元素。
Use getElementById("search")
to return the element then you can look into getting its value. 使用
getElementById("search")
返回元素,然后您可以查看获取其值。
<select id="search">
I think, there are to many spaces. 我想,有很多空间。
getElementById("search").value
I have not used this in a while, but is not it ... 我有一段时间没用过这个,但不是吗......
location.href = "search_results.htm";
Somewhat like this gives you access to the object. 有点像这样可以访问该对象。 And last but not least, you need to associate your function "go_button" with an event of the drop down box, something like this:
最后但并非最不重要的是,您需要将您的函数“go_button”与下拉框的事件相关联,如下所示:
<select id="search" onClick="go_button();">
我认为 - 如果可能的话 - 使用jQuery或其他js框架,都有内置的select和其他html / dom插件和方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.