jQuery更改表单的选定属性并在更改时提交表单
如果这个问题不是一个重复的问题,我会非常惊讶。我寻找这个问题的答案已经有一段时间了,但我没有找到。如果之前有人问过这个问题,我很抱歉再次问,如果你能给我指出已经回答了这个问题的问题,那就太好了 无论如何,我正在尝试使用jQuery在表单更改后提交表单。那部分很好用。当表单更改时,工作不正常的零件正在更改select attr。目标很简单:每次更改表单时,应将其更改为的值指定为选定的属性true,然后提交表单 HTMLjQuery更改表单的选定属性并在更改时提交表单,jquery,forms,Jquery,Forms,如果这个问题不是一个重复的问题,我会非常惊讶。我寻找这个问题的答案已经有一段时间了,但我没有找到。如果之前有人问过这个问题,我很抱歉再次问,如果你能给我指出已经回答了这个问题的问题,那就太好了 无论如何,我正在尝试使用jQuery在表单更改后提交表单。那部分很好用。当表单更改时,工作不正常的零件正在更改select attr。目标很简单:每次更改表单时,应将其更改为的值指定为选定的属性true,然后提交表单 HTML <!DOCTYPE html> <html>
<!DOCTYPE html>
<html>
<head>
<title>Drop Down</title>
</head>
<body>
<form id='example' method='GET' action='index.php'>
<select id='menu' name='family'>
<option value='Kristen'>Kristen</option>
<option value='Henk'>Henk</option>
<option value='Andrew'>Andrew</option>
<option value='Derek'>Derek</option>
</select>
</form>
<script src='http://code.jquery.com/jquery-1.8.3.min.js'></script>
<script src='script.js'></script>
</body>
</html>
当值更改但所选属性未更改时,表单正在提交。我知道所选属性没有改变,因为表单提交后,第一个值Kristen始终显示为默认值
提前感谢您的回答,如果这是一个重复的问题,我再次感到抱歉-同时我将继续搜索答案。您需要找到所选的选项元素,
更改处理程序中的此
指的是所选元素,而不是所选的选项元素
您可以使用选择器
演示:因为您不保存上次选择的值,所以默认选择的值是选项中的第一个值 如果要保留上次选定的属性,可以在提交页面后使用cookie或PHP代码检查选定值,尝试在您的案例中使用:
if($.cookie('selectVal') != null) {
$('#menu option[value="' + $.cookie('selectVal') + '"]').prop('selected', true);
}
$('#menu').change(function() {
$.cookie('selectVal', $('#menu option:selected').val(), { expires: 7, path: '/'});
$(this).find("option[selected='true']").removeAttr('selected');
$(this).find('option:selected').prop('selected', 'true');
this.form.submit();
});
请参阅-在Chrome中,属性的值似乎被重置为
selected
,而不是true
。我认为他不需要这个,只需提交表单即可。他的问题是在重新加载页面时显示所选内容,这必须在后台代码上完成。这在Fiddle中起作用。但是,当我将代码复制到Notepad++并取消对提交行的注释时,代码不再工作。当我将其包含在document.ready函数中时,出现了一个错误。表格根本没有提交。我在提交表单下添加了一个警告,看看它是否达到了那个点,但它没有。这段代码是否包含我丢失的语法错误,或者将其包含在document.ready函数中是错误的?我没有测试这段代码,顺便问一下,控制台中的具体错误是什么?
$(document).ready(function() {
$('#menu').change(function() {
//remove the select attr from the option that currently has a value of selected
$(this).find("option[selected='true']").removeAttr('selected');
//add the selected attr with value of true to the option that was clicked on
$(this).find('option:selected').attr('selected', 'true');
//submit the form
this.form.submit();
});
});
if($.cookie('selectVal') != null) {
$('#menu option[value="' + $.cookie('selectVal') + '"]').prop('selected', true);
}
$('#menu').change(function() {
$.cookie('selectVal', $('#menu option:selected').val(), { expires: 7, path: '/'});
$(this).find("option[selected='true']").removeAttr('selected');
$(this).find('option:selected').prop('selected', 'true');
this.form.submit();
});