2013-05-08 29 views
2

設置時,我有兩個輸入的頁面上的表單。在提交時,我希望頁面重定向到包含兩個輸入值的鏈接以及一個前面的字符串。在HTML如下:表單操作不正確使用Javascript

<form name="searchForm"> 
    <label for="property_type">Property Type</label> 
    <select name="property_type" id="property_type_number"> 
     <option value>- All Property Types -</option> 
     <option value="1432">Commercial</option> 
     <option value="1433">Land</option> 
     <option value="1434">MultiFamily</option> 
     <option value="1435">Rental</option> 
     <option value="1436">Residential</option> 
     <option value="1988">Residential/Condo</option> 
     <option value="1987">Residential/Single Family</option> 
    </select> 

    <label for="city">City</label> 
    <select name="city" id="city_number"> 
     <option value>- All Property Types -</option> 
     <option value>--</option> 
     <option value="cambridge">Cambridge</option> 
     <option value="zanesville">Zanesville</option> 
    </select> 

    <input type="submit" value="Search for Properties" onclick="searchform()"> 
</form> 

和JavaScript如下:

function searchform() 
{ 
    var propertyType = document.getElementById("property_type_number").value; 
    var city = document.getElementById("city_number").value; 

    target = "/idx/?" + city + propertyType + "hi"; 

    document.searchForm.action = target; 
} 

當我提交表單,它似乎只使用目標變量(「第一串/ IDX/?「),但忽略其餘。然後它會自動插入表單中的值。我希望它能夠進入上面的自定義目標。

如果你想看到它在網絡上的地址是:http://lainegabriel.net/(這是左邊的最後控件)。

+2

這裏工作在Chrome 26,採摘土地/ Zaneville給'IDX /房產類型= 1433&城市= zanesville'?你使用什麼瀏覽器? – RaphaelDDL 2013-05-08 20:26:28

+0

我使用Chrome 28;我還注意到,爲了測試目的而插入的「hi」字符串未包括在內。由於某種原因,它似乎只取第一部分(「/ idx /?」)。謝謝你的幫助! – user1498724 2013-05-08 20:31:37

+0

爲什麼使用開發人員版本容易出錯?測試'當前'鉻,火狐,IE9 .. [正常工作](http://jsfiddle.net/Daedalus/WXNe5/)。 – Daedalus 2013-05-08 20:32:48

回答

0

嗯,我無法解釋爲什麼形式表現爲這樣,或者爲什麼它不工作,因爲它會出現的信息每一位網上說做的正是你在做什麼..我但是,可以提供一個變通辦法:

首先,改變你的HTML這是從提交按鈕中刪除'onclick',並替換表單標籤:

<form name="searchForm" onsubmit="return searchform();"> 

其次,在您的searchform()功能:

function searchform() { 
    var propertyType = document.getElementById("property_type_number").value; 
    var city = document.getElementById("city_number").value; 


    target = "/idx/?" + city + propertyType + "hi"; 

    document.searchForm.action = target; // I just left this in here just in case you wanted it. 
    window.location.href = target; // redirect the window to the new url/action 
    return false; // prevent the default submit action from occurring 
} 

Demo

0

改變這一點:

var propertyType = document.getElementById("property_type_number").value; 
var city = document.getElementById("city_number").value; 

與此:

var select = document.getElementById("property_type_number"); 
var propertyType = select.options[ select.selectedIndex ].value; 
select = document.getElementById("city_number"); 
var city= select.options[ select.selectedIndex ].value; 

有什麼區別?
我知道它的代碼大,但我從未有過的問題(之前我切換到jQuery的,忘記所有這些類型的問題。)