gpt4 book ai didi

javascript - 根据单个查询字符串填充多个复选框

转载 作者:行者123 更新时间:2023-12-03 02:50:03 24 4
gpt4 key购买 nike

我有一个带有表单的 View ,该表单在数据库中存储一些值。稍后我可以再次打开记录,它将通过查询字符串将存储的值传递到同一 View 中,填充字段。

适用于文本字段和下拉列表,但我无法对复选框进行相同的处理。问题是,它们都必须位于相同的 js var 中,进入相同的数据库字段,进入相同的查询字符串,然后再次进入复选框。

// for testing
function displayTest() {
var contacts = $('input[name="fieldtotest"]:checked').map(function () {
return this.value;
}).get();
$("#outputtest").val(contacts.join(","));
}
$(":checkbox").change(displayTest);
displayTest();

//gets all qs
function getParameterByName(name, url) {
if (!url) {
url = window.location.href;
}
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}

var setmyfield = getParameterByName('myqsvar');
if (setmyfield) {
// something that selects the right checkboxes
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group" align="left">
<div>
<label for="fieldtotest">Field to test</label>
</div>
<div>
<input type="checkbox" name="fieldtotest" value="John Smith">John Smith<br>
<input type="checkbox" name="fieldtotest" value="Joseph Augustine">Joseph Peter<br>
<input type="checkbox" name="fieldtotest" value="Sarah Smith">Sarah Smith<br>
<input type="checkbox" name="fieldtotest" value="Caroline Gabes">Caroline Gabes
</div>
</div>
<input type="text" id="outputtest" size="50">

如果该字段是一个简单的文本框,我会选择查询字符串并使用

$('#fileldid').val(qsvalueforthefield)

再次填充该字段,但我无法对单个 var/qs 中的多个复选框执行此操作。这可能吗?

最佳答案

如果您在 displayTest() 中创建了以逗号分隔的字符串形式的值列表,则可以循环遍历该字符串并选中相应的框。

var param = "Joseph Augustine,Caroline Gabes";
$.each(param.split(","), (i, val) =>
$(":checkbox[name=fieldtotest][value='" + val + "']").prop("checked", true));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group" align="left">
<div>
<label for="fieldtotest">Field to test</label>
</div>
<div>
<input type="checkbox" name="fieldtotest" value="John Smith">John Smith<br>
<input type="checkbox" name="fieldtotest" value="Joseph Augustine">Joseph Peter<br>
<input type="checkbox" name="fieldtotest" value="Sarah Smith">Sarah Smith<br>
<input type="checkbox" name="fieldtotest" value="Caroline Gabes">Caroline Gabes
</div>
</div>
<input type="text" id="outputtest" size="50">

关于javascript - 根据单个查询字符串填充多个复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47914432/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com