我在这里找到了类似的问题:javascript - change form action based on selection?
但我的问题略有不同。我有两个选择:
<form id="CarSearch" action="" method="post">
<select name="style" id="Style">
<option value="" selected>Any Style</option>
<option value="style/sports-1">Sports</option>
<option value="style/wagon-3">Wagon</option>
<option value="style/suv-6">SUV</option>
</select>
<select name="make" id="Make">
<option value="" selected>Any Make</option>
<option value="make/porsche-3">Porsche</option>
<option value="make/ford-6">Ford</option>
<option value="make/volvo-7">Volvo</option>
</select>
<input type="submit" value="submit"/>
</form>
我想根据两个选择中的值构建表单操作属性。所以情况如下:
action="style/sports-1"
action="make/volvo-7"
action="/style/sports-1/make/volvo-7"
两个选项的默认值始终为“任意”。我可以尝试在jQuery中为每个选择创建两个变量,并在选择更改时设置它们的值。但它的连接部分令我感到困惑。
我在这里创建了一个JSFiddle,让我开始 http://jsfiddle.net/L91rb9f9/3/
当未指定样式时,我以两个斜杠结尾。
答案 0 :(得分:2)
尝试这样的事情:
$("#CarSearch").submit(function () {
var style = $("#Style").val();
var make = $("#Make").val();
if (style == "" && make == ""){
$('form').get(0).setAttribute('action', '');
}
else if (style != "" && make != "") {
$('form').get(0).setAttribute('action', style + "/" + make);
}
else {
$('form').get(0).setAttribute('action', style + make);
}
});
答案 1 :(得分:1)
<script>
function updateForm(){
var formelem=$('#CarSearch');
var styleelem=$('#Style');
var makeelem=$('#Make');
var action='/';
action+=styleelem.val();
if (action.length>1)action+='/';
action+=makeelem.val();
formelem.attr('action',action');
}
</script>
<form id="CarSearch" action="" method="post">
<select onchange="updateForm();" name="style" id="Style">
<option value="" selected>Any Style</option>
<option value="style/sports-1">Sports</option>
<option value="style/wagon-3">Wagon</option>
<option value="style/suv-6">SUV</option>
</select>
<select onchange="updateForm();" name="make" id="Make">
<option value="" selected>Any Make</option>
<option value="make/porsche-3">Porsche</option>
<option value="make/ford-6">Ford</option>
<option value="make/volvo-7">Volvo</option>
</select>
<input type="submit" value="submit"/>
</form>
答案 2 :(得分:1)
以下jQuery方法应该满足您的要求。
$("#CarSearch").click(function (){
var style = $("#Style").val();
var make = $("#Make").val();
var formAction = "";
if(style != "" && make != ""){
formAction = "/" + style + "/" + make;
}else if (style != "" && make == "") {
formAction = style;
}else if (style == "" && make != ""){
formAction = make;
}else {
formAction = "";
}
$("#CarSearch").attr("action", formAction);
alert('Form Action: ' + $("#CarSearch").attr("action"));
});