Making checkboxes checked using same id using Javascript - javascript

This is my code to make check boxes checked with same id
<input type="checkbox" name="MassApprove" value="setuju2" />
<input type="checkbox" name="MassApprove" value="setuju3" />
<input type="checkbox" name="MassApprove" value="setuju4" />
<input type="checkbox" name="MassApprove" value="setuju5" />
<input type="submit" value="Next Step" name="next" />
And This is my javascript code. I need to make this checkboxes as checked when am trigger this function. Help me!..
function doMassApprove(massApproveFlag) {
var confirmAlert = confirm("Do You Need Mass Approve !..");
var massApprove = document.getElementById("MassApprove").length();
if (confirmAlert == true) {
//alert(massApproveFlag);
for (var i = 0; i < massApprove; i++) {
document.getElementById("MassApprove").checked = true;
}
} else {
document.getElementById("headerMassApprove").checked = false;
}
}

IDs in HTML must be unique.
As you have already specified the name MassApprove, use Document.getElementsByName(),
Returns a nodelist collection with a given name in the (X)HTML document.
Which you can iterate using simple for loop
function doMassApprove(massApproveFlag) {
var confirmAlert = confirm("Do You Need Mass Approve !..");
if (confirmAlert) {
//Get elements with Name
var massApproves = document.getElementsByName("MassApprove");
//Iterate and set checked property
for (var i = 0; i < massApprove.length; i++) {
massApproves[i].checked = true;
}
} else {
document.getElementById("headerMassApprove").checked = false;
}
}

you do not have the same ID and should not since ID must be unique. You have the same NAME and that is fine. -
Do not user getElementById for names, instead use document.getElementsByName which will return a collection you can loop over
Like this
function doMassApprove(massApproveFlag) {
var massApprove = confirm("Do You Need Mass Approve !..");
if (massApprove) {
var checks = document.getElementsByName("MassApprove");
for (var i=0; i < checks.length; i++) {
checks[i].checked = massApprove; // or perhaps massApproveFlag?
}
}
else {
document.getElementById("headerMassApprove").checked = false;
}
}

Just for the heck of it, you can use some modern browser goodness:
Array.prototype.forEach.call(document.querySelectorAll('[name=MassApprove]'), function(cb){cb.checked = true});
and with arrow functions:
Array.prototype.forEach.call(document.querySelectorAll('[name=MassApprove]'), cb => cb.checked=true);

Related

Is it possible to use multiple for loop at same time?

