激活或从下拉菜单onchange事件检查复选框(Activate or check checkbox

2019-10-19 16:42发布

Javascript和我将永远是最好的朋友。

我尝试将复选框设置为通过改变从下拉列表中的元素进行检查。

这是片段

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

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

我怎么可以使用JavaScript与的onchange事件来设置的复选框选中状态?

Answer 1:

您可以设置其.checked属性:

document.getElementById("do_status_change").checked = true;
document.getElementById("do_status_change").checked = false;

但是,你需要设置一个id ; 该name属性是不够的。

>实施例<



Answer 2:

这就是为什么你应该是朋友与JavaScript的例子。

的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;
}


文章来源: Activate or check checkbox with onchange event from dropdown