Home » Php » javascript – Change form action on select option

javascript – Change form action on select option

Posted by: admin July 12, 2020 Leave a comment

Questions:

I want to change the form action based on a selection value.

Hi Guys,

<form name="store" id="store" method="post" action="">
<select name="storeID">
<option value="/stores/store6.php">6</option>
<option value="/stores/store10.php">10</option>
</select>                   
</form>

Now i want the form action, to use the select option value. For example:

If Selection 1 is selected, use the folowing form action /stores/store6.php

How to&Answers:

You can use the onchange event to change the form’s action

document.getElementById('store').storeID.onchange = function() {
    var newaction = this.value;
    document.getElementById('store').action = newaction;
};

Here is a jsfiddle with the code.

Answer:

Add to select onchange function

<select name="storeID" onchange='changeAction(this.value)'>

and add to javascript

function changeAction(val){
    document.getElementById('storeID').setAttribute('action', val);
}

This will change action after selected option is changed to selected option value.

Answer:

<form name="store" id="store" method="post" action="" id="FORM_ID" >
    <select name="storeID">
        <option value="/stores/store6.php">6</option>
        <option value="/stores/store10.php">10</option>
    </select>                   
</form>

<script type="text/javascript">
document.getElementById('storeID').onchange = function(){
    document.getElementById('FORM_ID').action = '/'+this.value;
}
</script>

check it out i wish it will work ..

Answer:

Add this to your select:

onchange=”changeAction(this)”

and this to your javascript

changeAction = function(select){
   document.getElementById("store").action = select.value;
}