I want to create a html form, it have 2 group(Name and fruit), each group have two check boxes, When user clicks the checkbox that input name are user_checkbox[] and fruit_checkbox[] , its will do something,i need to use array and for loop to get the user which group of checkboxes was checked , but it seems not to allow me use multiple for loop.
My Html File
//group1
<input name="user_checkbox[]" type="checkbox" value="Peter" onclick="showinputtext();" >Peter
<input name="user_checkbox[]" type="checkbox" value="Billy" onclick="showinputtext();" >Billy
//group2
<input name="fruit_checkbox[]" type="checkbox" value="Apple" onclick="showinputtext();" >Apple
<input name="fruit_checkbox[]" type="checkbox" value="Banner" onclick="showinputtext();" >Banana
My Javascript file
function showinputtext() {
var name = document.getElementsByName("user_checkbox[]");
var fruit = document.getElementsByName("fruit_checkbox[]");
for (var n = 0; n < name.length; n++) && for (var f = 0; f < fruit.length; f++) {
if(name[n].checked && fruit[f].checked){
dosomething..................
}
}
but it is not work for me, any idea?? thx
Try nested for loops.
function showinputtext(){
var name = document.getElementsByName("user_checkbox[]");
var fruit = document.getElementsByName("fruit_checkbox[]");
for (var i = 0; i < name.length; i++) {
for (var j = 0; j < fruit.length; j++) {
if(name[i].checked && fruit[j].checked){
alert("ok");
}
}
}
};
if you use jquery
try it :
Example
$("[type='checkbox']").on("click",function(){
var name = document.getElementsByName("user_checkbox[]");
var fruit = document.getElementsByName("fruit_checkbox[]");
for (var i = 0; i < name.length; i++) {
for (var j = 0; j < fruit.length; j++) {
if(name[i].checked && fruit[j].checked){
alert("ok");
}
}
}
});
Why not use forEach? Looks a bit nicer and does the same job in this instance:
function showInputText() {
var nameCheckboxes = document.getElementsByName("user_checkbox[]");
var fruitCheckboxes = document.getElementsByName("fruit_checkbox[]");
nameCheckboxes.forEach(function(nameCheckbox) {
fruitCheckboxes.forEach(function(fruitCheckbox) {
if (nameCheckbox.checked && fruitCheckbox.checked) {
alert ("ok");
};
});
});
I renamed the variables and the function to make this a bit more readable!
Just remember to change the function calls in the onclick attributes if you go for this approach:
// Group 1
<input name="user_checkbox[]" type="checkbox" value="Peter" onclick="showInputText();" >Peter
<input name="user_checkbox[]" type="checkbox" value="Billy" onclick="showInputText();" >Billy
// Group 2
<input name="fruit_checkbox[]" type="checkbox" value="Apple" onclick="showInputText();" >Apple
<input name="fruit_checkbox[]" type="checkbox" value="Banner" onclick="showInputText();" >Banana
However, reading your post, you might not need to do this at all. It seems unnecessary to iterate through both groups in a nested loop. Why not instead add each item to an array and "Do stuff" with both when the form is submitted?
I would change your checkboxes to have a fruit-input and user-input class:
<input type="checkbox" name="peter" class="user-input">
<input type="checkbox" name="banana" class="fruit-input">
Then I would add an event listener to the fruit-input and user-input elements which listen for changes to the checkboxes. When a change event occurs it then checks if the input has been checked or not, and it will then add or remove from either the selectedFruits or selectedUsers arrays:
document.getElementsByClassName("fruit-input")
.forEach(function(input){
input.addEventListener("change", selectFruit);
});
document.getElementsByClassName("user-input")
.forEach(function(input){
input.addEventListener("change", selectUser);
});
var selectedFruits = [];
var selectedUsers = [];
function selectFruit() {
var fruit = this.getAttribute("name");
if (this.checked) {
selectedFuits.push(fruit);
} else {
selectedFruits.remove(fruit);
}
}
function selectUser() {
var user = this.getAttribute("name");
if (this.checked) {
selectedUsers.push(user);
} else {
selectedUsers.remove(user);
}
}
Notice how the functions grab the value to add to the arrays from the input element's name attribute. Your current name attributes are invalid as they should really be unique.
It is even possible to refactor my suggestion above to have one generic input field listener and determine the array to add to based on a data attribute or something. But this is a good starting point.
After all this you can do whatever you need with the selectedFruits or selectedUsers arrays.
Try placing the second for loop inside the first one, like so
for (var n = 0; n < name.length; n++) {
for (var f = 0; f < fruit.length; f++) {
if(chboxsEng_single[n].checked && chboxsEng_fruit[f].checked){
dosomething..................
}
}
}
Be aware that this will go through every single value of f a total of n times, which may or may not be behaviour that you desire, it's not clear in the question.

JavaScript form same values

How can I make a form so they cannot repeat the same values in the Input?
I tried a way like:
var text1 = document.getElementById('num1').value;
var text2 = document.getElementById('num1').value;
var textform = [text1,text2];
if (
text1 == text2 ||
text2 == text1
) {
alert("repeated numbers");
return false;
}
But this is gets me into two troubles:
- If I put no value, it will say: Repated Numbers
- If I want to make this for 100 form values, it takes a lot of code
You could give all of your text elements the same class, and grab their values by class name to simplify building the array of text values.
<input type="text" class="checkDupe" id="input1" />
<input type="text" class="checkDupe" id="input2" />
Then grab their values in javascript
var checkDupes = document.getElementsByClassName('checkDupe');
var textArray = [];
for(var i = 0; i < checkDupes.length; i++){
textArray.push(checkDupes[i].value);
}
Now that we have an array of values that they entered, check to see if any of them repeat by sorting the array, and seeing if any two elements side-by-side are the same.
textArray.sort();
var dupes = false;
for(var i = 0; i < textArray.length; i++){
if(textArray[i] === textArray[i + 1]) dupes = true;
}
If we find any duplicates, let the user know.
if(dupes) alert('Repeated numbers!');
You could do something like this:
var text1 = document.getElementById('num1').value;
var text2 = document.getElementById('num2').value;
var textform = [text1, text2];
var seen = {};
textform.forEach(function(value) {
if (seen[value]) {
alert('Bad!');
}
seen[value] = true;
});
In the code above, we loop over each value in the array. The first time we encounter it, we push it into a map. Next time (if) we hit that value, it will exist in the map and it will tell us we've seen it before.
If you give all the input's a common class then you quickly loop through them.
The HTML:
<input type="text" name="num1" class="this that number"></input>
<input type="text" name="num2" class="this number"></input>
<input type="text" name="num3" class="that number"></input>
<input type="text" name="num4" class="number"></input>
<input type="text" name="num5" class=""></input> <!-- we don't want to check this one -->
<input type="text" name="num6" class="number that this"></input>
<input type="text" name="num7" class="this that number"></input>
The JavaScript:
// get all the inputs that have the class numbers
var ins = document.querySelectorAll("input.numbers");
// a tracker to track
var tracker = {};
// loop through all the inputs
for(var i = 0, numIns = ins.length; i < numIns; ++i)
{
// get the value of the input
var inValue = ins[i].value.trim();
// skip if there is no value
if(!inValue) continue;
// if the value is already tracked then let the user know they are a bad person
// and stop
if(tracker[inValue])
{
alert("You are a bad person!");
return;
}
// track the value
tracker[inValue] = true;
}
You could also enhance this to let the user know which inputs have duplicate values:
// get all the inputs that have the class numbers
var ins = document.querySelectorAll("input.numbers");
// a tracker to track
var tracker = {};
// loop through all the inputs
for(var i = 0, numIns = ins.length; i < numIns; ++i)
{
// get the value of the input
var inValue = ins[i].value.trim();
// skip if there is no value
if(!inValue) continue;
// if the value is already tracked then error them
if(tracker[inValue])
{
// mark the current input as error
ins[i].className += " error";
// mark the first found instance as an error
ins[tracker[inValue]].className += " error";
}
// save the index so we can get to it later if a duplicate is found
tracker[inValue] = i;
}
Here's a way of doing it that automatically picks up all the text inputs in your document and validates based on what you're looking for. Would be simple enough to expose the valid value and make this the validation handler (or part of one) that handles a form submission.
<meta charset="UTF-8">
<input id="num1" type="text" value="foobar1">
<input id="num2" type="text" value="foobar2">
<input id="num3" type="text" value="foobar3">
<input id="num4" type="text" value="foobar4">
<input id="num5" type="text" value="foobar5">
<button onClick="checkValues();">Validate</button>
<script>
function checkValues() {
var inputs = document.getElementsByTagName('input');
arrInputs = Array.prototype.slice.call(inputs);
var valid = true;
var valueStore = {};
arrInputs.forEach(function(input) {
if (input.type == 'text') {
var value = input.value.toUpperCase();
if (valueStore[value]) {
valid = false;
} else {
valueStore[value] = true;
}
}
});
if (valid) {
alert('Valid: No matching values');
} else {
alert('Invalid: Matching values found!');
}
}
</script>
With jquery you can iterate directly over the inputs.
<form>
<input type="text" >
<input type="text" >
<input type="text" >
<input type="text" >
<input type="text" >
<input type="text" >
<button>
TEST
</button>
</form>
function checkValues(){
var used = {};
var ok = true;
$('form input[type="text"]').each(function(){
var value = $(this).val();
if(value !== ""){
if(used[value] === true){
ok = false;
return false;
}
used[value] = true;
}
});
return ok;
}
$('button').click(function(event){
event.preventDefault();
if(!checkValues()){
alert("repeated numbers");
};
});
https://jsfiddle.net/8mafLu1c/1/
Presumably the inputs are in a form. You can access all form controls via the form's elements collection. The following will check the value of all controls, not just inputs, but can easily be restricted to certain types.
If you want to include radio buttons and checkboxes, check that they're checked before testing their value.
function noDupeValues(form) {
var values = Object.create(null);
return [].every.call(form.elements, function(control){
if (control.value in values && control.value != '') return false;
else return values[control.value] = true;
});
}
<form id="f0" onsubmit="return noDupeValues(this);">
<input name="inp0">
<input name="inp0">
<input name="inp0">
<button>Submit</button>
</form>
For old browsers like IE 8 you'll need a polyfill for every.
You can simply get all inputs iterate them twice to check if they are equals
var inputs = document.getElementsByTagName('input');
for (i = 0; i < inputs.length; i++) {
for (j = i + 1; j < inputs.length; j++) {
if (inputs[i].value === inputs[j].value) {
console.log('value of input: ' + i + ' equals input: ' + j);
}
}
}
<input value="56" />
<input value="12" />
<input value="54" />
<input value="55" />
<input value="12" />

Using document.getElementsByClass with Checkboxes

I have cut this code and I'm not that familiar using Class.
<form>
<input type="checkbox" name="Symptom1" class=sound value="case1"> Poor Sound Quality<br>
<input type="checkbox" name="Symptom2" class=sound value="case2"> Only One Speaker is Working<br>
<input type="checkbox" name="Symptom3" class=sound value="case3"> No Sound<br>
<input type="checkbox" name="Symptom4" class=sound value="case4"> Low Volume<br>
<input type="checkbox" name="Symptom5" class=sound value="case5"> Crackling Sound<br>
<input type="checkbox" name="Symptom6" class=battery value="case6"> Drain Easily<br>
<input type="checkbox" name="Symptom7" class=battery value="case7"> Flickering Screen<br>
<input type="checkbox" name="Symptom8" class=battery value="case8"> Battery Physically Wobbled<br>
<input type="checkbox" name="Symptom9" class=battery value="case9"> Turn Off from Now and Then<br>
<input type="checkbox" name="Symptom10" class=battery value="case10"> Does not Charge<br>
</form>
<button onclick="Submit()">Submit</button>
Here is my submit function that I am working on.
function Submit() {
if (document.getElementsByClassName('sound').checked) {
alert("You Picked Sound");}
} else {
alert("none");
}
}
What I wanted to do is if the user checked at least one of the checkboxes under the same class (i.e. sound) then pressed submit. It would alert the user that he/she picked that class. But apparently it would not and rather it always alert me with none.
Help?
You have to loop through the collection document.getElementsByClassName returns and check the checked attribute. Here's one way to do it (untested):
function Submit() {
var pickedOne = false;
var inputs = document.getElementsByClassName('sound');
for(var i = 0, l = inputs.length; i < l; ++i) {
if(inputs[i].checked) {
pickedOne = true;
alert('You picked ' + inputs[i].className);
break;
}
}
if(!pickedOne) {
alert('none');
}
}
If you can use jQuery, you can probably do something like this instead:
function Submit() {
var selectedClass = $('input[type=checkbox]:checked').attr('class');
if(selectedClass) {
alert('You picked ' + selectedClass);
}
else {
alert('none');
}
}
"document.getElementsByClassName" return a list of nodes.
For example document.getElementsByClassName('sound') will return an array 5 checkboxes. So you can use it like this:
var sounds = document.getElementsByClassName('sound');
// Now you can access one of them through it's index
function Submit() {
if (document.getElementsByClassName('sound')[0].checked) {
alert("You Picked Sound");}
} else {
alert("none");
}
}
document.getElementsByClassName() returns an array instead of an object. You need to loop through the array.
function Submit() {
var allCheckBox = document.getElementsByClassName('sound');
var allPick = false;
for(var i = 0; i < allCheckBox.length ; i++) {
if (allCheckBox[i].checked) {
allPick = true;
break;
}
}
if(allPick) {
alert("You Picked Sound");
} else {
alert("none");
}
}

