Joon Song Joon Song - 3 months ago 4
HTML Question

How to make a form input part of a website destination?

I have a select form made in html and I want to make the selected value part of the url destination when they submit it.
Example:

<form>
<select name="state" id="state">
<option value="AK">Alaska</option>
<option value="AL">Alabama</option>
<option value="AR">Arkansas</option>
<option value="AZ">Arizona</option>
<option value="CA">California</option>
</select>
<input type="submit" value="submit">
</form>


And when they choose, let's say "CA", I want the submit button go to "www.example.com/ca.html".

Here's my JS:

var stLocation = document.getElementById("state").value;
window.location.href = 'www.example.com/stLocation.html';

Answer

First of all you need to include yourjQuery library to your script. Then you try this

$('button').click(function (){
    selectedValue = $('select').val().toLowerCase(); //I converted it to lowercase due to the case difference in your value and your url
    window.location.href = "http://www.example.com/"+selectedValue+".html";
});

But if its in a form tag the use this instead

$('form').submit(function (e){
    e.preventDefault();
    selectedValue = $('select').val().toLowerCase(); //I converted it to lowercase due to the case difference in your value and your url
    window.location.href = "http://www.example.com/"+selectedValue+".html";
});
Comments