Question

To know if the checkbox has been checked or not, I have been calling this function. (when the user click submit button) delete_checkbox is the id of the checkbox field that is being checked.

function ifChecked() {
   if(!document.getElementById("delete_checkbox").checked) 
        alert("Select the tweet!");
}

How can I check when the id of the checkbox is generated dynamically ? For example :

<input type="checkbox" id="1" />
<input type="checkbox" id="78" />

For the above 2 fields, how can the above function be modified when the user clicks the submit button ?

Was it helpful?

Solution

Give each of the checkboxes the same name. The <form> tag as a property called elements which gives you access to all the fields within the form.

<form ... onsubmit="foo(event, this);">
    <input type="checkbox" name="delete_me" id="1">
    <input type="checkbox" name="delete_me" id="2">
    <input type="checkbox" name="delete_me" id="3">

    <button type="submit">Submit</button>
</form>

Then some JavaScript:

function foo(event, form) {
    event.preventDefault(); // keep form from submitting

    var deleteCheckboxes = form.elements.delete_me;

    for (var i = 0; i < deleteCheckboxes.length; i++) {
        if (deleteCheckboxes[i].checked) {
            console.log(deleteCheckboxes[i].id + " is checked");
        }
    }
}

OTHER TIPS

If you want to know if there are any unchecked checkboxes:

if (document.querySelectorAll("input[type=checkbox]:not(:checked)").length > 0) {
    alert("Please select all the tweets!");
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top