2

在一页中,我有两种搜索形式:

<form class="search-panel" method="post" action="" onsubmit="return searchRedirect(this)">
        <input type="test" name="searchFor" />
        <div class="additional-search-button"></div>
        <div id="additional-search-box">
            <div class="as-cont">
                Books<input type="radio" name="category" value="Books" checked="1" /><br/>
                School<input type="radio" name="category" value="School" /><br/>
                Music<input type="radio" name="category" value="Music" />
            </div>
        </div>
       <input type="submit" name="search" />
    </form>

<form class="search-panel" method="post" action="" onsubmit="return searchRedirect(this)">
            <input type="test" name="searchFor" />
            Games<input type="radio" name="category" value="Games" checked="1" />
            <input type="submit" name="search" />
        </form>

我的问题是,如果我在 searchRedirect 中单击搜索游戏,如果它们检查过,总是会提醒书籍、学校或音乐:

那是我的javascript函数:

function searchRedirect(form) {
    alert($(form['category']+':checked').val());

    if($(form['category']+':checked').val() == 'Форум')
        window.location.href = '/forum/search.php?keywords='+form['searchFor'].value;
    else {
        window.location.href = '/Search/'+$(form['category']+':checked').val()+'/'+form['searchFor'].value;
    }

    return false;
}

如果我点击搜索游戏,我需要 - 只搜索游戏,如果点击搜索书籍、学校或音乐 - 只搜索它们。但是现在搜索游戏的表单总是使用第一个表单检查按钮。

4

2 回答 2

3

form['category']将为您提供NodeList名称为 的所有表单元素category,因此您不能通过将其与 . 连接来将其用作选择器:checked。它相当于$("[object NodeList]:checked").

由于您已经在使用 jQuery,因此您可以使用以下代码:

alert($(form).find("input[name='category']:checked").val());

也就是说,在 的上下文中,找到名称为的form每个input元素,并获取其。categorycheckedvalue

于 2012-08-26T18:00:17.003 回答
1

你不能这样做form["category"] + ":checked",而是使用 jQuery 的过滤器方法,而不是使用 'this' 来引用表单。此外,您可以/应该使用 jQuery .submit() 来捕获事件而不是内联处理程序,并且只是为了更清晰的代码(以及更好的性能)将其$(form['category']+':checked')放入变量中,这样 jquery 就不需要再次搜索元素然后再次。这是一个示例:

$('form').submit(function(e){
var checked = $(this['category']).filter(':checked');
var value = checked.val();
alert(value);
})​

这是一个小提琴,所以你可以摆弄(传递给提交回调的 e 是事件对象,e.preventDefault 就像返回 false 所以表单不会提交):http: //jsfiddle.net/SJ7Vd/

于 2012-08-26T18:39:33.337 回答