【问题标题】:Form redirect on submit using dropdown options values for urls使用 url 的下拉选项值提交表单重定向
【发布时间】:2013-01-24 23:29:38
【问题描述】:

我在使用下面的这个表单时遇到了问题。它只包含一个<select> 下拉菜单和一个submit 按钮。如果用户选择一个选项并提交表单,则内联 javascript 应该获取相应的值并相应地重定向用户。我尝试使用下面的内联 javascript,但我不知道如何选择表单内的下拉菜单,可能不使用类或 id。

<form onsubmit="var sel = select; window.location.replace = sel.options[sel.selectedIndex].value; return false;">
    <select>
        <option>Menu</option>
        <option value="http://someurl...">Label</option>
        <option value="http://someurl...">Label</option>
        <option value="http://someurl...">Label</option>
        <option value="http://someurl...">Label</option>
        <option value="http://someurl...">Label</option>
    </select>
    <input class="btn" type="submit" value="Go">
</form>

注意事项:

  • 在同一页面上我可能有多个这样的表单,我想要 使用许多 id 或类 - 我只想在 内联 javascript 所在的表单。
  • 我知道这可以通过使用selectonchange(我做到了,但我认为是为了可用性 options 最好包含一个按钮)。
  • 我知道这可以使用 POST 而无需 javascript(例如 http://css-tricks.com/unobtrusive-page-changer/ 但我想做 在javascript中)

【问题讨论】:

  • var sel = this.getElementsByTagName('select')[0];
  • 感谢您的帮助!如果您将您的评论作为答案,我会将其标记为我问题的正确答案 - 再次感谢

标签: javascript forms html-select onsubmit


【解决方案1】:

由于您在表单的 onsubmit 属性中,您可以通过this 访问它,然后使用getElementsByTagName 选择select 元素。

var sel = this.getElementsByTagName('select')[0];

【讨论】:

    猜你喜欢
    • 2014-08-07
    • 2011-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多