简体   繁体   English

JavaScript:根据下拉菜单选择,选中/取消选中复选框

[英]JavaScript: Check/Uncheck box depending on dropdown menu selection

I am trying to get a check box to tick its self if a drop down list item is selected. 如果选择了下拉列表项,我试图获得一个复选框以勾选其自身。 For example, if 'Entry 0' is selected in the drop down, i want the check box '0 is selected' to be checked. 例如,如果在下拉列表中选择了“条目0”,则我希望选中“选择了0”复选框。 Also, if an entry other than 'Entry 0' is selected, I want the check box '0 is selected' to be unchecked. 另外,如果选择了除“条目0”以外的其他条目,则我希望取消选中“选择0”复选框。 The code i have uses 2 drop down menu items, and 2 corresponding check boxes. 我使用的代码使用2个下拉菜单项和2个相应的复选框。 Currently only check box 1 works, and does not deselect when another drop down item is selected. 当前仅复选框1有效,并且在选择另一个下拉项时不会取消选择。

I have searched the net and google for hours and cannot seem to find a solution. 我已经在互联网和Google上搜索了几个小时,但似乎找不到解决方案。 I am new to JavaScript, but need this for an online form. 我是JavaScript的新手,但需要在线表格。 (once I understand how to get this solution working, I should be able to put it into my online form.) (一旦我了解了如何使该解决方案生效,我应该可以将其放入在线表单中。)

<body>
<script language="JavaScript">
function onChange() {
   if (document.formName3.selectName3 = 'Entry 0')
 //{ alert("Option changed")
{ document.formName3.c_0.checked = true;
 document.formName3.c_1.checked = false;
}
  else if (document.formName3.selectName3 = 'Entry 1')
 //{ alert("Option changed")
{document.formName3.c_1.checked = true;
 document.formName3.c_0.checked = false;
 }}
{ alert("Begin")
 document.formName3.c_1.checked = true;
}
</script>

<form
  name="formName3" id="formName3"
  onSubmit="return false;"
>
  <p>
  <select
  name="selectName3"
  onChange="onChange()"
>
    <option
  value="Option 0" selected="selected"
>
      Entry 0
      <option
  value="Option 1"
>
      Entry 1
    </select>


  <p>
    <input name="c_0" type="checkbox" id="c_0" />
    <label for="c_0">0 Is selected</label>
  </p>
  <p>
    <input name="c_1" type="checkbox" id="c_1" />
    <label for="c_1">1 Is selected</label>
  </p>
</form>
</body>
    </html>

Can you let me know how to get it working please? 您能告诉我如何使其工作吗? Once I understand how to do this, i can apply it as a feature to my online form. 一旦了解了操作方法,便可以将其作为功能应用到我的在线表格中。 Thanks!!! 谢谢!!!

There are a couple of problems here. 这里有两个问题。

The following conditional will be true every time it is executed because you are using one equals sign instead of two. 由于您使用的是一个等号而不是两个,因此以下条件在每次执行时都会成立。 (= instead of ==). (=而不是==)。 You need to always use two equals signs when comparing values. 比较值时,必须始终使用两个等号。

if (document.formName3.selectName3 = 'Entry 0')

Second, the way you are trying to find the value of the currently selected option is incorrect. 其次,您尝试查找当前所选选项的值的方式不正确。 Instead of: 代替:

document.formName3.selectName3

You can use the following: 您可以使用以下内容:

document.formName3.selectName3.options[document.formName3.selectName3.selectedIndex].value

There are many other ways, but this is acceptable. 还有许多其他方法,但这是可以接受的。

To put these two suggestions together, the code now becomes: 为了将这两个建议放在一起,代码现在变为:

function onChange() {
    var selectValue = document.formName3.selectName3.options[document.formName3.selectName3.selectedIndex].value;
    if (selectValue == 'Entry 0') { 
        document.formName3.c_0.checked = true;
        document.formName3.c_1.checked = false;
    } else if (selectValue == 'Entry 1') {
        // ... ;
    }
}

Here is some more info: 这是更多信息:

http://www.mredkj.com/tutorials/tutorial002.html http://www.mredkj.com/tutorials/tutorial002.html

Start by turning all of your single "=" symbols into "===" in your 'if' conditions. 首先在“ if”条件下将所有单个“ =”符号变成“ ===”。

if ( foo === bar ){
 <<do something>>
}
if (document.formName3.selectName3 = 'Entry 0')

This is an assignment and not an equality check. 这是分配而不是相等性检查。 Use == or === . 使用=====
In the above code, the first if always evaluates to true . 在上面的代码中,第一个if始终计算为true

document.formName3.selectName3

Returns a DOM element, not the value. 返回DOM元素,而不是值。
To get the selected value from a select box, do: 要从选择框中获取选定的值,请执行以下操作:

var index = document.formName3.selectName3.selectedIndex;
var selectedValue = document.formName3.selectName3.options[ index ].value;

If you have a lot of options and checkboxes, the code will become quite extensive and a pain to maintain. 如果您有很多选项和复选框,则代码将变得相当广泛,并且很难维护。 You might want to consider using a library like jQuery or Prototype. 您可能要考虑使用jQuery或Prototype之类的库。

This code does what you want: 这段代码可以满足您的要求:

<html>
    <body>
        <script type="text/javascript">
            function onChange() {
                var selectBox = document.formName3.selectName3;
                var val = selectBox.value;
                i = 0;
                while(document.formName3["c_" + (i++)]) 
                    document.formName3["c_" + (i++)].checked = false;

                document.formName3["c_" + val].checked = true;
            }
        </script>

        <form name="formName3" id="formName3" onSubmit="return false;">
            <p>
                <select name="selectName3" onChange="onChange()">
                    <option value="0" selected="selected">Entry 0</option>
                    <option value="1">Entry 1</option>
                </select>
            </p>
            <p>
                <input name="c_0" type="checkbox" id="c_0" />
                <label for="c_0">0 Is selected</label>
            </p>
            <p>
                <input name="c_1" type="checkbox" id="c_1" />
                <label for="c_1">1 Is selected</label>
            </p>
        </form>
    </body>
</html>

Some pointers to help you learn: 一些帮助您学习的指针:

The current value of the select box is obtained with selectBox.value . 选择框的当前值是通过selectBox.value获得的。 This value is equal to the currently selected option' s value contents. 此值等于当前所选选项的value内容。

The function first clears all checkboxes, by taking advantage of a couple of javascript features. 该函数首先利用几个javascript功能清除所有复选框。 Notice the while loop. 注意while循环。 What that does is: 那是什么:

A. If an element named document.formName3["c_" + (i++)] , which is directly equivalent to document.formName3.c_0 exists, then set its value to false. A.如果存在一个名为document.formName3["c_" + (i++)]的元素,该元素直接等效于document.formName3.c_0 ,则将其值设置为false。

B. Increments i by one. B.将i加1。

C. Repeats, until i is equal to 2, at which point it can't find a checkbox like that, and stops. C.重复,直到i等于2,这时找不到这样的复选框,然后停止。

After all checkboxes have been cleared, the appropriate checkbox is checked. 清除所有复选框后,将选中相应的复选框。

Another final note: In javascript, you can access properties of objects by using the brackets syntax. 另一个最后的注意事项:在javascript中,您可以使用方括号语法访问对象的属性。 What that means, is that object1.property1 is directly equivalent to object1["property1"] . 这意味着object1.property1直接等效于object1["property1"]

Cheers, and I hope this helps. 干杯,我希望这会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM