2015-10-08 24 views
0

我正在嘗試做一個下拉選擇,更改表單操作,這將提交時將用戶帶到不同的鏈接。如何設置一個選擇選項來更改表單動作

我試過我認爲應該工作,但一直未能,任何幫助我在這裏做錯了將不勝感激。

JS

$("#time-select").change(function() { 

    if (document.getElementById("time-select").value != "WEEK") 
    { 
    document.getElementById("subs-form").setAttribute("action", "A"); 
    } 

    else (document.getElementById("time-select").value != "FORTNIGHT") 
    { 
    document.getElementById("subs-form").setAttribute("action", "B"); 
    } 

    else (document.getElementById("time-select").value != "MONTH") 
    { 
    document.getElementById("subs-form").setAttribute("action", "C"); 
    } 

} 

HTML

<div class="wrapper">        
<form name="linkForm" id="subs-form" action="" method="GET" > 

    <select id="time-select" > 
    <option value="WEEK" selected>1 BAG A WEEK</option> 
    <option value="FORTNIGHT">1 BAG A FORTNIGHT</option> 
    <option value="MONTH">1 BAG A MONTH</option> 
    </select> 

    <input id="subs-submit" type="submit" value="Subscibe"> 

</form> 
</div> 
+1

爲什麼你使用'!='?而不是'document.getElementById(「time-select」).value'只需使用'$(this).val()' – Satpal

+1

順便說一句:代替再次搜索select元素,您可以從事件中重用它.target:'$(「#time-select」)。change(function(event){if(event.target.value ==「WEEK」){/ * ... * /}});' – feeela

+1

@feeela,How關於'this.value'? – Rayon

回答

3

保持代碼儘可能乾淨(例如使用jQuery選擇),看到這個例子:

$("#time-select").change(function() { 
    var value = $(this).val(), 
     action = null; 

    switch(value) { 
    case "WEEK": 
     action = "A" 
     break; 
    case "FORTNIGHT": 
     action = "B" 
     break; 
    case "MONTH": 
     action = "A" 
     break; 
    } 

    $("#subs-form").attr("action", action); 
} 
0
$("#time-select").change(function() { 
    var option = document.getElementById("time-select").value; 
    var el = document.getElementById("subs-form"); 

    switch(option) { 
    case "WEEK": 
     action = "A" 
     break; 
    case "FORTNIGHT": 
     action = "B" 
     break; 
    case "MONTH": 
     action = "C" 
     break; 
    } 
    el.setAttribute("action", action);  
}); 
0

working fiddle with nicer code.

$("#time-select").on('change', function() { 
     var value = $(this).val(); 
     if (value !== "WEEK") 
      document.getElementById("subs-form").setAttribute("action", "A"); 
     else if (value !== "FORTNIGHT") 
      document.getElementById("subs-form").setAttribute("action", "B") 
     else if (value !== "MONTH") 
      document.getElementById("subs-form").setAttribute("action", "C"); 
}); 
相關問題