我有一个由 Perl 语言生成的表单。我想自定义这个表单来添加css效果,而不使用默认的perl表单。
该表格运作良好。我可以在启动查询之前选择每个单选按钮。但在验证表格后,
单选按钮的焦点始终返回默认复选框,即日期。我认为问题不是来自 Perl,而是来 self 使用 javascript 函数执行此操作的方式。但我没有找到如何动态更改复选框并在表单验证后选择当前复选框?
有人有想法吗?
预先感谢您
这是我的 html (html 5) 脚本:
print '<form name="newForm">';
print '<div>';
print '<input type="radio" name="sort" id="rdo-1" value="up2date" checked>';
print '<label for="rdo-1"><span>Date</span></label>';
print '</div>';
print '<div>';
print '<input type="radio" name="sort" id="rdo-2" value="title" >';
print '<label for="rdo-2"><span>Title</span></label>';
print '</div>';
print '<div>';
print '<input type="radio" name="sort" id="rdo-3" value="author">';
print '<label for="rdo-3"><span>Author</span></label>';
print '</div>';
print '<button type="submit" style="margin-right: 15px;" onClick="sorting()">Sort</button>';
print '</form>';
print "<br />\n";
这是我的 JavaScript :
function sorting() {
if (document.getElementById("rdo-1").checked){
document.getElementById("newForm").submit();
document.getElementById("rdo-1").checked = true;
document.getElementById("rdo-1").focus();
} else if (document.getElementById("rdo-2").checked){
document.getElementById("newForm").submit();
document.getElementById("rdo-2").checked = true;
document.getElementById("rdo-2").focus();
} else {
document.getElementById("newForm").submit();
document.getElementById("rdo-3").checked = true;
document.getElementById("rdo-3").focus();
}
}
最佳答案
首先,您不应该使用内联事件处理程序。其次,您多次提交表单。只需单击提交按钮,浏览器就会提交表单。然后,在 JavaScript 中,您将重新提交表单(为什么?)。第三,提交表单后,您的 onclick 可能会被触发。使用 jQuery 和提交事件:
(function($) {
$(function() {
$('form[name="newForm"]').submit(function() {
var rdoOne = $('#rdo-1'),
rdoTwo = $('#rdo-2'),
rdoThree = $('#rdo-3');
if (rdoOne.is(':checked')) {
rdoOne.focus();
}
else if (rdoTwo.is(':checked')) {
rdoTwo.focus();
}
else if (rdoThree.is(':checked')) {
rdoThree.focus();
}
});
});
})(jQuery);
关于javascript - 如何使用javascript动态更改当前复选框的默认复选框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51926210/