开发者

Best way to change a form action upon submit

开发者 https://www.devze.com 2023-04-06 12:58 出处:网络
Basically 开发者_开发百科I have a form with a few drop-downs, but the page I\'d like to be set as the action of the form submit would be based on the option chosen in one of the drop downs. I\'d like

Basically 开发者_开发百科I have a form with a few drop-downs, but the page I'd like to be set as the action of the form submit would be based on the option chosen in one of the drop downs. I'd like to stick with one submit button, so it seems a little tricky. Can anyone point me in the right direction?


You could use some jQuery.

$("#yourDropDown").change(function() { 
    var text = $(this).children(':selected').text(); 
    $("#yourForm").attr('action', text); 
});

Where "yourDropDown" is the ID of your dropdown, and "yourForm" is the ID of your form, and where the text in the dropdown-options are fully qualified URLs to post to.

Edit: Also I agree with Quentin's comment on your post.


Another way is to add an onsubmit event handler on the form. If your form looks something like:

<form id="myForm" action="action1.php">
    <select id="myDropdown">
        <option value="1">Option 1</option>
        <option value="2">Option 1</option>
    </select>
    <input type="submit" value="Submit" />
</form>

add the following javascript (using jQuery here):

$(document).ready(function() {

    $('#myForm').submit(function() {
        var dropdownVal = $("#myDropdown").val();
        switch( dropdownVal ) {
            case 1:
                $(this).attr('action', 'action1.php');
                // do other stuff if you want
                break;
            case 2:
                $(this).attr('action', 'action2.php');
                // do other stuff if you want
                break;                
        }
    }

});
0

精彩评论

暂无评论...
验证码 换一张
取 消