从下拉菜单中激活或选中带有onchange事件的复选框

问题描述:

JavaScript和我永远都不是最好的朋友.

Javascript and I will never be best friends.

我尝试通过更改下拉列表中的元素来设置要选中的复选框.

I try to set a checkbox to checked by changing the elements from a dropdownlist.

这是代码段

<select name="change_status_to" id="sel">
  <option>....</option>
  <option>....</option>
</select>

<input type="checkbox" name="do_status_change" value="on">

如何将Javascript与onchange-event结合使用,以将复选框设置为选中状态?

How could I use Javascript with the onchange-event to set the checkbox to the state checked?

以下是您应该与javascript成为朋友的一个示例.

Here is an example of why you should be friends with javascript.

JSFiddle- http://jsfiddle.net/juc7Q/1/

JSFiddle - http://jsfiddle.net/juc7Q/1/

HTML

You're feeling toward Javascript
<select name="friends" id="friends">
    <option value="love">I love JS</option>
    <option value="weird">JS is weird</option>
    <option value="misunderstood">Are we speaking the same language?</option>
</select>

<button id="selectWeird">Keep JS Weird</button>
<div>
    <input type="checkbox" id="we_friends"> - Friends?
</div>

JavaScript

//Select this using js
var list = document.getElementById('friends');
var cb = document.getElementById('we_friends');

//Add event when change happens
list.onchange = function () {
    var value = list.value;
    if(value == 'love') {
        alert('I knew you would come around');
        cb.setAttribute('checked', '');
    } else if(value == 'weird') {
        alert('And I like being weird :-)!!');
        cb.removeAttribute('checked');
    } else {
        alert('And you think I understand you?');
        cb.removeAttribute('checked');
    }
}

//Change to 'Weird' when I click on it
var btn = document.getElementById('selectWeird');
btn.onclick = function () {
    list.options.selectedIndex = 1;
}