开发者

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


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();"


Sorry, misunderstood your question at first. You can change the form action by adding

document.this_form.action = "somecomplicatedurl?category=span";

to your onClick-event, before submitting.


Seems to me that using method "GET" in the form tag would accomplish what you want, or am I misunderstanding the question...


Changing the form method to get is probably the easiest, but on the off-chance that it's a little more complicated than that, here's some jQuery. Take out those inline scripts and write something like this:

$(function () {
    $('#category_list input').change(function () {
        var jQthis = $(this),
            jQform = $(this).parents('form'),
            currentAction = jQform.attr('action'),
            // This removes the current query, if you've added one.
            newAction = currentAction.split('?').shift();

        // Work out the new action and set it.
        newAction += jQthis.val();
        jQform.attr('action', newAction);

        // Submit the form, since your previous handlers were doing that.
        jQform.submit();

    });
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