admin管理员组文章数量:1364143
I'm trying to add ma to a string and show that into label through following function :
HTML :
<input type="text" onkeyup="addCommas(this.value);" /> <br /><br />
<label id="result">Result: </label>
JS
function addCommas(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
var result = x1 + x2;
document.getElementById('result').value = result;
}
JsFiddle
But won't show the result into label.
What am i doing wrong?
I'm trying to add ma to a string and show that into label through following function :
HTML :
<input type="text" onkeyup="addCommas(this.value);" /> <br /><br />
<label id="result">Result: </label>
JS
function addCommas(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
var result = x1 + x2;
document.getElementById('result').value = result;
}
JsFiddle
But won't show the result into label.
What am i doing wrong?
Share Improve this question edited Jun 25, 2014 at 8:16 Hamed Kamrava asked Aug 17, 2013 at 7:41 Hamed KamravaHamed Kamrava 12.9k34 gold badges92 silver badges128 bronze badges 1-
2
No wrap - in <head>
. – elclanrs Commented Aug 17, 2013 at 7:45
3 Answers
Reset to default 5Label doesn't use value
to assign values. It uses innerHTML
. Try the below.
document.getElementById('result').innerHTML = result;
As pointed out in ments, it is better to use textContent
or innerText
options to set value (only for plain text) as they are safer than innerHTML
.You can use it as shown below.
document.getElementById('result').textContent = result;
or
document.getElementById('result').innerText = result;
innerText
property is not supported by FireFox and it uses the textContent
property. Hence, the below method will work across browsers.
var resultDiv = document.getElementById('result');
if (typeof resultDiv.innerText === 'string') {
resultDiv.innerText = result;
}
else {
resultDiv.textContent = result;
}
Sources:
- IE8 label update via javascript issue
- 'innerText' works in IE, but not in Firefox
Try this
document.getElementById('result').innerHTML = result;
instead of .value
, use .innerHTML
Use innerHTML
instead of value
:
document.getElementById('result').innerHTML = result;
JSFIDDLE http://jsfiddle/J4mLD/1/
Also note, to use inline event handlers in JSFIDDLE you must set the second dropdown to one of the nowrap options.
本文标签: javascriptJS Add comma to a stringStack Overflow
版权声明:本文标题:javascript - JS: Add comma to a string - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743775988a2536986.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论