I have these buttons and want to click the selected ones at one time
<div >
<input type="checkbox">
<label><button onclick="alert('a')">button1</button></label>
</div>
<div >
<input type="checkbox">
<label><button onclick="alert('b')">button2</button></label>
</div>
<div >
<input type="checkbox">
<label><button onclick="alert('c')">button3</button></label>
</div>
<button>go</button>
I tried some jquery stuff but not made it
CodePudding user response:
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 >
<input type="checkbox" >
<label ><button onclick="alert('a')">button1</button></label>
</div>
<div >
<input type="checkbox" >
<label ><button onclick="alert('b')">button2</button></label>
</div>
<div >
<input type="checkbox" >
<label ><button onclick="alert('c')">button3</button></label>
</div>
<br>
<button onclick="go()">go</button>
CodePudding user response:
Instead of just giving you some code:
- You're not assigning any click to your GO button (Why?)
- Add an ID to your GO button to help you query it in JS
- Assign a
class
to your checkboxes as well. Like: - Don't use unsafe inline
on*
handlers. JS should be in one place only, and that's its respective tag or file. Use addEventListener instead - Makes no sense to use
<button>
inside<label>
since it will steal the focus. - Your checkboxes are missing the
value
attribute. Use that attribute to store the desired value. - You're missing
for
attributes. Either addid
to your INPUTs andfor
to your labels, or just wrap everything inside the LABEL - You're missing
type="button"
on your buttons - Avoid the use of
prompt
,alert
. Replace those with a proper UI. For testing purpose useconsole
// 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 >
<label>
<input type="checkbox" value="a">
<!-- DON'T USE <button> INSIDE A LABEL -->
<span >button A</span>
</label>
</div>
<div >
<label>
<input type="checkbox" value="b">
<span data-click="a">button B</span>
</label>
</div>
<div >
<label>
<input type="checkbox" value="c">
<span >button C</span>
</label>
</div>
<button id="go" type="button">GO</button>