0

PHP

<input type="number"  min="0" max="500" value="" name="qty<?php echo $key ?>" id="<?php echo $key ?>" onChange="findTotal()" />

JS

function findTotal() {
    var arr = document.getElementsByName('qty');
    ....
}

How do I get element by name which has $key inside?

Chin Leung
  • 14,621
  • 3
  • 34
  • 58
Steve
  • 9
  • 5

4 Answers4

0

Let's say $key is 'x'. You could then use getElementbyID('x'), because echoing $key is the same as putting id="x".

joshcoles
  • 1
  • 1
0

Oh, I see. you have series of rows with the different qty keys.

then try this.

in PHP:

<input type="number" min="0" max="500" value="" name="qty<?php echo $key ?>" id="<?php echo $key ?>" onChange="findTotal('qty<?php echo $key?>')" />

and in JS:

 function findTotal(key) {
    var arr = document.getElementsByName(key);
    ....
}
JP Kim
  • 743
  • 8
  • 26
  • weird..it should work. I guess you have to check other part of the codes first. check the html out source if echo $key actually works. for example, if the key value is "abc", then the html look like this: – JP Kim May 02 '17 at 04:24
0

You can assign thisas your function params then you can call its name or id from your function when onchange event executed !!

//assign this
<input type="number"  min="0" max="500" value="" name="qty<?php echo $key ?>" id="<?php echo $key ?>" onChange="findTotal(this)" />

function findTotal(current) {
  var arr = current.name; // current.id for id
  alert(arr);    
}
Jack jdeoel
  • 4,554
  • 5
  • 26
  • 52
0

Since your name is dynamic, you can not get the element by the name unless your JS has some way of knowing that dynamic name (such as if you have a list of them and are running them in a loop).

In your case, you may want to try using data attributes as outlined here: Mozzila - Using data attributes

You may also be able to take advantage of this as outlined in this answer: Javascript Get Element Value - Answer By yorick

Let me know if this helps. I may be able to refine this answer if you can give some more information about your specific implementation.

Cheers!

Community
  • 1
  • 1
Justin Waulters
  • 303
  • 2
  • 8