当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - How to automatically add the values inserted by user in the text fields then display total on div?

问题描述:

I currently have this html code:

<a href="#" onclick="addmore()">Add More Field</a>

<div id="addmore">

<ul class="jcform" id="countme">

<li><input id="name" class="form-control" name="cname[]" type="text" value=""/></li>

<li><input id="score" class="form-control" name="cscore[]" type="text" value=""/></li>

</ul>

</div>

Total: <div id="displaytotalscore"></div>

Below is my javascript:

function removeme(numm) {

document.getElementById('remove'+numm+'').remove();

}

function addmore() {

var top_level_div = document.getElementById('addmore');

var count = top_level_div.getElementsByTagName('ul').length;

var ul = document.createElement('ul');

ul.className = 'jcform';

ul.id = 'remove' + count;

var tbl1 = '<li><input class="form-control" id="field1" name="cname[]" type="text"

value=""/></li>

<li><input class="form-control" id="fieldpoints1" name="cpoints[]"

type="text" value=""/></li>

<li><a href="#" class="btn btn-danger" onclick="removeme(' + count + ')">

Removed</a></li>';

ul.innerHTML = tbl1;

document.getElementById('addmore').appendChild(ul)

}

What i want to achieve is, when a user enters values in the text fields id="score", i want to display the total sum in the div id="displaytotalscore". I am not sure how to use onchange event here.

Ok here's the jsfiddle link http://jsfiddle.net/41fw2c4x/

网友答案:

document.querySelector("#score").addEventListener("change", function(){
  document.querySelector("#displaytotalscore").textContent = this.value;
}, false);
<a href="#" onclick="addmore()">Add More Field</a>
<ul class="jcform" id="countme">
  <li><input id="name" class="form-control" name="cname[]" type="text" value=""/></li>
  <li><input id="score" class="form-control" name="cscore[]" type="text" value=""/></li>
</ul>

 Total: <div id="displaytotalscore"></div>
分享给朋友:
您可能感兴趣的文章:
随机阅读: