Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am adding two text boxes using function and want to display result in third text box. For this I used two functions. First getdata() to read first textbox value and second is getdata1() to read second textbox value. I also use onchange event. but in result it display NaN. Please, help me. Here is my Code

var a, b, c;

function getdata(txt) {
  x = txt.value;
  if (!isNaN(x)) {
    a = parseInt(document.getElementById("txt").value);
  } else {
    alert("Input not valid");
    txt.focus();
    txt.value = "";
  }
}

function getdata1(txt) {
  x = txt.value;
  if (!isNaN(x)) {
    b = parseInt(document.getElementById("txt").value);
  } else {
    alert("Input not valid");
    txt.focus();
    txt.value = "";
  }
}

function myFunction(s, t) {
  var s = a;
  var t = b;
  var c = s + t;
  document.getElementById("result").value = c;
}
<td><input type="text" name="txt[]" id="txt[]" onchange="getdata(this)" /></td>
<td><input type="text" name="txt[]" id="txt[]" onchange="getdata1(this)" /></td>
<td><input type="text" name="result" id="result" onfocus="myFunction()" /></td>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
205 views
Welcome To Ask or Share your Answers For Others

1 Answer

first of all, if you have multiple element that has the same ids, the first or last will be the only one fetched by your selector. Second, attribute 'id' is called id because it gives identity to your element, which basically means try not to give same identity to each elements. Third, you're getting NaN because you're looking for an element with id 'txt' but there is none in your page (this error occurs in your parseInt part). The id of your element is 'txt[]'. Try changing those ids to 'txt1' and 'txt2' for the other one and change your scripts. Update me when you've fixed it. cheers


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...