How to determine which checkboxes are checked in an HTML form? - javascript

I have 11 checkboxes in my HTML form and already have a section in my onclick function to determine how many of them were checked, but I would like to be able to tell which of the checkboxes were checked, and possibly just add whichever checkboxes were checked to an arraylist by id/value etc.
EDIT: (Fixed code..?)
var formobj = document.forms[0];
var ingNum = 0;
checked = [];
for (var j = 0; j < formobj.elements.length; j++) {
if (formobj.elements[j].type == "checkbox" && formobj.elements[j].checked) {
ingNum++;
checked.push(formobj.elements[j].value);
}
}

If you want to convert the ones checked to an array of their value attributes (if id attribute, swap value with id), you could use...
var inputs = document.getElementById('your-form').getElementsByTagName('input'),
checked = [];
for (var i = 0, length = inputs.length; i < length; i++) {
if (inputs[i].type == 'checkbox' && inputs[i].checked) {
checked.push(inputs[i].value);
}
}
That will work on any of the older IEs you may care about.
If you have the luxury of only supporting newer browsers, you could use...
var checked = [].slice.call(document
.querySelectorAll('#your-form input[type="checkbox"]'))
.filter(function(checkbox) {
return checkbox.checked;
})
.map(function(checkbox) {
return checkbox.value;
});
If you were using a library such as jQuery, it's even simpler...
var checked = $('#your-form :checkbox:checked')
.map(function() {
return this.value;
})
.get();

var checkedBoxes = [];
$("input:checked").each(function() {
checkedBoxes.push($(this));
});
Actually, I think you could just do this:
var checkedBoxes = $("input:checked");
but I'm not 100% sure if that works.

Related

How to change the parameters of getElementById in a loop

I am working on a form, and I would like to reset the lines individually without using reset.
How to vary the values ​​of the attribute passed as parameter of the method getElementById in JavaScript using a loop?
Here is an example of my source code below:
<script>
var element = document.getElementById('#re');
element.addEventListener('click', function() {
document.getElementById("#id1").value = "";
document.getElementById("#id2").value = "";
document.getElementById("#id3").value = "";
});
</script>
Assuming your IDs have the format shown in your example:
for (var i = 1; i <= 3; i++) {
document.getElementById("id" + i).value = "";
}
If that's not the case but you know the ID of every element you can put all IDs in an array and use that:
var elementIds = ["id1", "id2", "id3"];
elementIds.forEach(function(id) {
document.getElementById(id).value = "";
});
Another solution is to give all the elements you want to reset a specific class and target that:
var elements = document.getElementsByClassName("resetable-element");
[].slice.call(elements).forEach(function(element) {
element.value = "";
});
Instead of using ids, you can loop through your inputs for example:
var inputs = document.querySelectorAll("input");
for (var i = 0; i < inputs.length; i++) {
inputs[i].value = "";
}
For your simple example, you could loop through the values 1 - 3 (I assume the # in the ID is a typo?):
for(var i = 1; i <= 3; i++) {
document.getElementById('id' + i).value = '';
}
If you can identify the elements by something else, such as a class name, you might prefer to iterate over that:
var elements = document.querySelectorAll('.field');
Array.prototype.slice.call(elements).forEach(function(element) {
element.value = '';
});

how to Delete duplicate items on asp:dropdownlist, Sharepoint Designer 2013

I have used asp:drowdownlist on dataviewwebpart and is bind with source spdatasource1.
It have multiple duplicate items. How could I delete those duplicate item
asp:DropDownList runat="server" id="DropDownList1" DataValueField="ID" DataTextField="ProgramMaster" DataSourceID="spdatasource1" AutoPostBack="False" AppendDataBoundItems="True" ToolTip="Select a Program from the list"/>
Also, It is showing items in following formation ID;#ProgramName. How can I get programName only.
Well I use JQuery to remove duplicates item from asp:dropdownlist and here's the code if in-case somebody might need it. The code works in four part, Get the value from Dropdown, strip off the Duplicates and get the value in usable form, Remove the existing value from Dropdown and last set or append the values back to the dropdown list.
<script type="text/javascript">
$(document).ready(function(){
var handles= [];
$('#DropDownList1 option').each(function() {
var Prog1 = $(this).attr('text');
if(Prog1 != 'All'){
var Prog2 = Prog1.split(';#');
handles.push('All');
handles.push(Prog2[1]);
}
//Remove The existed Dropdownlist value
$("select#DropDownList1 option[value='" + $(this).val() + "']").remove();
//$(this).val().remove();
});
//Removing the Duplicates
var individual = [];
for (var i = 0; i<handles.length; i++) {
if((jQuery.inArray(handles[i], individual )) == -1)
{
individual .push(handles[i]);
}
}
//Inserting or setting the value from array individual to the dropdownlist.
var sel = document.getElementById('DropDownList1');
for(var i = 0; i < individual.length; i++) {
var opt = document.createElement('option');
opt.innerHTML = individual[i];
opt.value = individual[i];
sel.appendChild(opt);
}
});
</script>
P.S if the given ID didn't work fine for dropdown, get the ID from IE debugging tool which will be in form ctl00_PlaceHolderMain_g_a0a2fb36_2203_4d2e_bcd4_6f42243b880f_DropDownList1
you can do this with jquery
var usedNames = {};
$("select[name='company'] > option").each(function () {
if(usedNames[this.text]) {
$(this).remove();
} else {
usedNames[this.text] = this.value;
}
});
or with server side code try this
void RemoveDuplicateItems(DropDownList ddl)
{
for (int i = 0; i < ddl.Items.Count; i++)
{
ddl.SelectedIndex = i;
string str = ddl.SelectedItem.ToString();
for (int counter = i + 1; counter < ddl.Items.Count; counter++)
{
ddl.SelectedIndex = counter;
string compareStr = ddl.SelectedItem.ToString();
if (str == compareStr)
{
ddl.Items.RemoveAt(counter);
counter = counter - 1;
}
} } }

Loop though all input boxes and clear them

How can I, using javascript, loop through all input boxes on a page and clear the data inside of them (making them all blank)?
Try this code:
​$('input').val('');
It's looping over all input elements and it's setting their value to the empty string.
Here is a demo: http://jsfiddle.net/maqVn/1/
And of course if you don't have jQuery:
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i += 1) {
inputs[i].value = '';
}​​​​
Since I prefer the functional style, you can use:
Array.prototype.slice.call(
document.getElementsByTagName('input'))
.forEach(function (el) {
el.value = '';
});
[].forEach.call(document.getElementsByTagName('input'), function(e){
e.value = '';
});
Edit: If you want to grab textareas and other elements, you can use querySelectorAll:
[].forEach.call(
document.querySelectorAll('input, textarea'),
function(e) { e.value = ''; }
);
var inputs = document.getElementsByTagName("input"),
clearTypes = { "text" : 1, "password" : 1, "email" : 1 }, // etc. you fill this in
i = inputs.length,
input;
while (i) {
if (clearTypes[(input = inputs[--i]).type]) {
input.value = "";
}
}
Just to register an alternative without JavaScript, the HTML element <input type="reset" /> clear all fields of the form. In some scenarios it may be enough.
Without jquery:
var list = document.getElementsByTagName('input');
for(var i = 0; i < list.length; i++) {
if(list[i].type == 'text' || list[i].type == 'password')
list[i].value = '';
}
You are able to do something like tha following:
<script>
e = document.getElementsByTagName('input');
for (i = 0; i < e.length; i++){
if (e[i].type != 'text') continue;
e[i].value = '';
}
</script>
Edited: added exclude for input which their types are not text!

