Javascript 在选择选项上更改表单操作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25960729/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:08:45  来源:igfitidea点击:

Change form action on select option

javascriptphphtml

提问by daniel.

I want to change the form action based on a selection value.

我想根据选择值更改表单操作。

Hi Guys,

嗨,大家好,

<form name="store" id="store" method="post" action="">
<select name="storeID">
<option value="/stores/store6.php">6</option>
<option value="/stores/store10.php">10</option>
</select>                   
</form>

Now i want the form action, to use the select option value. For example:

现在我想要表单操作,以使用选择选项值。例如:

If Selection 1 is selected, use the folowing form action /stores/store6.php

如果选择了选择 1,请使用以下表单操作 /stores/store6.php

回答by Tasos K.

You can use the onchangeevent to change the form's action

您可以使用该onchange事件来更改表单的操作

document.getElementById('store').storeID.onchange = function() {
    var newaction = this.value;
    document.getElementById('store').action = newaction;
};

Hereis a jsfiddle with the code.

是一个带有代码的jsfiddle。

回答by Jozef Dúc

Add to select onchangefunction

添加选择onchange功能

<select name="storeID" onchange='changeAction(this.value)'>

and add to javascript

并添加到 javascript

function changeAction(val){
    document.getElementById('storeID').setAttribute('action', val);
}

This will change action after selected option is changed to selected option value.

这将在选定选项更改为选定选项值后更改操作。

回答by Ferrakkem Bhuiyan

<form name="store" id="store" method="post" action="" id="FORM_ID" >
    <select name="storeID">
        <option value="/stores/store6.php">6</option>
        <option value="/stores/store10.php">10</option>
    </select>                   
</form>

<script type="text/javascript">
document.getElementById('storeID').onchange = function(){
    document.getElementById('FORM_ID').action = '/'+this.value;
}
</script>

check it out i wish it will work ..

检查一下,我希望它会起作用..

回答by Johan Karlsson

Add this to your select:

将此添加到您的选择中:

onchange="changeAction(this)"

onchange="changeAction(this)"

and this to your javascript

这给你的 javascript

changeAction = function(select){
   document.getElementById("store").action = select.value;
}