使用Javascript设置时,表单操作不正确

Form action incorrect when set with Javascript

本文关键字:表单 操作 不正确 Javascript 设置 使用      更新时间:2023-09-26

我在页面上有一个有两个输入的表单。提交时,我希望页面重定向到一个链接,其中包含两个输入的值,加上前面的字符串。html格式如下:

<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/(它是左边的最后一个小部件)

嗯,我无法解释为什么表单的行为是这样的,或者为什么它不起作用,因为似乎在线的每一点信息都说要做你正在做的事情。但是,我可以提供一个解决方法:

首先,把你的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
}
演示

改变这个:

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并忘记所有这些问题之前…)