简体   繁体   中英

check checkbox by clicking button

I got a problem with checking checkboxes by clicking a separate button. For example I want to check the Mercedes SLK checkbox by clicking the button unterneath. How can I implement that?

Thanks in advance for your feedbacks.

Example code:

<form action="">
<input type="checkbox" name="vehicle" value="volvo">Volvo XC90<br>
<input type="checkbox" name="vehicle" value="bmw">BMW 325i<br> 
<input type="checkbox" name="vehicle" value="mercedes">Mercedes SLK
</form>
<button type="button">Check Mercedes SLK</button> 

Try This:

$("select[name='cars'] option[value='mercedes']").prop('checked', true)

demo

just take this inside button click.

将此添加到您的按钮元素:

onclick="document.getElementById('mercedes').checked = true"

Wthout changing the html and giving IDs which in itself would be a good idea.

Plain JS:

window.onload=function() {
  document.querySelector("button").onclick=function() {
    document.getElementsByName("vehicle")[2].checked=true;
  }
}

jQuery:

DEMO

$(function() {
  $("button").on("click",function() {
    $("input[value='mercedes']").prop("checked",true);
  });
});

you can do it using jquery like that:

<form>
<input type="checkbox" name="vehicle" value="volvo">Volvo XC90<br>
<input type="checkbox" name="vehicle" value="bmw">BMW 325i<br> 
<input type="checkbox" id="slk" name="vehicle" value="mercedes">Mercedes SLK
</form>
<button id="checkSlk" type="button">Check Mercedes SLK</button> 

<script type="text/javascript">
    $(function () {
        $("#checkSlk").on("click", function () {
            if ($("#slk").is(':checked')) {
                $("#slk").attr("checked", false);
            } else {
                $("#slk").attr("checked", true);
            }
        });
    });
</script>

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