从下拉菜单中激活或选中带有onchange事件的复选框 [英] Activate or check checkbox with onchange event from dropdown

查看:181
本文介绍了从下拉菜单中激活或选中带有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;
}

这篇关于从下拉菜单中激活或选中带有onchange事件的复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