根据从选择标记中选择的选项选择表单操作

时间:2012-10-23 03:11:57

标签: javascript

我对此很新,所以这可能不是解决这个问题的最好方法。基本上,我试图在表单提交时运行三个.php文件之一。我运行的.php文件应该取决于用户从id =“periodDisplay”的select字段中选择的值。真的很感激一些帮助。

<script>

    function onSubmitForm(){

    if(document.getElementById("periodDisplayed").selectedIndex == 'This Week')
    {
        return document.selectDisplay.action ="thisWeek.php";
    }

    else if(document.getElementById("periodDisplayed").selectedIndex == 'This Month')
    {
        return document.selectDisplay.action ="thisMonth.php";
    }

    else if(document.getElementById("periodDisplayed").selectedIndex == 'All Workouts')
    {
            return document.selectDisplay.action ="allWorkouts.php";
    }

    else
    {
        return document.selectDisplay.action = "index.html";
    }
return true;
    }
</script>




<form id="selectDisplay" onsubmit="return onSubmitForm();">
    I want to see 
    <select id="unitDisplayed">
        <option>Distance</option>
        <option>Time</option>
    </select>
     for 
    <select id="periodDisplayed">
        <option>This Week</option>
        <option>This Month</option>
        <option>All Workouts</option>
    </select>

    <input type="submit"></input>
</form>

2 个答案:

答案 0 :(得分:1)

您是否进行了调试以查看selectedIndex返回的内容?它返回INTEGER,而不是所选选项的值/文本。

为什么要这么复杂。将值设置为您要转到的页面并引用它。所有代码都减少到一行。

<强> HTML

<select id="periodDisplayed">
    <option value="thisWeek.php">This Week</option>
    <option value="thisMonth.php">This Month</option>
    <option value="all.php">All Workouts</option>
</select>

<强>的JavaScript

function onSubmitForm() {
    document.selectDisplay.action = document.getElementById("periodDisplayed").value;
    return true;
}

答案 1 :(得分:0)

应该是

function onSubmitForm(){

if(document.getElementById("periodDisplayed").value == 'This Week')
{

    document.selectDisplay.action ="thisWeek.php";
    return true;
}
....

document.selectDisplay.action = "index.html";
return true;

}