systempuntoout systempuntoout - 5 months ago 8
jQuery Question

How to modify a form action adding the selected radio button value

I have an HTML form with some radio buttons like these:

<form action = "/somecomplicatedurl" method="post">
<ul id="category_list">
<li>
<label for="Foo">
<input type="radio" name="category" id="foo" value="foo" onclick="this.form.submit()" />
Foo</label>
</li>
<li>
<label for="Bar">
<input type="radio" name="category" id="bar" value="bar" onclick="this.form.submit()"/>
Bar</label>
</li>
<li>
<label for="Spam">
<input type="radio" name="category" id="spam" value="spam" onclick="this.form.submit()"/>
Spam</label>
</li>
</ul>
</form>


On the
onclick
event, I would like to add a query string to the action
/somecomplicatedurl
adding the selected category.

For example, clicking the category
spam
should fire an HTTP post with an action like this:

/somecomplicatedurl?category=spam


Javascript or jQuery are both valid.

EDIT:

the category value is already passed correctly to the server;
I just need that, once the radio button is clicked, the url displayed in the browser address-bar contains the selected category. *

* I would like to avoid to add another redirect because I'm currently handling different cases on that /somecomplicatedurl route

Answer

The mixing of POST/GET variables is considered as a poor form. Why not dynamically set a hidden form field:

<input type="hidden" id="category" name="category" value="spam" />

instead?

Your onclick would become:

onClick="document.getElementById('category').value = this.value; this.form.submit();"

if it's just a display issue, then

onclick="this.form.action='/somecomplicatedurl?category=' + this.value; this.form.submit();"