How To Change Action of Form Based on Selection Using JavaScript

In this case, I want to change the action URL of a form. The url will change dynamically depend on the selected item that user choosed. My form looks like this :

<form action="${baseURL}/sample/uploadfiletoday" method="POST" enctype="multipart/form-data" name="uploadfile" id="uploadfile">
    <div class="form-group">
        <label>File Type : </label>
        <select name="filetype" id="filetype" onchange="filetypechange()">
            <optgroup label="Bank BOHAY">
                <option value="CSV_TODAY">Today Transaction (CSV)</option>
                <option value="CSV_HISTORY">History Transaction (CSV)</option>
                <option value="XLS_LOG">Log Transaction (XLS)</option>
            </optgroup>
            <optgroup label="Bank OKEH">
                <option value="MANDIRI_TODAY">Today Account Report (CSV)</option>
            </optgroup>                                                                
        </select>
    </div>
    <div class="form-group">
        <label>File input</label>
        <input type="file" name="file" onchange="checkfile(this);"/>
        <div id="msgerror" class="msg" style="float: left"></div>
    </div>
    <br/>
    <div class="form-group">
        <button type="submit" id="upload" class="btn btn-primary" >Upload</button>                        
    </div>
</form>

The script will be:

<script>
function filetypechange(){
    var form = document.uploadfile;
        switch (form.filetype.selectedIndex) {                    
        case 0:
                form.action = "${baseURL}/sample/uploadfiletoday";
                break;
        case 1:
                form.action = "${baseURL}/sample/uploadfilehis";
                break;
        case 2:
                form.action = "${baseURL}/sample/uploadfilelog"
                break;
        case 3:
               form.action = "${baseURL}/sample/uploadaccstt"
                break;
        }
     }
</script>

Hope this simple article can help 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s