2014-01-23 62 views
1

如果此问题不是重复问题,我将非常惊讶。我已经寻找了一段时间来回答这个问题,但我还没有找到答案。如果在我再次提出问题之前已经问过这个问题,如果你能指出我已经回答了这个问题的问题,那将是非常好的。jQuery更改所选表单的属性并提交表单

无论如何,我想使用jQuery提交表单,一旦它被更改。这部分工作得很好。工作不正常的部分是在表单更改时更改选择属性。目标很简单:每次表单被改变时,它被改变的值应该被赋予一个真正的选定attr,然后表单应该被提交。

的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> 

的JS

$(document).ready(function() { 
    $('#menu').change(function() { 
     //remove the select attr from the option that currently has a value of selected 
     $("option[selected='true']").removeAttr('selected'); 
     //add the selected attr with value of true to the option that was clicked on 
     $(this).attr('selected', 'true'); 
     //submit the form 
     this.form.submit(); 
    }); 
}); 

当值改变,但所选择的ATTR是不会改变的形式被提交。我知道所选的attr没有变化,因为在表单提交后,第一个值Kristen总是显示为默认值。

在此先感谢您的答复,如果此问题最终成为重复问题,我将再次抱歉 - 同时我会继续寻找答案。

+0

请参阅http:// jsfiddle.net/arunpjohny/nfR2r/1/ - 该属性的值似乎被重置为“selected”,而不是“true”,在铬版中 –

回答

1

因为你不保存最后一次选择的值,默认选择的值是选项的第一个值。

如果你想保留最后选定的属性,您可以使用Cookie或使用PHP代码检查选定的值提交后网页

0

您需要在变更处理程序中查找选定的选项元素this请参阅选择元素而不是选定的选项元素。

可以使用:selected选择

$(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(); 
    }); 
}); 

演示:Fiddle

+0

我不认为他需要这个,只需将表单提交即可。他的问题是显示所选的东西,当页面重新加载时,必须在后面的代码 – ariel

+0

这可以在小提琴中使用。但是,当我将代码复制到Notepad ++并取消注释提交行时,代码不再有效。 – user3108671

1

尝试在你的情况下使用jQuery cookie

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(); 
}); 
+0

当我将这个包含在document.ready函数中时,出现错误。表格完全没有提交。我在表单提交下发出警报,看看它是否达到了这一点,但没有。这段代码是否包含我缺少的语法错误或者是否将它包含在document.ready函数中是错误的? – user3108671

+0

我没有测试这个代码,btw什么是控制台中的具体错误? – Felix