[英]How to get element by name with $key
PHP 的PHP
//Here is my html for qty
<p>Qty : <input type="number" value="" name="qty<?php echo $key ?> onChange="findTotal()"/>
JS function JS功能
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?
如何在js函数中获取名称以计算数量?
You can use 您可以使用
document.querySelector("input['name^='qty']").value
if you don't have jQuery. 如果您没有jQuery。
This will select an input
with name
attribute starting with "qty". 这将选择
name
属性以“ qty”开头的input
。 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
. 这将返回一个
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 如果您使用的是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. 在纯DOM中,可以使用getElementsByTagName来获取所有输入元素,并循环遍历所得数组。 Elements with name starting with 'qty' get pushed to another array:
名称以“ qty”开头的元素将被推送到另一个数组:
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. 不要通过name属性的值查询元素。 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:
我不确定该键的目的是什么,以及为什么在findTotal方法中需要它,但这是一个示例:
<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 . 这是jsFiddle演示 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.