[Answer]-JS Change form action upon select change doesn't work with .trim()

1👍

Wouldn’t it be easier to do it this way? (Using the id as the value of the select options)

<form role="form"  method="post" id="switch-customer-form" class="switch-customer-form">
        {% csrf_token %}
        <div class="form-group col-xs-12 floating-label-form-group controls">
            <select class="form-control customers-dropdown" id="customers-dropdown" name="form_customers">
                {% for c in customers %}
                    <option{% if customer == c %} selected="true"{% endif %} value="{{c.id}}">{{ c }} - {{ c.id }}</option>
                {% endfor %}
            </select> 
        </div>
        <div class="form-group col-xs-12 floating-label-form-group controls">
            <input type="submit" value="View Calendar" class="btn btn-primary btn-sm">
        </div>


    </form>

$("#customers-dropdown").change(function() {

    var action1 = "/ac/calendar/";
    var action2 = "/2014/12/";

    var customer = this.value;

    var final_action = action1 + customer + action2;

    alert(final_action);

    $("#switch-customer-form").attr("action", final_action);

});

UPDATE

This is without adding a value to the tag. Upon doing so I
encounter the same issue where it does not update the form action and
simply posts to the current page.

You’re being redirected to the same page because the change event hasn’t been triggered and there’s no action in the form. If the change event would be triggered, the action would change and it would work.

You need to add an action to the form or add javascript to change the action to the option marked as selected when the DOM is ready.

For instance, on DOM ready:

var changeAction = function(id) {
    var action1 = "/ac/calendar/";
    var action2 = "/2014/12/";    

    var final_action = action1 + id + action2;

    $("#switch-customer-form").attr("action", final_action);
};

changeAction($("#customers-dropdown").val());// On document ready, change action to selected item.
$("#customers-dropdown").change(function () {// On change event, change action as well
    changeAction(this.value);
});

fiddle

Leave a comment