简体   繁体   中英

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. Also, if an entry other than 'Entry 0' is selected, I want the check box '0 is selected' to be unchecked. The code i have uses 2 drop down menu items, and 2 corresponding check boxes. Currently only check box 1 works, and does not deselect when another drop down item is selected.

I have searched the net and google for hours and cannot seem to find a solution. I am new to JavaScript, but need this for an online form. (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

Start by turning all of your single "=" symbols into "===" in your 'if' conditions.

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 .

document.formName3.selectName3

Returns a DOM element, not the value.
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.

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 . This value is equal to the currently selected option' s value contents.

The function first clears all checkboxes, by taking advantage of a couple of javascript features. Notice the while loop. 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.

B. Increments i by one.

C. Repeats, until i is equal to 2, at which point it can't find a checkbox like that, and stops.

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. What that means, is that object1.property1 is directly equivalent to object1["property1"] .

Cheers, and I hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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