Selecting ONE radio out of many

I'm trying to "modify/change" the way this code works, I want it to only allow ONE radio button selection out of 30 or more choices. as it is written now, it looks for all selected before submitting. im a noob, please be kind.
<script type="text/javascript">
function checkform() {
//make sure all picks have a checked value
var f = document.entryForm;
var allChecked = true;
var allR = document.getElementsByTagName('input');
for (var i=0; i < allR.length; i++) {
if(allR[i].type == 'radio') {
if (!radioIsChecked(allR[i].name)) {
allChecked = false;
}
}
}
if (!allChecked) {
return confirm('One or more picks are missing for the current week. Do you wish to submit anyway?');
}
return true;
}
function radioIsChecked(elmName) {
var elements = document.getElementsByName(elmName);
for (var i = 0; i < elements.length; i++) {
if (elements[i].checked) {
return true;
}
}
return false;
}
</script>
Use a counter instead of a flag for "allChecked".
Set it to zero. If the element is checked, use allChecked++ then check to see if the value is ONE at the end.

javascript to create multiple checkboxes in for statement

Hi I am trying to create a bunch of checkboxes without having to make each one currently I have:
function test(obj) {
if (document.getElementByID("info").checked == true) {
document.getElementById("gender")[0].disabled = true;
}
}
and it works for one checkbox but I have been trying to use the code below:
function test(obj) {
var x = obj.name;
var rowCount = $('#List tr').length;
for (var i = 0; i rowCount-1; i++) {
if (x == document.getElementByID("info"["+i+"]).checked == true) {
document.getElementById("gender"["+i+"]).disabled = true;
}
}
}
to create as many checkboxes as I want without me having to make each one but it doesn't seem to be working.
Ok, lets start from the beginning:
To create a check-box in javascript you must do something like this:
var checkbox = document.createElement("input");
checkbox.type = "checkbox";
Then to add your checkbox into a div on your webpage you would do something like:
document.getElementById("your_div_id").appendChild(checkbox);
Then to see if the checkbox is checked you look at the "checked" property like so:
var isChecked = !!document.getElementById("your_checkbox").checked;
if(isChecked == true){
// Do whatever you want
}
Here's a function that would loop through a bunch of checkboxes
function testCheckBoxes(container_id){
var checkboxes = document.querySelector("#" + container_id + " > input[type='checkbox']");
for(var i = 0; i < checkboxes.length; i++){
if(!!checkboxes[i].checked == true){
// Your code
}
}
[Side Note: I'm using document.querySelector for consistency but since I think you're using jquery then use $ instead]
If you want to do something when someone clicks on your checkbox the use an event listener:
var list = document.getElementsByClassName("checkbox");
for(var i = 0; i < list.length; i++){
list[i].addEventListener('click', function(event){
if(!!event.target.checked == true){
// Do something
}
}, true);
}
Hopefully this is enough to get you started. Good Luck =)

Categories