简体   繁体   English

触发复选框单击按钮

[英]Trigger checkbox click with button

I'm trying to change my 'send' button which onClick sends a message from an input box to a div, to also trigger the click of a 'checkbox' input. 我正在尝试更改我的“发送”按钮,即onClick将消息从输入框发送到div,以触发单击“复选框”输入。

HTML HTML

<button type="submit" class="btn btn-default">Post</button> 
   <input name="stry" type="text" id="stry"/> 
   <input name="nope" type="text" id="message-input"/>
        <input type="checkbox" name="sendsms" onclick="copyStory(this)">

*These buttons are actually in a form *这些按钮实际上是一种形式

JS JS

 function copyStory(ch) {
     if (ch.checked)
         var text1 = document.getElementById("message-input").value;
     else
         text1 = '';
     document.getElementById("stry").value = text1;
 }

I've searched around but I can't find a way to make the send button trigger the checkbox, any suggestions? 我到处搜索,但是找不到使发送按钮触发复选框的方法,有什么建议吗?

So what you need is to have same handler for both onclick and onchange events. 因此,您需要为onclickonchange事件具有相同的处理程序。 Try this way, 试试这个

HTML : HTML:

<input type="button" id="sendButton" value="Send" onclick="copyStory(this)" />
<input name="nope" type="text" id="message-input"/>
<input type="checkbox" name="sendsms" onchange="copyStory(this)"/>

<div id="msgDiv"></div>

javaScript : javaScript:

 function copyStory(ch) {
     var text1
     if (ch.checked || ch.id == "sendButton")
         text1 = document.getElementById("message-input").value;
     else
         text1 = document.getElementById("msgDiv").innerText = "";

     document.getElementById("msgDiv").innerText = text1;
 }

jsFiddle 的jsfiddle

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

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