JavaScript - get value from multiple inputs in an array

I am trying to get the value from muliple inputs with the same id in an array.
I already used the forum, but haven't find a solution for me.
Exmaple
<input type="hidden" value="'+image_url+'" name="webcampics[]" id="webcampics">
<input type="hidden" value="'+image_url+'" name="webcampics[]" id="webcampics">
<input type="hidden" value="'+image_url+'" name="webcampics[]" id="webcampics">
<input type="hidden" value="'+image_url+'" name="webcampics[]" id="webcampics">
var elem = document.getElementById("webcampics");
var names = [];
for (var i = 0; i < elem.length; ++ i) {
names += elem[i]+'|';
}
var webcamval = names;
You shouldn't have elements with identical id's within the document. ID's have to be unique throughout your entire markup, by specification. If you do it anyways, methods like document.getElementById will only match the very first occurence for instance.
Use a class instead of ids.
<input type="hidden" value="'+image_url+'" name="webcampics[]" class="webcampics">
<input type="hidden" value="'+image_url+'" name="webcampics[]" class="webcampics">
<input type="hidden" value="'+image_url+'" name="webcampics[]" class="webcampics">
<input type="hidden" value="'+image_url+'" name="webcampics[]" class="webcampics">
var inputs = document.getElementsByClassName( 'webcampics' ),
names = [].map.call(inputs, function( input ) {
return input.value;
}).join( '|' );
Demo: http://jsfiddle.net/QgJrq/
What you are asking for is wrong very wrong, it is recommended IDs should be unqiue, but for learners sake here's what you would do
var elem = document.getElementsByTagName("input");
var names = [];
for (var i = 0; i < elem.length; ++i) {
if (typeof elem[i].attributes.id !== "undefined") {
if (elem[i].attributes.id.value == "webcampics") {
names.push(elem[i].value);
}
}
}
var webcamval = names;
http://jsfiddle.net/5vamG/
Due to someone down voting after giving a full explanation why the above mentioned method is wrong, however does exactly what youve asked for, here's the correct method.
change all the inputs id to class
var elem = document.getElementsByClassName("webcampics");
var names = [];
for (var i = 0; i < elem.length; ++i) {
if (typeof elem[i].value !== "undefined") {
names.push(elem[i].value);
}
}
}
var webcamval = names;
http://jsfiddle.net/5vamG/1/
You shouldn't have more than one element with the same id.
getElementById returns exactly one element; use getElementsByName which will return the list you seek.

