Add attribute to specific elements in JavaScript - javascript

I wish to add a new attribute to all of my elements that their type is text
Can you please let me know where I'm wrong?
Firstly, I identify all my elements that their type is text as follows (input tag name is the tag name that contains text types)
var inputs = document.getElementsByTagName('input');
Secondly, I add my attribute to those with text type
if (inputs.type =='text') {var att = document.createAttribute("class")}
Then when I want to check if the new attribute is added or not
inputs.hasAttribute("class");
I got this error
Uncaught TypeError: inputs.hasAttribute is not a function

document.getElementsByTagName('input');
returns an array like list instead of just one element. Therefore, this is what you should do:
var inputs = document.getElementsByTagName('input');
for(var i = 0; i < inputs.length; i++){
if(inputs[i].type == 'text'){
inputs[i].classList.add("some", "class");
}
}
An even better way would be this:
// Only works in recent browsers
document.querySelectorAll("input[type=text]").forEach(function(ele){
ele.classList.add("some", "class");
});

Try this:
var inputs = document.getElementsByTagName("input");
for(var i = 0; i < inputs.length; i++){
if(inputs[i].type == 'text'){
var att = document.createAttribute("class");
att.value = "testClass";
inputs[i].setAttributeNode(att);
console.log(inputs[i].hasAttribute("class"));
}
}
<input type="text"/>
<input type="text"/>

Related

How do I get the id of a element in a form?

I need to get the id of an element within a form so I can tag the element as "false" or "true". Or, alternately, I need a way to associate a name with an element that can I pull in javascipt so I can change the associated value.
var form = document.getElementById("myForm");
form.elements[i].value
Those lines of code is what I tried but it doesn't seem to work.
Edit:
function initial(){
if (localStorage.getItem("run") === null) {
var form = document.getElementById("myForm").elements;
for(var i = 0; i < 1 ; i++){
var id = form.elements[i].id;
sessionStorage.setItem(id,"false");
}
localStorage.setItem("run", true);
}
}
So basically when I run the page, I want a localStorage item attached to all the buttons on the screen. I want this to run once so I can set all the items to false. Problem is I don't know how to get the ids so I have a value to attach to the button. Any idea of how to accomplish a task like this.
Edit2:
function initial(){
if (localStorage.getItem("run") === null) {
var form = document.getElementById("myForm");
var tot = document.getElementById("myForm").length;
for(var i = 0; i < tot ; i++){
sessionStorage.setItem(form.elements[i].id,"false");
}
localStorage.setItem("run", true);
}
}
This is the new code. It mostly seems to work but for some reason only the first value is getting set to false. Or maybe it has to do with this function, I'm not sure.
function loader(){
var form = document.getElementById("myForm");
var tot = 5;
for(var i = 0; i < 5 ; i++){
if(sessionStorage.getItem(form.elements[i].id) === "true"){
document.getElementById(form.elements[i].id).style.backgroundColor = "green";
return ;
}else{
document.getElementById(form.elements[i].id).style.backgroundColor = "red";
return false;
}
}
}
Anyways, I'm running both of these at the same time when the page is executed so they are all set to false and turn red. But when a button is properly completed, the color of the button turns green.
It's available via the id property on the element:
var id = form.elements[i].id;
More on MDN and in the spec.
Live Example:
var form = document.getElementById("myForm");
console.log("The id is: " + form.elements[0].id);
<form id="myForm">
<input type="text" id="theText">
</form>
You're already storing all the elements in the form so it must be :
var form = document.getElementById("myForm").elements;
var id = form[i].id;
Or remove the elements part from the form variable like :
var form = document.getElementById("myForm");
var id = form.elements[i].id;

Set an array of the checkbox values with another array of values

