2013-05-08 80 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的,忘记所有这些类型的问题。)