Using JavaScript to manipulate HTML input (checkbox) elements via type instead of name

I am implementing an HTML form with some checkbox input elements, and I want to have a Select All or DeSelect All button. However, I do not want to rely on the name of the input element (like this example) but rather the type because I have multiple checkbox groups with different names. Is there a way to check and uncheck all checkbox input elements within a form with JavaScript by relying on the type instead of the name?
Edit: We rely on YUI libraries, so I have access YUI if that provides a solution.
This should do it:
<script>
function checkUncheck(form, setTo) {
var c = document.getElementById(form).getElementsByTagName('input');
for (var i = 0; i < c.length; i++) {
if (c[i].type == 'checkbox') {
c[i].checked = setTo;
}
}
}
</script>
<form id='myForm'>
<input type='checkbox' name='test' value='1'><br>
<input type='checkbox' name='test' value='1'><br>
<input type='checkbox' name='test' value='1'><br>
<input type='checkbox' name='test' value='1'><br>
<input type='checkbox' name='test' value='1'><br>
<input type='button' onclick="checkUncheck('myForm', true);" value='Check'>
<input type='button' onclick="checkUncheck('myForm', false);" value='Uncheck'>
</form>
function findCheckBoxes(el, check) {
for(var i=0;el.childNodes[i];i++)
{
var child = el.childNodes[i];
if (child.type=="checkbox")
{
child.checked = check;
}
if (child.childNodes.length > 0)
this.findCheckBoxes(child, check);
}
}
iterate through the form.elements collection and check .type == "checkbox".
var button = getSelectAllButtonInFormSomeHow();
/*all formelements have a reference to the form. And the form has an elements-collection.*/
var elements = button.form.elements;
for(var i = 0; i < elements.length;i++) {
var input = elements[i];
if (input.tagName == "input" && input.type == "checkbox") input.checked = true;
}
Every input element has an attribute, type, which for checkboxes is "checkbox" so you could try something like this:
for (var i = 0; i < document.myForm.elements.length; i++) {
if (document.myForm.elements[i].type == "checkbox") {
document.myForm.elements[i].checked = true;
}
}
If jQuery is an option you can do this rather easily.
See the documentation on jQuery selectors. (The last example in the section shows how to do it with radio buttons but just replace that with check boxes.)
Is assigning a class to all required checkbox elements an option? If yes, then this is how I would do it (assuming "class_name" is the name of the css class present in all checkbox elements in question):
function selectCheckBoxes(bChecked) {
var aCheckBoxes = YAHOO.util.Dom.getElementsByClassName('class_name', 'input');
for (var i = 0; i < aCheckBoxes.length; i++) {
aCheckBoxes[i].checked = bChecked;
}
}
If you want to stay away from classes, but can get parent element by ID (or any other method, I will use ID in the example, though), than you can do this:
function selectCheckBoxes(bChecked) {
var oParent = document.getElementById('parentsID');
var aElements = oParent.getElementsByTagName('input');
for (var i = 0; i < aElements.length; i++) {
if (aElements[i].type == 'checkbox') {
aElements[i].checked = bChecked;
}
}
}
I would stick to the "class" method, however.
<html>
<head>
<script>
function selectCheckBox()
{
if(document.getElementById('id11').checked==true)
{
document.frm.id2.checked=true
document.frm.id3.checked=true
document.frm.id4.checked=true
}
if(document.getElementById('id11').checked==false)
{
document.frm.id2.checked=false
document.frm.id3.checked=false
document.frm.id4.checked=false
}
}
function selectCheckBox1()
{
if(document.getElementById('id12').checked==false)
{
document.frm.id1.checked=false
}
}
function selectCheckBox2()
{
if(document.getElementById('id13').checked==false)
{
document.frm.id1.checked=false
}
}
function selectCheckBox3()
{
if(document.getElementById('id14').checked==false)
{
document.frm.id1.checked=false
}
}
</script>
</head>
<body>
<form name="frm">
All :<input type="checkbox" id="id11" name="id1" value="1" onClick="selectCheckBox()"><br>
A. :<input type="checkbox" id="id12" name="id2" value="2" onClick="selectCheckBox1()"><br>
B. :<input type="checkbox" id="id13" name="id3" value="3" onClick="selectCheckBox2()"><br>
C. :<input type="checkbox" id="id14" name="id4" value="4" onClick="selectCheckBox3()"><br>
</form>
</body>
</html>

Categories

Resources