如何修改添加所选单选按钮值的表单操作

时间:2011-07-06 21:51:23

标签: javascript jquery forms action

我有一个带有一些单选按钮的HTML表单:

<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>

onclick事件中,我想向添加所选类别的操作/somecomplicatedurl添加查询字符串。

例如,点击类别spam会触发HTTP帖子,其操作如下:

/somecomplicatedurl?category=spam

Javascript或jQuery都有效。

修改
类别值已正确传递给服务器; 我只需要,单击单选按钮后,浏览器地址栏中显示的URL将包含所选类别。 *

*我想避免添加另一个重定向,因为我目前正在处理/ somecomplicatedurl route上的不同情况

4 个答案:

答案 0 :(得分:2)

POST / GET变量的混合被认为是一种糟糕的形式。为什么不动态设置隐藏的表单字段:

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

代替?

你的onclick会变成:

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

如果它只是一个显示问题,那么

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

答案 1 :(得分:1)

对不起,首先误解了你的问题。 您可以通过添加

来更改表单操作
document.this_form.action = "somecomplicatedurl?category=span";
在提交之前

到你的onClick事件。

答案 2 :(得分:0)

在我看来,在表格标签中使用方法“GET”可以达到你想要的效果,或者我误解了这个问题......

答案 3 :(得分:0)

将表单方法更改为get可能是最简单的,但是如果它比这更复杂,那么这里有一些jQuery。取出那些内联脚本并编写如下内容:

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

    });
});