using getElementById("id") it will return only the first element with id, so to select all elements with same id we can use querySelectorAll("#id"), which will return all elements with that id.
let elements = document.querySelectorAll("#currency");
after selecting all the elements we can use the foreach to add the event in each element in this way:
elements.forEach(el => {
el.onblur = () => {
//number-format the user input
el.value = parseFloat(el.value.replace(/,/g, ''))
.toFixed(2)
.toString()
.replace(/\B(?=(\d{3})+(?!\d))/g, '.');
//set the numeric value to a number input
el.value = el.value.replace(/,/g, '');
};
});
remembering that it is not recommended to have more than one element with the same id in an html file, I believe that you could identify the elements using a class and get the elements this way:
let elements = document.querySelectorAll(".currency");
So you could pass a foreach on Elements in the same way.
html used for testing:
<td>
<tr>
<input name='product_cost[]' placeholder='0.00' class='currency' type='text' class='form-control'
placeholder='0.00' required>
</tr>
</td>
<td>
<input name='product_pvp[]' placeholder='0.00' class='currency' type='text' class='form-control' placeholder='0.00'
required>
</td>
<td>
<input name='product_pvp[]' placeholder='0.00' class='currency' type='text' class='form-control' placeholder='0.00'
required>
</td>
<td>
<input name='product_pvp[]' placeholder='0.00' class='currency' type='text' class='form-control' placeholder='0.00'
required>
</td>
If you’re going to have one more input then I suggest using a class so that you don’t have two elements with the same id.
– Gabriel José de Oliveira
how so? what I intend to find is all the same ID and modify them...
– John
@John is not possible. You may even have several inputs with the same ID, but Javascript will consider only one of them.
– Valdeir Psr
you can even select all elements with the same id this way: Document.querySelectorAll("#id");
– Gabriel José de Oliveira
doesn’t work. I replace it with Document.querySelectorAll('#currency'). onblur =Function(), and nothing
– John
Using my code, you can help me right?
– John
Okay, I’ll see what I can do
– Gabriel José de Oliveira
if the answer does not solve your problem edit your question by also inserting the html snippet, so that I can better understand the structure of your page
– Gabriel José de Oliveira
Brotherzinho, an id is like a CPF, each one has its own single. If you are using equal id’s in more than one element, it is a sign that you need to learn HTML. Ever wonder if more than one person had the same number, what the hell wouldn’t it be? :D
– Sam