In one page I have two form for search:
<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>
My problem is that if I click search for Games in searchRedirect always alert Books, School or Music if they checked:
That is my javascript function:
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;
}
I need if I click to search games - search only for games, if click to search books,school or music - searching only for them. But now search form for games always use first form checked buttons.
form['category']
will give you a NodeList
of all form elements whose name is category
, thus you can't use it as a selector by concatenating it with :checked
. It'd be the equivalent of $("[object NodeList]:checked")
.
Since you are already using jQuery, you can use the following instead:
alert($(form).find("input[name='category']:checked").val());
That is, within the context of form
, find every input
element with name category
that is checked
, and get its value
.
you can't real do form["category"] + ":checked"
, instead use jQuery's filter method and than use 'this' to reference the form. Also, you can/should use jQuery .submit() to catch the event instead of an inline handler and just for clearer code (and also for better performance) put the $(form['category']+':checked')
into a variable so jquery won't need to search for the element again and again. This is a sample:
$('form').submit(function(e){
var checked = $(this['category']).filter(':checked');
var value = checked.val();
alert(value);
})
This is a fiddle so you can fiddle (the e passed to the submit callback is the event object and e.preventDefault is like returning false so the form won't submit): http://jsfiddle.net/SJ7Vd/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.