2016-09-23 1 views
0

У меня есть два ввода текста для пользователя к типу номера, и я хотел бы страницу, чтобы вывести итог этих двух чисел в другом вводе текстаOnChange события не принимает мой яваскрипта кода

<input id="attendance_1" onchange="parseInt(document.getElementById('attendance_output').value) += parseInt(this.value);" type="text" name="attendance_1" value="" /> 
 

 
<input id="attendance_2" onchange="parseInt(document.getElementById('attendance_output').value) += parseInt(this.value);" type="text" name="attendance_2" value="" /> 
 

 
// The results of adding the two text values should go here 
 
<input id="attendance_output" type="text" value="" />

я получаю ошибку:

ReferenceError: invalid assignment left-hand side

+0

[TRY] (https://jsfiddle.net/q4cv6qdt/3/) это один мат. – KiRa

ответ

2

Предлагаю поместить код вашего обмена в функцию и просто вызвать эту функцию onclick. Это облегчает отладку.

Пример

function addValue(field) { 
    parseInt(document.getElementById('attendance_output').value) += parseInt(field.value); 
} 

<input id="attendance_1" onchange="addValue(this)" type="text" name="attendance_1" value="" /> 

<input id="attendance_2" onchange="parseInt(document.getElementById('attendance_output').value) += parseInt(this.value);" type="text" name="attendance_2" value="" /> 

// The results of adding the two text values should go here 
<input id="attendance_output" type="text" value="" /> 

Но проблема в том, что ваш расчет не назначен ни к чему. Вы берете значение поля, разбираете его и пытаетесь и значение для результата синтаксического анализа.

Я думаю, вы хотите добавить это значение в значение поля и назначить его ?!

function addValue(field) { 
    var val = parseInt(document.getElementById('attendance_output').value); 
    val += parseInt(field.value); 
    document.getElementById('attendance_output').value = val; 
} 
+1

Спасибо за ваше время, но поле вывода говорит «NaN» –

+0

Если одно из полей не имеет действительного числа в качестве текущего значения, результатом будет NaN. Да. –

+1

Благодарим за помощь. Он решен. –

1

Просьба под кодом. он должен работать. ваш код не работает, потому что выражение + = sign.

<input id="attendance_1" onchange="document.getElementById('attendance_output').value=parseInt(document.getElementById('attendance_output').value) + parseInt(this.value);" type="text" name="attendance_1" value="" /> 
 

 
<input id="attendance_2" onchange="document.getElementById('attendance_output').value=parseInt(document.getElementById('attendance_output').value) + parseInt(this.value);" type="text" name="attendance_2" value="" /> 
 

 
// The results of adding the two text values should go here 
 
<input id="attendance_output" type="text" value="" />

+1

Я пробовал это, прежде чем я пришел сюда, то же самое. В тексте результата «NaN» говорится: –

1

Так что это на самом деле основной JS с typechecks

function addValue(field) { 
    parseInt(document.getElementById('attendance_output').value) += parseInt(field.value); 
} 

<input id="attendance_1" onchange="addValue(this)" type="text" name="attendance_1" value="" /> 

<input id="attendance_2" onchange="parseInt(document.getElementById('attendance_output').value) += parseInt(this.value);" type="text" name="attendance_2" value="" /> 

// The results of adding the two text values should go here 
<input id="attendance_output" type="text" value="" /> 

Но проблема в том, что ваш расчет не назначен ни к чему. Вы берете значение поля, разбираете его и пытаетесь и значение для результата синтаксического анализа.

Я думаю, вы хотите добавить это значение в значение поля и назначить его ?!

function addValue(field) { 
    var oVal = parseInt(document.getElementById('attendance_output').value); 
    var iVal = parseInt(field.value); 

    if(!oVal || Number.isNaN(oVal)) { 
     oVal = 0; 
    } 

    if(!iVal || Number.isNaN(iVal)) { 
     iVal = 0; 
    } 

    oVal = oVal + iVal; 

    document.getElementById('attendance_output').value = oVal; 
} 
1

попробуйте это. :) он не будет работать должным образом, если пользователь вводит строку, поэтому я думаю, что она должна иметь валидацию.

function addValue() { 
var num1 = document.getElementById('attendance_1').value; 
var num2 = document.getElementById('attendance_2').value; 
if (num1 === ''){ 
    num1 = 0; 
} 
if(num2 === ''){ 
    num2 = 0; 
} 

    var sum = parseInt(num1) + parseInt(num2); 
    document.getElementById('attendance_output').value = sum; 

} 

вы можете сделать текстовое поле принимает только цифры, с помощью JQuery

$(document).ready(function() { 
$("#attendance_1, #attendance_2").keydown(function (e) { 
    if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 || 
     (e.keyCode == 65 && (e.ctrlKey === true || e.metaKey === true)) || 
     (e.keyCode >= 35 && e.keyCode <= 40)) { 
      return; 
    } 
    if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) { 
     e.preventDefault(); 
    } 
    }); 
}); 
1

Используйте этот код внутри

 
onchange="document.getElementById('attendance_output').value=+document.getElementById('attendance_output').value+ +this.value" 

Надеется, что это будет полезно для вас :)

1

Это может быть вариант. Я полностью удалил встроенный JS. Пошел от onchange к обработчику oninput, который будет выполнять только расчет, если приведенные значения фактически являются номерами не строк.

var inpt = document.querySelectorAll('.attendance'); 
 
var out = document.getElementById('attendance_output'); 
 

 
var onInput = function(e) { 
 
    if(/\d/.test(this.value)) { 
 
    var sum = [].slice.call(inpt).reduce(function(a, b) { 
 
     if (a.value.length && b.value.length) { 
 
     return +a.value + +b.value; 
 
     } else { 
 
     return +a.value || +b.value; 
 
     } 
 
    }) 
 
    out.value = sum || this.value; 
 
    } else { 
 
    out.value = ""; 
 
    } 
 
} 
 

 
inpt.forEach(function(el) { 
 
    el.addEventListener('input', onInput, false) 
 
})
<input class="attendance" type="text" name="attendance_1" value="" /> <span>+</span> 
 
<input class="attendance" type="text" name="attendance_2" value="" /> 
 

 
<br><br> 
 
<input id="attendance_output" type="text" value="" disabled />

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

  • Нет связанных вопросов^_^