[英]Using javascript and rails to make a drop down menu of links
I am trying to make a drop down menu of links. 我正在尝试制作链接的下拉菜单。 I use the following in rails to generate the drop down menu: 我在rails中使用以下命令来生成下拉菜单:
select("post","id", current_user.admin.post.all.collect {|p| [p.title, post_path(p) ] }, {:include_blank => 'None', :prompt => 'Your Posts'})
As a result of this ruby, the drop down menu looks like this: 由于此红宝石,下拉菜单如下所示:
<select id="post_id" name="post[id]">
<option value="">Your posts</option>
<option value="">None</option>
<option value="/posts/1">Vacations</option>
</select>
And I am trying to get the following javascript to send the user to the correct url: 而且我正在尝试获取以下JavaScript,以将用户发送到正确的网址:
$(document).ready(function() {
$("#post_id").change(function () {
var newwindow = $("#post_id option:selected").attr("id");
window.location.replace(newwindow);
})
});
However, it tries to go to /admins/undefined and comes back with this: 但是,它尝试转到/ admins / undefined并返回以下内容:
Couldn't find Admin with id=undefined 找不到ID =未定义的管理员
Any help would be appreciated! 任何帮助,将不胜感激!
John 约翰
You're getting undefined
because none of your <option>
elements have id
attributes, perhaps you want to look at their values: 由于您的<option>
元素都不具有id
属性,因此您变得undefined
,也许您想查看它们的值:
$("#post_id").change(function () {
var newwindow = $("#post_id option:selected").attr("value");
if(newwindow)
window.location.replace(newwindow);
else
// Complain or something.
});
Or just grab the value straight from the <select>
: 或者直接从<select>
获取值:
$("#post_id").change(function () {
var newwindow = $("#post_id").val();
if(newwindow)
window.location.replace(newwindow);
else
// Complain or something.
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.