javascript 如何使用javascript在多选中设置选定的选项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13467799/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 18:51:49  来源:igfitidea点击:

How to set the selected options in multiselect with javascript

javascript

提问by Caderade

Alright, so this question has definitely been asked before, and I was actually able to find an answer to my question in jquery and when I tried to implement the answer I couldn't get it to work. I would just rather do it in java-script so.....

好的,所以这个问题之前肯定有人问过,我实际上能够在 jquery 中找到我的问题的答案,当我尝试实现答案时,我无法让它工作。我宁愿用java脚本来做,所以.....

I'm reading a string of text separated by commas from a DB, and I want to translate those into selected options in a multiselect box.

我正在从数据库中读取以逗号分隔的一串文本,我想将这些文本转换为多选框中的选定选项。

All I've been doing up to this point is trying to get the browser to select a single option which matches a hard-coded string when I click a button but I can't even get that to work. But I figured that since I'm asking the question, I might as well write out the whole script so you can see it all and maybe catch any other problems I can expect to have...lastly, how can I get this to run on the page's load? Sorry if this is redundant and rudimentary but I'm very new to JS and finding existing answers to questions to be of little help. Thanks in advance.

到目前为止,我一直在尝试让浏览器在我单击按钮时选择一个与硬编码字符串匹配的选项,但我什至无法让它工作。但我想,既然我在问这个问题,我不妨写出整个脚本,这样你就可以看到这一切,也许还能发现我可能遇到的任何其他问题......最后,我怎样才能让它运行在页面的负载?对不起,如果这是多余的和基本的,但我对 JS 很陌生,并且发现问题的现有答案几乎没有帮助。提前致谢。

EDIT

编辑

So, I found that I can get the assignment to work if I use 'select.options[i].value=true' (boolean instead of string) per Asad's answer. However, I am using Harvest's Chosen multiple select control: http://harvesthq.github.com/chosen/

所以,我发现如果我根据 Asad 的回答使用 'select.options[i].value=true' (布尔值而不是字符串),我可以让任务工作。但是,我正在使用 Harvest 的选择多选控件:http: //harvesthq.github.com/chosen/

The script will not work when I have assigned the chosen class to the control. I know that the control is calling on JQuery, is this the reason why? Is it possible to get it to work? Thanks again.

当我将选定的类分配给控件时,脚本将不起作用。我知道控件正在调用 JQuery,这是为什么?有可能让它工作吗?再次感谢。

function selectitems() {
  var select = document.getElementById("multiselectid");
  var array = stringFromDB.split(",");

  for(count=0, count<array.length, count++) {
    for(i=0; i<select.options.length; i++) {
      if(select.options[i].value == array[count]) {
        select.options[i].selected="selected";
      }
    }
  }
}

采纳答案by Ian

Your first forloop has two syntax errors. Try checking the console in your browser

您的第一个for循环有两个语法错误。尝试检查浏览器中的控制台

for(count=0, count<array.length, count++) {

should be:

应该:

for(count=0; count<array.length; count++) {

Notice the change of "," to ";" after the count=0and count<array.lengthparts.

注意将“,”改为“;” 在count=0count<array.length部分之后。

Also, you might want to use for(var count=0and for(var i=0so that the countand ivariables are not declared globally.

此外,您可能希望使用for(var count=0andfor(var i=0以便不全局声明counti变量。

回答by rink.attendant.6

Alright so I'm going to try to address all the parts of your question in my answer.

好的,所以我将尝试在我的回答中解决您问题的所有部分。

As Ian had mentioned, there is a syntax error in your forstatement.

正如伊恩所说,您的for语句中有语法错误。

On second thought I'll give the code then do the explanation. I have included the entire HTML document for purposes of clarity:

第二个想法我会给出代码然后做解释。为清楚起见,我包含了整个 HTML 文档:

<!DOCTYPE html>
<html lang=en-CA>
    <meta charset=utf-8>
    <title>JavaScript in multi-select</title>

    <script>

    function selectItems(stringFromDB) {
        'use strict';

        var select = document.getElementById("multiselectid"),
            stringArray = stringFromDB.split(","),
            count = 0,
            i;

        for(count = 0; count < stringArray.length; count += 1) {
            for(i = 0; i < select.options.length; i += 1) {
                if(select.options[i].value === stringArray[count]) {
                    select.options[i].selected = true;
                }
            }
        }
    }

    window.addEventListener('load', function() {
        'use strict';

        // The "string from DB" would be the parameter here
        selectItems( 'hockey,volleyball,football');
    }, false);

    </script>

    <body>
        <div>
            <select id='multiselectid' multiple>
                <option value="hockey">Hockey</option>
                <option value="golf">Golf</option>
                <option value="volleyball">Volleyball</option>
                <option value="football">Football</option>
            </select>
        </div>

Now for the explanation.

现在解释一下。

  1. Instead of using the traditional onloadevent attribute on the body element to run the script on page load (as you had wanted), I attached an event handler with the event loadto the windowDOM element. Event handlers are more useful as they help separate the JavaScript from the HTML (and many other reasons). You can read more about event handlers here: https://developer.mozilla.org/en-US/docs/DOM/element.addEventListener

  2. In the function selectItems(), I have put all of the variables onto one declaration to keep the code clean.

    3. To avoid potential issues with arrays, I have called the variable stringArrayinstead. arrayis a reserved word in JavaScript and could cause issues with some browsers, although I'm not completely sure which ones (if any).

  3. ALWAYS, ALWAYS, ALWAYS use ===instead of ==. That way you are sure the comparison is strict and correct (i.e. both things being compared are of the same type, in this case: strings).

  4. It is a good idea to force the handling of your JavaScript functions in strict mode by using 'use strict;'. This way the browser will stop (and throw exceptions) if it detects something that is not allowed, and thus allowing you to write better JavaScript code.

  1. 我没有使用onloadbody 元素上的传统事件属性在页面加载时运行脚本(如您所愿),而是将带有事件的事件处理程序附加loadwindowDOM 元素。事件处理程序更有用,因为它们有助于将 JavaScript 与 HTML 分开(以及许多其他原因)。您可以在此处阅读有关事件处理程序的更多信息:https: //developer.mozilla.org/en-US/docs/DOM/element.addEventListener

  2. 在函数中selectItems(),我将所有变量放在一个声明中以保持代码整洁。

    3. 为了避免数组的潜在问题,我stringArray改为调用变量。array是 JavaScript 中的保留字,可能会导致某些浏览器出现问题,尽管我不完全确定是哪些(如果有)。

  3. 始终,始终,始终使用===代替==。这样你就可以确定比较是严格和正确的(即被比较的两个东西都是相同的类型,在这种情况下:字符串)。

  4. 使用'use strict;'. 这样,如果浏览器检测到不允许的内容,它就会停止(并抛出异常),从而允许您编写更好的 JavaScript 代码。

Hope this helped, feel free to ask more questions if you're still confused!

希望这对您有所帮助,如果您仍然感到困惑,请随时提出更多问题!