I have these buttons and want to click the selected ones at one time
<div class="form-group">
<input type="checkbox">
<label><button onclick="alert('a')">button1</button></label>
</div>
<div class="form-group">
<input type="checkbox">
<label><button onclick="alert('b')">button2</button></label>
</div>
<div class="form-group">
<input type="checkbox">
<label><button onclick="alert('c')">button3</button></label>
</div>
<button>go</button>
I tried some jquery stuff but not made it
Instead of just giving you some code:
class to your checkboxes as well. Like: class="chk"on* handlers. JS should be in one place only, and that's its respective tag or file. Use addEventListener instead<button> inside <label> since it will steal the focus.value attribute. Use that attribute to store the desired value.for attributes. Either add id to your INPUTs and for to your labels, or just wrap everything inside the LABELtype="button" on your buttonsprompt, alert. Replace those with a proper UI. For testing purpose use console// DOM utility functions:
const EL = (sel, par) => (par || document).querySelector(sel);
const ELS = (sel, par) => (par || document).querySelectorAll(sel);
// Task:
const doSomething = (EL_chk) => {
// Do something...
console.log(EL_chk.value);
};
// Add change events to each checkbox
ELS(".chk").forEach((EL_chk) => {
EL_chk.addEventListener("input", () => doSomething(EL_chk));
});
// On button GO click, target the checked ones
EL("#go").addEventListener("click", () => {
ELS(".chk:checked").forEach(doSomething);
});
.btn {
display: inline-block;
background: #eee;
padding: 0.3rem 0.5rem;
border-radius: 0.2rem;
border: 0;
}
<div class="form-group">
<label>
<input class="chk" type="checkbox" value="a">
<!-- DON'T USE <button> INSIDE A LABEL -->
<span class="btn">button A</span>
</label>
</div>
<div class="form-group">
<label>
<input class="chk" type="checkbox" value="b">
<span class="btn" data-click="a">button B</span>
</label>
</div>
<div class="form-group">
<label>
<input class="chk" type="checkbox" value="c">
<span class="btn">button C</span>
</label>
</div>
<button id="go" class="btn" type="button">GO</button>
Try this. In JS we are selected button with checkbox status checked and then triggering click event.
function go() {
document.querySelectorAll('input[type="checkbox"]:checked ~ label > button').forEach(function(element){
element.click();
})
}
<div class="form-group">
<input type="checkbox" >
<label ><button onclick="alert('a')">button1</button></label>
</div>
<div class="form-group">
<input type="checkbox" >
<label ><button onclick="alert('b')">button2</button></label>
</div>
<div class="form-group">
<input type="checkbox" >
<label ><button onclick="alert('c')">button3</button></label>
</div>
<br>
<button onclick="go()">go</button>