2014-01-17 50 views
0

我試圖自動檢查基於URL中參數值的單選按鈕。在用戶選擇了一些值並在前一頁上提交表單後,這些參數被添加到URL中。在下一頁中,有一個表單和其他一些輸入。我想要做的是檢查相同的值,該用戶已在上一頁中選擇無線電。jQuery。從URL獲取參數值並檢查單選按鈕

可以說我有這個網址的頁面二:domain.com/page.html?checkbox-one=1 &複選框兩= 0

在此頁面中我有無線電輸入:

<input type="radio" name="checkbox-one" value="0" id="radio1" /> 
    <label for="radio1">Radio#1</label> 

    <input type="radio" name="checkbox-one" value="1" id="radio2" /> 
    <label for="radio2">Radio#2</label> 

    <input type="radio" name="checkbox-two" value="0" id="radio3" /> 
    <label for="radio3">Radio#3</label> 

    <input type="radio" name="checkbox-two" value="1" id="radio4" /> 
    <label for="radio4">Radio#4</label> 

在這種情況下,我想查看name="checkbox-one" value="1"name="checkbox-two" value="0"檢查。

PHP解決方案是不可取的,所以我怎麼用jQuery來實現這一點。有沒有辦法讀取URL參數值並檢查基於它們的單選按鈕?

謝謝!

回答

1

This post展示瞭如何從URL

function getParameterByName(name) { 
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]"); 
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"), 
     results = regex.exec(location.search); 
    return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " ")); 
} 

你可以得到一個參數值,然後通過複選框循環,看看他們是否應檢查與否。

$("input[type=radio]").each(function() { 
     var currInputName = $(this).attr('name'); 

     if(getParameterByName(currInputName) == '1'){ 
      $(this).prop("checked", true); 
     } 
}); 

您應該注意,您一次只能檢查1個收音機。

+0

感謝您的回答,這很有幫助,並給了我一個關於如何繼續下去的想法。請參閱我的解決方案,該解決方案使用jQuery替代方案。 –

1

接受的答案是非常有幫助的,但jQuery的用法在我的情況下更可取,所以我使用了一些不同的解決方案。 Here我發現了一個很好的代碼片斷,爲了我的目的我稍微修改了一下。

// Getting query string parameters 
var vars = [], hash; 
var query = document.URL.split('?')[1]; 
if(query != undefined){ 
    query = query.split('&'); 
    for(var i = 0; i < query.length; i++){ 
     hash = query[i].split('='); 
     vars.push(hash[1]); 
     populateRadios(); 
    } 
}; 

// Checking radio buttons 
function populateRadios() { 
    $("input[type=radio]").each(function() { 
     $('input[name="' + hash[0] + '"][value="' + hash[1] + '"]').prop('checked', true); 
    }); 
}; 

該代碼段解構查詢字符串,並將參數及其值放入單獨的散列中。然後調用單選按鈕檢查功能,就是這樣。

我會感謝您的意見和改進建議。謝謝!