0

Please pardon my extreme naivety......I am trying to execute a javascript using the getElementByName method, but essentially, when I get to the site I want 0 to be entered in the quantity field (after 15 seconds of getting to said site).

This is what I get when I inspect the quantity field -

<input type ="text" name="quantity" value="1" size="3">

function emptylocation() {

    var myVar = setInterval(emptylocation, 15000);

    (document.getElementByName("quantity")[0].value = 0)
    (document.getElementByName("quantity")[1].value = 0)
    (document.getElementByName("quantity")[2].value = 0)
    (document.getElementByName("quantity")[3].value = 0)
    (document.getElementByName("quantity")[4].value = 0)
    (document.getElementByName("quantity")[5].value = 0)
}
Mister Jojo
  • 12,060
  • 3
  • 14
  • 33
Code_Guess
  • 15
  • 4
  • 1
    you need an `s`: `getElementsByName`, also, your `setInterval` function will create a new internal every time your functions runs (which happens every 15 seconds) – Nick Parsons Apr 01 '20 at 01:18
  • getElements not getElement – chiliNUT Apr 01 '20 at 01:19
  • I have added the s and it's still not executing. I don't know this is as a result of using getElementsByName as opposed to getElemenetsByID – Code_Guess Apr 01 '20 at 04:01

2 Answers2

1

document.getElementsByName()

An old method that has unexpected results in an edge case involving for loops. Instead use document.querySelectorAll()* which is the Swiss ArmyTM knife of DOM methods. Replace the following methods on the left with the methods on the right:

  <article class='x' name='x'></article>
  // ... Any amount of DOM elements that meet specific traits

  document.getElementsByClassName('x') /* ------> */ document.querySelectorAll('.x')
  document.getElementsByName('x') /* -----------> */ document.querySelectorAll('[name=x]')
  document.getElementsByTagName('article') /* --> */ document.querySelectorAll('article')

* Also see this article

document.forms & .elements

If these DOM elements are form controls (aka fields -- ex. <input>, <select></select>, etc), and are within a <form></form> (which they should be, although still valid without a <form></form>) -- .forms and .elements properties can be used:

<form id='x'>
  <input name='z'>
  // ... Any amount of fields with the name of 'z' (ie ['name=z'])
</form>

// Reference form#x
const fx = document.forms.x
// Reference all form controls within form#x
const fc = fx.elements
// Reference all form controls with ['name=z'] within form#x
const fz = fc.z

/* OR */
/* The above statements in one line */
const fXCZ = document.forms.x.elements.z

Demo

Details are commented in demo

//~~[1]~~
/* Reference DOM Elements *///

//1a. 
/* Example 1 */
// Reference all fields within form#example1
const exp1 = document.forms.example1.elements;
/*
Collect all input[name=quantity] within form#example1 into a HTML Collection
*/
const qty1 = exp1.quantity;

//1b. 
/* Example 2 */
// Reference form#example2
const exp2 = document.getElementById('example2');
/*
Collect all input within form#example2 into a NodeList 
*/
const qty2 = exp2.querySelectorAll('input');

//~~[2]~~
/* Define Function *///

//2.
/*
@Params collection -- An array-like object of fields (ex. qty1 or qty2)
        dataString -- A String assigned to each field - defaults to "0" 
                      if not specified
*/
function changeValue(collection, dataString = "0") {
  collection.forEach(field => field.value = dataString);
}

//~~[3]~~
/* Invoke setTimeout() *///

//3a.
/* Example 1 */
setTimeout(function() {
  changeValue(qty1, '0');
}, 15000);

//3b.
/* Example 2 */
setTimeout(function() {
  changeValue(qty2);
}, 15000);
<form id='example1'>
  <input name="quantity" type="number" value="1" size="3">
  <input name="quantity" type="number" value="1" size="3">
  <input name="quantity" type="number" value="1" size="3">
  <input name="quantity" type="number" value="1" size="3">
  <input name="quantity" type="number" value="1" size="3">
  <input name="quantity" type="number" value="1" size="3">
</form>
<hr>
<form id='example2'>
  <input name="quantity" type="number" value="1" size="3">
  <input name="quantity" type="number" value="1" size="3">
  <input name="quantity" type="number" value="1" size="3">
  <input name="quantity" type="number" value="1" size="3">
  <input name="quantity" type="number" value="1" size="3">
  <input name="quantity" type="number" value="1" size="3">
</form>
Community
  • 1
  • 1
zer00ne
  • 31,838
  • 5
  • 32
  • 53
0

You can do

var quantities = document.getElementsByName("quantity");
for(var i=0; i < quantities.length; i++) 
    quantities[i].value = 0;
}

It might also be better to use ID instead of name for such things.

Sunny Patel
  • 194
  • 1
  • 10
  • Thanks sir - I actually planned on using ID, but when I inspected element, I didn't see ID – Code_Guess Apr 01 '20 at 03:23
  • @Code_Guess that was just a suggestion btw. See [this](https://stackoverflow.com/a/7470407/2522616) answer for more details. – Sunny Patel Apr 01 '20 at 05:14
  • thanks so much, that really helped me...... Is it possible to do a for loop using the the document.querySelector? So, on this same page, I want the same javascript to cilck the "update quantity" button after inputting the number 0... There are multiple "update quantity" buttons on the page with the same input type – Code_Guess Apr 01 '20 at 23:43
  • @Code_Guess Sorry, I don't think I understand that completely. Can you give a tiny example of what you are trying to achieve and I can try to help you more? Btw, you can also upvote and mark correct answers ;) – Sunny Patel Apr 03 '20 at 00:03
  • I have a web page that has a list of various items. I go into this location regularly to empty it out by inputting 0 in the quantity field and then click an "update quantity" button, this process is/has to be done item by item. There are multiple quantity field and "update qty" buttons with the same element properties – Code_Guess Apr 03 '20 at 22:39
  • Oh okay, so you can have two types of buttons "Update Quantity' button like you already do which updates 1 textbox. AND you can make another button like "Update All" and use the code that I posted, which will update all the text fields with `name=quantity` to 0. – Sunny Patel Apr 04 '20 at 00:02
  • How do I go about creating the "Update All" button and make it do the action of updating the the quantities to 0? – Code_Guess Apr 04 '20 at 00:19