简体   繁体   中英

Select a form action depending on the option chosen from a select tag

I'm very new to this, so this may not the best way to go about solving this problem. Basically, I am trying to run one of three .php files upon a form submit. Which .php file I run should depend on what value the user chooses from the select field with id="periodDisplay". Would really appreciate some help.

<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>

Did you debug to see what selectedIndex returns? It returns an INTEGER, not the value/text of the selected option.

Why make it so complicated. Set the value to the page you want to go to and reference it. All of the code is reduced to one line.

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;
}

Should be

function onSubmitForm(){

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

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

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM