how to set another field value in same row - javascript

Given a grid with 5 columns and an array of the IDs in column 2 how do you set the boolean value of column 1 to true for the IDs in the array? There are 25 rows and 5 of the rows are in the array.
var ProductIDArray = [2,5,9,12,16];
var i;
for (i = 0; i < ProductIDArray.length; i++) {
document.getElementById("chk").checked = true;
}

First mistake: you can't/shouldn't have duplicate IDs on the page. Either use classes, or make those IDs unique for each element.
Second mistake: you need to check different element each time in the loop.
Based on this:
Column 1 is a checkbox column. Only the ones in the array should have the checkbox checked. The other rows shouldn't have column 1 checked.
Let's try to fix it. Assuming that your checkbox IDs are chk_N where N is the number that matches the product ID (chk_1, chk_2, etc...), the code should look like this:
var ProductIDArray = [2,5,9,12,16];
var i;
for (i = 0; i < ProductIDArray.length; i++) {
document.getElementById("chk_" + ProductIDArray[i]).checked = true;
}
Here's an example:
var ProductIDArray = [2, 5, 9, 12, 16];
var i;
for (i = 0; i < ProductIDArray.length; i++) {
document.getElementById("chk_" + ProductIDArray[i]).checked = true;
}
<input type="checkbox" id="chk_11" />11<br>
<input type="checkbox" id="chk_2" />2<br>
<input type="checkbox" id="chk_33" />33<br>
<input type="checkbox" id="chk_45" />45<br>
<input type="checkbox" id="chk_65" />65<br>
<input type="checkbox" id="chk_5" />5<br>
<input type="checkbox" id="chk_16" />16<br>
<input type="checkbox" id="chk_9" />9<br>
<input type="checkbox" id="chk_12" />12<br>
...

Related

html checkboxes associative array - how to access this array in javascript?

I'm trying to do this:
<input type="checkbox" name="appliances[microwave]">
<input type="checkbox" name="appliances[coffee-machine]">
<input type="checkbox" name="appliances[grill]">
and get access to this array in javascript like this
1.
var myarr = document.getElementsByName('appliances');
alert('here ' + myarr);
result: alert shows "here [object NodeList]"
2.
var myarr = document.getElementsByName('appliances');
alert('here ' + myarr['grill']);
result: alert shows "here undefined"
How may I get access to this array?
Your elements all have different names as far as HTML is concerned, "appliances[microwave]", "appliances[coffee-machine]", etc. Those names are only special to certain software (for instance, PHP will handle them on a form submission).
You can find all elements whose name starts with appliances by using querySelectorAll with the selector input[name^=appliances]. Then you access the entries in that NodeList by index (0, 1, and 2):
const checkboxes = document.querySelectorAll("input[name^=appliances]");
for (let n = 0; n < checkboxes.length; ++n) {
console.log(`${checkboxes[n].name} checked? ${checkboxes[n].checked}`);
}
<input type="checkbox" checked name="appliances[microwave]">
<input type="checkbox" name="appliances[coffee-machine]">
<input type="checkbox" name="appliances[grill]">
<!-- A fourth one just to show that it won't get selected: -->
<input type="checkbox" name="something-else">
If you want to access them by the names in [], you could create an object and put them on the object as properties:
function getNamedElementObject(baseName) {
const result = {};
// NOTE: The next line assumes there are no `]` characters in `name`
const list = document.querySelectorAll(`[name^=${baseName}]`);
for (const element of list) {
const match = element.name.match(/\[([^]+)\]/);
if (match) {
const propName = match[1]
result[propName] = element;
}
}
return result;
}
const checkboxes = getNamedElementObject("appliances");
console.log(`checkboxes["microwave"].checked? ${checkboxes["microwave"].checked}`);
console.log(`checkboxes["coffee-machine"].checked? ${checkboxes["coffee-machine"].checked}`);
console.log(`checkboxes["grill"].checked? ${checkboxes["grill"].checked}`);
// You could also loop through by getting an array from `Object.values`:
for (const checkbox of Object.values(checkboxes)) {
console.log(`${checkbox.name} checked? ${checkbox.checked}`);
}
<input type="checkbox" checked name="appliances[microwave]">
<input type="checkbox" name="appliances[coffee-machine]">
<input type="checkbox" name="appliances[grill]">
<!-- A fourth one just to show that it won't get selected: -->
<input type="checkbox" name="something-else">
Or you could use a Map:
function getNamedElementMap(baseName) {
const result = new Map();
// NOTE: The next line assumes there are no `]` characters in `name`
const list = document.querySelectorAll(`[name^=${baseName}]`);
for (const element of list) {
const match = element.name.match(/\[([^]+)\]/);
if (match) {
const propName = match[1]
result.set(propName, element);
}
}
return result;
}
const checkboxes = getNamedElementMap("appliances");
console.log(`checkboxes.get("microwave").checked? ${checkboxes.get("microwave").checked}`);
console.log(`checkboxes.get("coffee-machine").checked? ${checkboxes.get("coffee-machine").checked}`);
console.log(`checkboxes.get("grill").checked? ${checkboxes.get("grill").checked}`);
// You could also loop through via the iterator from the `values` method:
for (const checkbox of checkboxes.values()) {
console.log(`${checkbox.name} checked? ${checkbox.checked}`);
}
<input type="checkbox" checked name="appliances[microwave]">
<input type="checkbox" name="appliances[coffee-machine]">
<input type="checkbox" name="appliances[grill]">
<!-- A fourth one just to show that it won't get selected: -->
<input type="checkbox" name="something-else">

