jQuery根据所选值改变表单动作

jQuery change form action based on selected value

本文关键字:改变 表单 jQuery      更新时间:2023-09-26

我遇到了一个相当棘手的问题,当使用一个方法来设置表单的动作时,值的变化。我有以下代码:

var actions = new Array();
actions[0] = "some-site.html";
actions[1] = "some-other-site.html";
actions[2] = "another-site.html";
etc....
$("select#feld-urlaubsart").change(function () {
if ($("select#fieldname").val() !== "") {
$("form#searchform").attr("action","http://www.mysite.com/" +  
actions[$("select#fieldname").val()]);
}
});

在另一边,我的选择看起来像这样:

<select id="fieldname" name="fieldname">
<option value="0" selected="selected">All</option>
<optgroup label="Golfurlaub mit Greenfees">
<option value="1">Alle Greenfee-Angebote</option>
<option value="2">Top-Angebote</option>
<option value="3">Golfurlaub mit 4 Tage Greenfee</option>
</optgroup>

实际上它确实工作,但我不满意它,因为我需要依靠value="1" value="2"等。

现在我需要使用实际的描述作为值与另一个脚本兼容,我传递的值在PHP/JSON中使用。我需要这样的数据

<option value="All">All</option>
<option value="Option 1">Option 1</option>
etc

我怎么能改变基于所选值表单的动作,而不需要使用数组键,如"1"2"等?

谢谢你的建议

使用json对象:
actions = {"All":"some-site.html","Option1":"some-other-site.html"}
然后

actions["All"]

"some-site.html"