jQuery。从URL获取参数值并选中单选按钮
我试图根据URL中参数的值自动检查单选按钮。在用户选择一些值并在上一页提交表单后,这些参数被添加到URL中。在下一页上有一个表单,其中包含相同的输入和一些其他输入。我想做的是检查用户在上一页为收音机选择的相同值 假设我有第二页的URL:domain.com/page.html?复选框一=1&复选框二=0 在本页中,我有无线电输入:jQuery。从URL获取参数值并选中单选按钮,jquery,html,url,checkbox,radio-button,Jquery,Html,Url,Checkbox,Radio Button,我试图根据URL中参数的值自动检查单选按钮。在用户选择一些值并在上一页提交表单后,这些参数被添加到URL中。在下一页上有一个表单,其中包含相同的输入和一些其他输入。我想做的是检查用户在上一页为收音机选择的相同值 假设我有第二页的URL:domain.com/page.html?复选框一=1&复选框二=0 在本页中,我有无线电输入: <input type="radio" name="checkbox-one" value="0" id="radio1" /> <
<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>
无线电1
无线电#2
收音机#3
无线电4
在这种情况下,我希望看到选中了name=“checkbox one”value=“1”
和name=“checkbox two”value=“0”
PHP解决方案是不可取的,那么如何使用jQuery实现这一点呢。有没有办法读取URL参数值并根据它们检查单选按钮
谢谢大家! 显示如何从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);
}
});
您应该注意,您一次只能选中一个单选框。接受的答案非常有用,但在我的情况下使用jQuery更可取,因此我使用了一种稍微不同的解决方案。我发现了一个很好的代码片段,为了我的目的,我对它做了一些修改
// 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);
});
};
//获取查询字符串参数
var vars=[],散列;
var query=document.URL.split(“?”)[1];
if(查询!=未定义){
query=query.split('&');
for(var i=0;i
该代码段解构查询字符串,并将参数及其值“放入”到单独的散列中。然后单选按钮检查功能被调用,就是这样
我将感谢您的意见和改进建议。谢谢大家! 谢谢你的回答,这很有帮助,给了我一个如何继续下去的想法。请参阅我的解决方案,它使用jQuery替代方案。