I have a set of input checkboxes on a form that look like this:
<input type="checkbox" value=""><span value="Atlanta">Atlanta</span>
<input type="checkbox" value=""><span value="Charleston">Charleston</span>
<input type="checkbox" value=""><span value="Chicago">Chicago</span> and etc.
The above is due to running this, $dataTable.ajax.reload(), and for some reason this erases the values of the checkboxes in my form. These checkboxes are not hardcoded and are being dynamically generating.
Instead of doing the below, I realize I can just refresh the page and get all the value back, but I'd like to see if there is another way to do what I'm trying to do below.
Anywho, I took the span text of each checkbox, turned that into an array and called it spanarr. I also turned the input checkboxes into an array, called emergcheck.
var emergspanarr = $('#emergencyForm span').toArray();
var spanarr = [];
var emergcheck = $('#emergencyForm input[type="checkbox"]');
emergspanarr.map(function(item){
spanarr.push(item.innerHTML.trim());
});
I'm trying to insert one span value (from spanarr) into each of input checkbox (from emergcheck).
What I have so far:
for (var j = 0; j < emergcheck.length; j++){
for (var k = 0; k < spanarr.length; k++){
emergcheck.attr("value", function(i, val){
return val + spanarr[k];
})
}
}
But it's producing this:
<input value="AtlantaCharlestonChicagoHouston (Sales)Houston (Terminal)Long BeachMarseillesMiamiMontreal....Santa Ana SavannahSeattleSecaucusTorontoVancouverAtlantaCharlestonChicagoHouston (Sales)Houston (Terminal)Long BeachMarseillesMiamiMontrealSanta Ana .....Santa AnaSavannahSeattleSecaucusTorontoVancouver" type="checkbox"><span value="Atlanta">Atlanta</span>
<input value="AtlantaCharlestonChicagoHouston (Sales)Houston (Terminal)Long BeachMarseillesMiamiMontreal....Santa Ana SavannahSeattleSecaucusTorontoVancouverAtlantaCharlestonChicagoHouston (Sales)Houston (Terminal)Long BeachMarseillesMiamiMontrealSanta Ana .....Santa AnaSavannahSeattleSecaucusTorontoVancouver" type="checkbox"><span value="Charleston">Charleston</span> and etc.
I want it to be this instead:
<input type="checkbox" value="Atlanta"><span value="Atlanta">Atlanta</span>
<input type="checkbox" value="Charleston"><span value="Charleston">Charleston</span>
<input type="checkbox" value="Chicago"><span value="Chicago">Chicago</span
I feel like I am close. What am I missing? In need of another pair of eyes. Thanks,
Just try to change code with below code -
JS Code -
for (var j = 0; j < emergcheck.length; j++){
emergcheck.eq(j).val(spanarr[j]);
}
Maybe it can help you.
I think you just want the value of the input. You can use .val() from jQuery or just .value as pure js.
jQuery way:
var emergspanarr = $('#emergencyForm span').toArray();
var emergcheck = $('#emergencyForm input[type="checkbox"]').toArray();
for (var j = 0; j < emergcheck.length; j++) {
emergcheck[j].val(emergspanarr[j].val());
}
Pure js way:
var emergspanarr = $('#emergencyForm span').toArray();
var emergcheck = $('#emergencyForm input[type="checkbox"]').toArray();
for (var j = 0; j < emergcheck.length; j++){
emergcheck[j].value = emergspanarr[j].value;
}

How to get element by name with $key

PHP
//Here is my html for qty
<p>Qty : <input type="number" value="" name="qty<?php echo $key ?> onChange="findTotal()"/>
JS function
function findTotal() {
var arr = document.getElementsByName('qty');
...
document.getElementById('result').value = decimalPlaces(tot, 2);
}
My qty name needs key for post array. How do I get name inside js function to calculate quantities?
You can use
document.querySelector("input['name^='qty']").value
if you don't have jQuery.
This will select an input with name attribute starting with "qty". If you have multiple inputs which match the criteria you can select them all using
document.querySelectorAll("input[name^='qty']")
which will return a NodeList. You can read more about this here.
You can do something like this
var myVar = document.getElementsByTagName("somename");
//do something else
If you are using jquery
value = $( "input[name^='qtd']" ).val();
//it will pick the input wich name starts with 'qtd'
In pure DOM, you could use getElementsByTagName to grab all input elements, and loop through the resulting array. Elements with name starting with 'qty' get pushed to another array:
var eles = [];
var inputs = document.getElementsByTagName("input");
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].name.indexOf('qty') == 0) {
eles.push(inputs[i]);
}
}
Don't query the element by the name attribute's value. I'm not sure what's the purpose of the key and why you need it in the findTotal method, but here's an example:
<p>Qty : <input type="number" value="" name="qtyMyKey" onChange="findTotal(event)" /></p>
<script>
function findTotal(e) {
var inputEl = e.target,
inputName = inputEl.getAttribute('name'),
myKey;
if (typeof inputName === 'string') {
myKey = inputName.replace('qty', '');
}
console.log(myKey);
//var arr = document.getElementsByName('qty');
//document.getElementById('result').value = decimalPlaces(inputEl.value(), 2);
}
</script>
Here's the jsFiddle demo.

How to get value from JS-Generated HTML inputs in PHP using POST or GET

