2

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?

Tim H
  • 205
  • 2
  • 17
  • 1
    Don't. Have a single action that can handle everything (even if it does so by `if ($_POST['foo'] === 'bar') { include('bar.php'); }`). Otherwise you get an unnecessary dependancy on JS. – Quentin Sep 22 '11 at 13:38
  • Thanks for the tip. However, this project is for strictly in-house users that will have JS enabled. – Tim H Sep 22 '11 at 13:44
  • Just realized this may be a duplicate of [1925614](http://stackoverflow.com/questions/1925614/jquery-change-form-action-based-on-selection) – jbyrd Sep 22 '11 at 14:37

2 Answers2

1

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.

Andreas Eriksson
  • 8,979
  • 8
  • 47
  • 65
  • 1
    Don't think $('#yourForm').attr('action') = ... will work. Should be $('#yourForm').attr('action', 'actionGoesHere.php') – jbyrd Sep 22 '11 at 14:07
  • Yeah, I was getting "Cannot assign to a function result" for a little while before figuring that out. Thanks. – Tim H Sep 22 '11 at 14:23
1

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

});
jbyrd
  • 5,287
  • 7
  • 52
  • 86