How to push values to input type hidden when clicked on radio button using jQuery?

I am getting values from one variable in array format so by using for loop it will iterate and when click on input type radio button each value with comma separated push to hidden field
I tried this but nothing gets inserted. How can I push those values to the hidden field?
var id = ["1", "2"]; // getting this value from another varaible in array format
for (var i = 0; i < id.length; i++) {
$("input[name=radion_btn" + id[i] + "]").change(function() {
$(".selected_val").push(id[i]); //values like 1,2 want to push in hidden field when click on radio button
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" name="selected_val[]" value="" class="selected_val" />
<input type="radio" name="radion_btn1" value="" />
<input type="radio" name="radion_btn2" value="" />
As per your code. for(var i = 0; i < id.length; i++) { run two times and whenever your event occur. At that time i value come 2 and id[2] comes undefined. Below code should work.
var id = ["1", "2"]; // getting this value from another varaible in array format
arrayData = [];
for (var i = 0; i < id.length; i++) {
$("input[name=radion_btn" + id[i] + "]").change(function() {
console.log($(this).val());
arrayData.push($(this).val()); //values like 1,2 want to push in hidden field when click on radio button
$('.selected_val').val(arrayData.join());
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="value" name="selected_val[]" value="" class="selected_val" />
<input type="radio" name="radion_btn1" value="1" />
<input type="radio" name="radion_btn2" value="2" />
You can simulate a push by adding the hidden input's value before the new value
var id = ["1", "2"]; // getting this value from another varaible in array format
for (var i = 0; i < id.length; i++) {
$(".selected_val").val("");
$("input[name=radion_btn" + id[i] + "]").change(function() {
$(".selected_val").val((i == 0 ? "" : ",") + $(".selected_val").val() + id[i]);
});
}
Here's an example of one approach that might help. See comments in snippet below.
let obj = {}; // create an empty object to store the clicked values
$(".radio").change(function() { // when a radio button is clicked
obj[this.id] = $(this).val(); // store it in the object
$(".selected_val").val(JSON.stringify(obj)); // and add the object to hidden field as string
console.log($(".selected_val").val()); // spit it out to the console
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" name="selected_val[]" value="" class="selected_val" />
<input type="radio" class="radio" name="radion_btn1" id="1" value="1" />1
<input type="radio" class="radio" name="radion_btn2" id="2" value="2" />2
<input type="radio" class="radio" name="radion_btn3" id="3" value="3" />3
You'll notice I added a common class for all radio buttons. This is what I'm attaching the event handler to. I also added the IDs to the radio button elements as well.
This may or may not work best for your scenario, but hopefully gets you started in the right direction.
Update
If you'd rather store the values in an array, just change it to an array:
let arr = [];
$(".radio").change(function() {
arr.push($(this).val());
$(".selected_val").val(JSON.stringify(arr));
}
Of course, that won't associate the ID with the value like with an object.

How to count number of checkboxes on open object in view?

I am trying to count the number of checkbox elements on the current panel I am on. What is happening is that I have checkboxes on 4 panels, on each panel there are checkboxes.
Only one panel can be open at a time. When I do a count of checkboxes, I am getting the total of all the checkboxes in my app and not the number on the panel I am showing.
I have tried specifically telling the code that this is the window open
var a = angular.element(document.querySelector('[widget-id="popup-1"]
div')).scope().$parent.me.visible
but to no avail,
I am not sure how to tell the code that this is the panel that is open, count checkboxes on it only.
I am trying to count the number of boxes, then compare checked boxes and if num = checked, then I will continue on.
$scope.checkNum = function() {
// var a = angular.element(document.querySelector('[widget-id="popup-1"]
div')).scope().$parent.me.visible
var inputs = document.getElementsByTagName("input");
//or document.forms[0].elements;
var cbs = [];
//will contain all checkboxes
var checked = [];
//will contain all checked checkboxes
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == "checkbox") {
cbs.push(inputs[i]);
if (inputs[i].checked) {
checked.push(inputs[i]);
}
}
}
var nbCbs = cbs.length;
//number of checkboxes
var nbChecked = checked.length;
//number of checked checkboxes
alert("# checkboxes = " + nbCbs + "\n" + "# checked checkboxes = " +
nbChecked);
console.log(" # checked checkboxes = " + nbChecked);
}
let's say your current panel looks like the following
var test = document.getElementById("dv_Test");
get_CheckboxCount(test);
function get_CheckboxCount(element) {
var check = element.querySelectorAll("input[type=checkbox]");
console.log(check.length);
}
<div id="dv_Test">
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
</div>
<div id="dv_Test2">
<input type="checkbox" />
</div>

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.

How do I validate a group of textboxes using javascript?

I have group of check-boxes and corresponding text-boxes with them. I can get each checkbox one by one, but how do I get the group of textboxes so I can validate them?
Here is my javascript code below:
function validate_orderform(proform)
{
var flag=0;
for (var i = 0; i < proform.chk.length; i++) {
if (proform.chk[i].checked && proform.quant[i].value=="") {
flag=1;
}
}
if(flag==1){
return false;
}
return true;
}
and my html code:
<td><input type="checkbox" id="chk1" name="chk"></td>
<td><input type="text" size="10" id="quant1" name="quant1"></td>...and so on
If name of textboxes are different then you can access all textboxes by
var txtObjList = document.getElementsByTagName("input");
for(var i=0; i < txtObjList.length; i++){
if(txtObjList[i].getAttribute("type") == "text" && this.value != ""){
// success for i+1 textbox
}
}
Or you can give common class name to all textboxes and then can access by
var txtObjList = document.getElementsByClassName("classname");
for(var i=0; i < txtObjList.length; i++){
if(this.value != ""){
// success for i+1 textbox
}
}
Remember by using javascript library such as jquery, prototype your work will be simpler.
There are a couple of methods you could use, you could use document.getElementsByTagName to retrieve all of the input elements, check their type etc... It works but it's slow and potentially expensive depending on how complex your form is.
If you have a group of checkboxes and each one has it's own text box then you could group them, so add a common name to each type, e.g.
Entry 1:
<input type="checkbox" id="chk1" name="chk"/>
<input type="text" id="quant1" name="quant"/>
Entry 2:
<input type="checkbox" id="chk2" name="chk"/>
<input type="text" id="quant2" name="quant"/>
Then you can use the document.getElementsByName method, so in this instance the following would retrieve a collection of 2 objects for you're text boxes:
var myTextBoxes = document.getElementsByName("quant");

Categories

Resources