2014-10-28 41 views
0

我有一個表單,其中包含可緩存項目的Javascript填充集合,以及由用戶輸入的ID爲文本框。我希望表單提交將用戶重定向到來自其他調用的JSON響應。當我直接進入瀏覽器時,其餘的URL起作用,但是將它轉移到html和js會擊敗我。點擊提交時,提交表單不會執行任何操作。html onsubmit無法啓動Javascript功能

我的形式 -

<form id="query" action="get" onsubmit="return restLink();"> 
    <td> 
    <select id="selectCacheableItemType"> 
     <option>Select a Cacheable Item Type</option> 
    </select> 
    </td> 
    <td> 
    Cacheable item Id: <input type="text" id="cacheableId"><br> 
    </td> 
</form> 

的緩存項目類型在這裏居住 -

window.onload = function cacheItemType(){ 
    var select = document.getElementById("selectCacheableItemType"); 
    var options = ["1", "2", "3", "4", "5", "6","7"]; 
    for(var i = 0; i < options.length; i++) { 
     var opt = options[i]; 
     var el = document.createElement("option"); 
     el.textContent = opt; 
     el.value = opt; 
     select.appendChild(el); 
    } 
}; 

和restLink()函數 -

function restLink() { 
    cachetypename = document.getElementyId('selectCacheableItemType').getValue(); 
    cacheid = document.getElementyId('cacheableId').getValue(); 
    return window.location.href = "http://localhost:8080/rest/query/"+ cachetypename + "/" + cacheid; 
} 

任何幫助深表感謝。

+1

哪裏提交按鈕?您的HTML無效。你不能在td標籤周圍有表格。 – epascarello 2014-10-28 14:27:58

+0

您是否嘗試添加提交輸入?並在該提交輸入上進行onclick事件? – guramidev 2014-10-28 14:28:35

+0

設置'window.location.href'會讓你轉到那個頁面。其次,當你的JavaScript中有錯誤時,你的函數將不會被調用/ finnished。在瀏覽器中打開您的開發人員工具 - >控制檯,查看您提交時是否返回錯誤。 – 2014-10-28 14:30:40

回答

2

您正試圖設置window.location.href。你要麼提交表單到這個URL。或者你根本不需要表單,只是想將位置更改爲此網址。你正在合併2件事,這就是爲什麼它不工作。我會擺脫從,並創建一個按鈕與onclick調用你的restLink()方法。這裏不需要表格。

事情是這樣的:

<table> 
<tr> 
    <td> 
    <select id="selectCacheableItemType"> 
     <option>Select a Cacheable Item Type</option> 
    </select> 
    </td> 
    <td> 
    Cacheable item Id: <input type="text" id="cacheableId"><br> 
    </td> 
</tr> 
<tr> 
    <input type="button" id="enterButton" onclick="restLink()"> 
</tr> 
</table> 
+0

這是最適合我的答案。非常感謝。有投票並接受剔。 – 2014-10-28 16:24:41

+0

歡迎您的光臨,我可以幫助您! – brso05 2014-10-28 16:38:17

0

你有沒有嘗試添加一個提交按鈕?

<form id="query" action="get" onsubmit="return restLink();"> 
    <td> 
    <select id="selectCacheableItemType"> 
     <option>Select a Cacheable Item Type</option> 
    </select> 
    </td> 
    <td> 
    Cacheable item Id: <input type="text" id="cacheableId"><br> 
    </td> 
<input type="submit" value="Submit" id="submitForm"/> 
</form> 

然後:

$(document).ready(
function(){ 
    cacheItemType(); 
var select = $("#selectCacheableItemType"); 
    var options = ["1", "2", "3", "4", "5", "6","7"]; 
    for(var i = 0; i < options.length; i++) { 
     var opt = options[i]; 
     var el = document.createElement("option"); 
     el.textContent = opt; 
     el.value = opt; 
     select.appendChild(el); 
});