表单事件onChange不工作下拉列表选择

时间:2015-01-16 14:27:21

标签: javascript forms

我有一个完美运行的表单,并根据单选按钮更改表单的操作:

 <form name="form1" method="post" action="[[base_urlnt]]/electricity-rate-plans">
 <input type="radio" name="energy" value="electricity" checked>
 <label for="electricity">Electricity</label>
 <input type="radio" name="energy" value="gas" onChange="if(this.checked){document.forms[0].action='[[base_urlnt]]/natural-gas-rate-plans'}">
 <label for="gas">Natural Gas</label>
 <input name="service_zip_5" type="text" id="search" placeholder="Enter ZIP Code"><button type="submit" class="bigButton">Get Rates</button>
 </form>

我想做同样的事情,但是使用onChange而不是单选按钮更改另一个表单上的操作,但使用下面的下拉列表。我做错了什么?

<form name="form1" method="post" action="[[base_url]]alberta/electricity-plans">
<p>Choose Your Service</p>
<select name="service" id="service" title="Choose Your Service">
<option value="Electricity" selected="selected">Electricity</option>
<option value="Gas" onChange="if(this.selected){document.forms[0].action='[[base_url]]alberta/natural-gas-plans'}">Natural Gas</option>
<option value="Dual" onChange="if(this.selected){document.forms[0].action='[[base_url]]alberta/dual-fuel-plans'}">Dual Fuel</option>
</select>
<p>Enter Your ZIP Code</p>
<input name="service_zip_5" type="text" id="zipcode">
<button type="submit" id="submit">Get Started</button>
</form>

我试过了     的onChange =&#34;如果(this.checked) 首先,并认为既然它是一个选择,它应该是onChange =&#34; if(this.selected)但不起作用。这不是一个功能吗?

1 个答案:

答案 0 :(得分:1)

您需要稍微更改一下。

您的onchange事件应该绑定到选择而不是单个选项。

我还为每个选项添加了一个属性“data-url”,用于存储需要添加到表单操作onchange的URL。

然后,javascript函数可以使用此“data-url”属性来更新表单操作。这也意味着您不必在所有onchange属性中重复相同的代码。您只需调用一个提取相应“data-url”的函数。

请参阅 - http://jsfiddle.net/williamtdavies/8kxzaquw/

<form name="form1" method="post" action="[[base_url]]alberta/electricity-plans">
    <p>Choose Your Service</p>
    <select name="service" id="service" title="Choose Your Service" onChange="changeFormAction(this);">
        <option value="Electricity" data-url="[[base_url]]alberta/electricity-plans">Electricity</option>
        <option value="Gas" data-url="[[base_url]]alberta/natural-gas-plans">Natural Gas</option>
        <option value="Dual" data-url="[[base_url]]alberta/dual-fuel-plans">Dual Fuel</option>
    </select>
    <p>Enter Your ZIP Code</p>
    <input name="service_zip_5" type="text" id="zipcode"/>
    <button type="submit" id="submit">Get Started</button>
</form>

<script>
    function changeFormAction(elem){
    document.forms[0].action = elem.options[elem.selectedIndex].getAttribute("data-url"); 
    }
</script>
相关问题