2013-12-16 3 views
0

В настоящее время я пишу JS code для вычисления количества полных входов. Проблема в том, что для моего фактического проекта я не могу напрямую изменить HTML, поскольку он создан из программы сценариев. Однако я могу манипулировать им с помощью JS.Динамически устанавливаемый атрибут onKeyUp с Javascript

До сих пор у меня есть div для добавления, который может отображать сумму входов. Но это работает, только если входы имеют атрибут onKeyUp(). Это не относится к сгенерированной HTML, поэтому мне нужно написать JS script, который добавляет его в этом то, что я сделал до сих пор:.

<html> 
<head> 
<script> 
    //try to set an onKeyUp attribute to the elements. 
    var number1 = document.getElementById("_Q0_Q0_Q0"); 
    number1.onkeyup = function(){ return summer()}; 

    var number2 = document.getElementById("_Q0_Q0_Q1"); 
    number2.onkeyup = function(){ return summer()}; 

    var number3 = document.getElementById("_Q0_Q0_Q2"); 
    number3.onkeyup = function(){ return summer()}; 

    function summer() { 
     var count = 0; //start with nothing 
     var num1 = (parseFloat(document.getElementById("_Q0_Q0_Q0").value)) || 0; //if there aren't any numbers, add nothing 
     var num2 = (parseFloat(document.getElementById("_Q0_Q0_Q1").value)) || 0; 
     var num3 = (parseFloat(document.getElementById("_Q0_Q0_Q2").value)) || 0; 
     count = num1+num2+num3; //sum them up 
     if (!document.getElementById("output")) { //check to see if there is a div with the output already, if not create one. 
     var newDiv = document.createElement('div'); 
     newDiv.setAttribute('id', 'output'); 
     var gutterDiv = document.getElementById("right_gutter") 
     gutterDiv.appendChild(newDiv); 
     }; 
     document.getElementById("output").innerHTML = "Your running total = "+count 
}; //show output 
</script> 
</head> 
<body> 
<input type="text" id="_Q0_Q0_Q0" name="number" /> 
<input type="text" id="_Q0_Q0_Q1" name="number" /> 
<input type="text" id="_Q0_Q0_Q2" name="number" /> 
<div id='right_gutter'> 
<button type="button" onclick="summer()">Clicking here adds your input to the "count" variable</button> //two purposes of this. 1) Acts as a placeholder for where the output should end up. 2) Shows that the summing function works. 
</div> 
<br> 
</body> 
</html> 
+0

обработчики событий чувствительны к регистру, поэтому он должен быть 'onkeyup'. – kamituel

+1

HTML нечувствителен к регистру, поэтому вы можете увидеть: ' ', но это не работает в JavaScript. – Halcyon

+0

Изменен для onkeyup, но он все еще не работает – Scironic

ответ

1

Не уверен если правильно, но не нужно так много коды.

JS

window.onload=function(){ 
function sum(){ 
    result.textContent="Your running total = "+ 
    ((form.a.value*1)+(form.b.value*1)+(form.c.value*1)); 
} 
var form=document.forms[0],result=document.getElementById('result'); 
form.addEventListener('keyup',sum,false); 
} 

HTML

<form><input name="a"><input name="b"><input name="c"></form> 
<div id="result"></div> 

пример

http://jsfiddle.net/cyLaF/

2

Рад, что вы получили его работы. Думаю, теперь это избыточно, но я отправляю этот ответ в случае, если он будет полезен в любом случае.

//Create a NodeList of all elements whose name='number': 
var nums = document.getElementsByName("number"); 

//add the onkeyup event to all nums: 
for(var n=0; n < nums.length; n++){ 
    nums[n].onkeyup = function(){return summer()}; 
} 

//add the click event to the button: 
document.getElementById("button").onclick = function(){return summer();} 


function summer() { 
    var count = 0; 
    for(var n=0; n < nums.length; n++){//iterate and sum values 
     count += parseFloat(nums[n].value) || 0; 
    } 
    //create the output element: 
    var outputDiv = document.getElementById("output") || document.createElement('div'); 
    //if it doesnt already exist append it: 
    if(!document.getElementById("output")){ 
      outputDiv.setAttribute('id', 'output'); 
      document.getElementById("right_gutter").appendChild(outputDiv); 
      createdAlready=true; 
     } 
    //set the output string: 
    outputDiv.innerHTML = "Your running total = "+count; 
} 

Демо: http://jsfiddle.net/8BrQE/2/

Смежные вопросы