2012-08-26 27 views
2

在一個頁面上,我有兩個形式的搜索:的Javascript:經過單選按鈕

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

如果我點擊搜索比賽我所需要的 - 僅搜索遊戲,如果點擊搜索書籍,學校或音樂 - 只爲他們尋找。但現在,遊戲的搜索表單總是使用第一個表單檢查按鈕。

+1

僅供參考,您可以在窗體(而不是div)中使用更多語義元素。 '

'+''用於對相關表單控件進行分組。 –

回答

3

form['category']會給你所有的表單元素,其名稱是categoryNodeList,所以你不能用:checked相連來使用它作爲一個選擇。這將相當於$("[object NodeList]:checked")

既然你已經使用jQuery,您可以改用以下內容:

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

也就是說,form範圍內,找到名稱categorycheckedinput元素,並獲取其value

+0

好的謝謝,解決我的問題:)。 – Defense

+0

我知道,但有消息接受答案:您可以接受..... – Defense

+0

@Defense中的答案,如果它解決了您的問題,爲什麼不投票回答? – user907860

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/

+0

F @#K,我有一段時間的窗口,回來之前沒有刷新,然後再寫答案...我確信他們已經AJAX這個獲得新帖子沒有刷新...好吧,還有另一個答案...無論如何,我建議使用.submit和變量... – Lior