Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
212 views
in Technique[技术] by (71.8m points)

javascript - issue with java script functions

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...