'Document.QuerySelector to fill a unique value with prepend and append
I am trying to use a JS code to fill up elements with their already filled up values as desribed in the table link image below:
For this code below, what modifcation will be required to get the desired final value?
var data = document.querySelectorAll("[id^='1253']").forEach(x => x.value
if( data > 0){
var result = '(' + data + ')'
document.querySelectorAll("[id^='1253']").forEach(x => x.value = result)
}
Solution 1:[1]
Not sure why you call querySelectorAll twice or what data is for:
document.querySelectorAll("[id^='1253']")
.forEach(o => {
if (o.value && !isNaN(o.value) && o.value < 0.9) o.value = `(${o.value})`;
});
<div><input id="1253~blah1" value="0.1" /></div>
<div><input id="1253~blah2" value="0.2" /></div>
<div><input id="1253~blah3" value="" /></div>
<div><input id="1253~blah4" value="0.9" /></div>
<div><input id="1253~blah5" value="11.2" /></div>
Solution 2:[2]
User innerText instead of value when setting the result in your elements. value is an html property and doesn't necessarily mean what's viewed on the screen.
if( data > 0) {
var result = '(' + data + ')'
document.querySelectorAll("[id^='1253']").forEach(x => x.innerText = result)
}
Solution 3:[3]
document.querySelectorAll("[id^='1253']")
.forEach(o => {
if (o.value && !isNaN(o.value) && o.value < 0.9) o.value = `(${o.value})`;
});
This is the code which solved my query. Thank you everyone.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | PsiKai |
| Solution 3 | Vicky Lahkar |
