Paddy Hallihan
Paddy Hallihan

Reputation: 1686

Redirecting page based on <select> value

I have a <select> tag on my site that when I change it submits the form and goes to the page in question where I can use the $_POST variable.

<form method='POST' action='myURL'>
<select onchange='this.form.submit();'>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
</select>
</form>

This is fine and works as intended but if someone is on the page and refreshes it I don't want to have to have the warning for resubmitting the form.

So what I was trying to do is remove the form element and have something like this and I can use $_GET instead of $_POST.

<select onchange='window.location.href="myURL?var=this.value";'>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
</select>

However, this redirects to the page but the $_GET variable is literally this.value.

Is there another way of getting this to work or will I need to write an external piece of JS for this?

Note JS isn't my language, the snippets above are all being rendered via PHP

Upvotes: 1

Views: 137

Answers (2)

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

I would suggest to you to avoid the use of inline-events as onchange and use the addEventListener() method instead to attach the change event.

So first give you select tag an identifier (id or class) then attach the event using this identifier like :

<select id="my-select">

Then in the JS part it could be attached like :

document.querySelector('#my-select').addEventListener('change', function(){
    window.location.href = "myURL?var=" + this.value;
})

Or if you could use jQuery it will be :

$('#my-select').change(function(){
    window.location.href = "myURL?var=" + $(this).val();
})

Upvotes: 0

Robin Zigmond
Robin Zigmond

Reputation: 18249

You've hardcoded the string - just do this instead:

<select onchange='window.location.href=("myURL?var=" + this.value);'>

Upvotes: 6

Related Questions