I am making a grid of inputs using javascript. Each of these inputs has a unique name and id: "test1","test2"... I'm also able to change the style of these inputs based on their name.
var c = document.getElementById("gridOne");
function createTable() {
var table = document.createElement('table');
var rows = +document.getElementById('numRows').value;
var cols = +document.getElementById('numCols').value;
var n = 0;
for(var r=0; r<rows; r++) {
var tr = document.createElement('tr');
table.appendChild(tr);
for(var c=0; c<cols; c++) {
if(r == 0 || c == 0 || r == rows - 1 ||c == cols - 1 ){
var td = document.createElement('td');
tr.appendChild(td);
var inp = document.createElement('input');
inp.setAttribute('id', 'test'+n);
inp.setAttribute('name', 'test'+n);
inp.setAttribute('value', n);
inp.setAttribute('type','number');
td.appendChild(inp);
n++;
} else {
var tq = document.createElement('td');
tr.appendChild(tq);
tq.classList.add('inner');
var inp = document.createElement('input');
inp.setAttribute('type','text');
inp.disabled = true;
tq.appendChild(inp);
}
}
}
var container = document.getElementById('input_container');
container.innerHTML = '';
container.appendChild(table);
}
The HTML code that is handling and outputting the JavaScript is this
<form method="POST">
<div class="canvas" id="input_container">
<script type="text/javascript" src="js/Grid1.js"></script>
</div>
<input name="Confirm" type="submit">
When i try to access the values submitted by these inputs i'm getting an error. I'm using PHP, ive tried both GET and POST but im getting no luck.
if (isset($_POST['Confirm']))
{
$test0 = $_POST['test0'];
$test1 = $_POST['test1'];
$test2 = $_POST['test2'];
}
My code works for everything except the dynamically generated input forms.
The error you are getting is actually not an error, but a notice.
Undefined index: test0 in x on line y
To avoid that you should firstly check whether these values exists, i.e.:
$test0 = isset($_POST['test0']) ? $_POST['test0'] : 'default value';
Or using PHP7 null coalescing operator:
$test0 = $_POST['test0'] ?? 'default value';
Better approach for your problem
I think that better way to handle dynamically generated fields would be to use arrays. So you should:
use [name] attribute with braces [] at the end
on the backend, iterate over that array.
So, example code might look like:
<input type="number" name="test[]">
<input type="number" name="test[]">
<input type="number" name="test[]">
and PHP:
foreach ($_POST['test'] as $test) {
var_dump($test);
}

Having trouble with onchange and storing numbers in an array via textbox

I am having trouble with my onchange not working and storing numbers in an array via a text box.
What I want the code to do is to get statistics on the numbers inputted into the text box. I do this by having the user input numbers into the text box and hit the Enter key to display those numbers. The numbers should be put into an array before being put into a list to display the inputted numbers. However, I keep getting this error where the onchange is not triggering when hitting the Enter key or clicking off of the text box.
Here is an image of the error I am getting when inspecting the code
With the numbers stored in the array, I want to try to get the Mean of the numbers. But, I keep getting the error "NaN" which makes me think that my numbers are not getting stored into the array properly.
Here is the code:
<html>
<head>
<title>Stats</title>
</head>
<p>Array is called numbers. numbers.sort();</p>
<div id="stats">
<input type ="text" id="value" onchange="list()"> <!-- Getting the Onchange Error here -->
<button id="button1" onclick = "list()">Enter</button>
<ul id="list1">
</ul>
<button id="stat_button" onclick="calculateMean()">Get Statistics</button>
<p id="mean">Mean= </p>
</div>
<script>
function list() {
var liElement = document.createElement("li"); //Creating new list element//
var ulElement = document.getElementById("list1"); //Get the ulElement//
var input = document.getElementById("value").value; //Get the text from the text box//
var numbers = []; //create Array called numbers
numbers.push(input);//adds new items to the array
//for loop//
for(var i=0; i < numbers.length; i++) {
liElement.innerHTML = numbers[0]; //Puts the array into the list for display//
ulElement.appendChild(liElement); //add new li element to ul element//
}
}
function calculateMean() {
var meanTotal = 0;
var meanAverage = 0;
var meanArray = [];
for (var i = 0; i < meanArray.length; i++) {
meanTotal += meanArray[i];
}
meanAverage = (meanTotal / meanArray.length);
document.getElementById("mean").innerHTML = meanAverage;
}
</script>
Try adding it through addEventListener instead of inline like that:
document.getElementById('value').addEventListener('change', function(e){
list()
})
The reason the Mean is always NaN is because your mean array is always an empty array when you start with. I think you were referring to a numbers array here.
You will have to declare the array outside the scope of the 2 functions, since it is the common to both.
And it is always a better idea to decouple Javascript and HTML. Bind your events in JS instead of inline event handlers.
Note: When you read the value from the input, it is a string, so convert it to a number before storing it in the numbers array.
HTML
<p>Array is called numbers. numbers.sort();</p>
<div id="stats">
<input type="text" id="value">
<!-- Getting the Onchange Error here -->
<button id="button1">Enter</button>
<ul id="list1">
</ul>
<button id="stat_button">Get Statistics</button>
<p id="mean">Mean= </p>
</div>
JS
document.getElementById('value').addEventListener('change', list);
document.getElementById('button1').addEventListener('click', list);
document.getElementById('stat_button').addEventListener('click', calculateMean);
var numbers = [];
function list() {
var liElement = document.createElement("li"); //Creating new list element//
var ulElement = document.getElementById("list1"); //Get the ulElement//
var input = document.getElementById("value").value; //Get the text from the text box//
numbers.push(input); //adds new items to the array
//for loop//
for (var i = 0; i < numbers.length; i++) {
liElement.innerHTML = numbers[0]; //Puts the array into the list for display//
ulElement.appendChild(liElement); //add new li element to ul element//
}
}
function calculateMean() {
var meanTotal = 0;
var meanAverage = 0;
for (var i = 0; i < numbers.length; i++) {
meanTotal += numbers[i];
}
meanAverage = (meanTotal / numbers.length);
document.getElementById("mean").innerHTML = meanAverage;
}
jsFiddle

Categories

Resources