使用javascript提交后如何保留选定的下拉列表值

时间:2014-05-31 13:07:41

标签: javascript php jquery html

如何在页面刷新后保留所选项目,我在多重选择中有一种语言,

我现在尝试使用java脚本这里是我的代码它无法正常工作,任何人都可以指导我如何选择它

我的HTML代码

<div class="control-group">
<label for="textfield" class="control-label">Language</label>
<div  class="controls">
    <select name="myLanguage" id="myLanguage" multiple="multiple">
        <option value="English,">English,</option>
        <option value="Arabic,">Arabic,</option>
        <option value="Hindi,">Hindi,</option>
        <option value="Malayalam,">Malayalam,</option>
        <option value="Danish,">Danish,</option>

    </select>
</div>
</div>

的javascript

 document.getElementById('myLanguage').value = "<?php echo $_GET['language'];?>";

5 个答案:

答案 0 :(得分:1)

如果你使用jQuery,请使用:

$(document).ready(function(){
    $('#myLanguage').val("<?php echo $_GET['language'];?>");
});

答案 1 :(得分:0)

Javascript没有使用会话变量,因此无法将值添加到会话中。你仍然可以做两件事:

选项1: 使用Jquery将值添加到cookie:

Set: $.cookie("test", 1);

Read: var value = $.cookie("test");

了解详情:How do I set/unset cookie with jQuery?

选项2: 将值发布到新页面并请求该页面:

读取值可以通过以下方式完成:

Read: $_REQUEST["my_variable"];

注意:读数值可以像:

$("#myLanguage option:selected").text();

答案 2 :(得分:0)

如果您使用HTML5作为doctype,则可以轻松地将值存储在localStorage中。

参考:http://www.w3schools.com/html/html5_webstorage.asp

设置它:

localStorage.setItem("variable_name", variable_value);

获得它:

localStorage.variable_name

删除它:

localStorage.removeItem("variable_name");

如果您愿意,也可以将js cookies与 jquery.cookie 插件一起使用。

答案 3 :(得分:0)

As mentioned in the comments, when using the multiple attribute, 
the name attribute must be an array such as:

<div class="control-group">
    <label for="myLanguage[]" class="control-label">Language</label>
    <div  class="controls">
        <select name="myLanguage[]"  multiple="multiple"> 
            <option value="English,">English,</option>
            <option value="Arabic,">Arabic,</option>
            <option value="Hindi,">Hindi,</option>
            <option value="Malayalam,">Malayalam,</option>
            <option value="Danish,">Danish,</option>
        </select>
    </div>
</div>

javascript // Note: I'm not so sure on the following syntax

   var myLanguage[] = document.elements('myLanguage[]').value;

答案 4 :(得分:0)

<?php
$languages = array(
  'en' => 'english',
  'vi' => 'vietnamese',
  'cn' => 'chinese'
);

if (isset($_GET['lang']) AND array_key_exists($_GET['lang'], $languages))
{
    include './lang/' . $languages[$_GET['lang']] . '.php';
}
else
{
    include './lang/english.php';

}
?>