开发者

Copy input from one place and use it as a variable or in another area using onclick

I'm trying to figure out how to take values from one of these input boxes and duplicate them in another input box. This action would be very useful in another project I'm working on but, I can seem to get it to work. What am I doing wrong?

http://jsfiddle.net/qBFAe/

HTML

Field1: <input type="text" id="field1" />
<br />
Field2: <input type="text" id="field2" />
<br /&开发者_如何转开发gt;<br />
Click the button to copy the content of Field1 to Field2.
<br />
<button id="convert">Copy Text</button>

JS

var converter = document.getElementById("convert");
var ff2 = document.getElementById('field2');
var ff1 = document.getElementById('field1');
convert.onclick = fillFun();

function fillFun(){
ff2.value=ff1.value;

}


You have to do this after elements are loaded, in the window.onload event, plus assign the function as the event handler properly (without parentheses). Fixed code:

var ff2 = null;
var ff1 = null;

window.onload = function() {
    ff2 = document.getElementById('field2');
    ff1 = document.getElementById('field1');
    var converter = document.getElementById("convert");
    converter.onclick = fillFun;
};


function fillFun(){
    ff2.value = ff1.value;
}

Updated jsFiddle.


You have two errors:

  1. You assign onclick to convert and not to converter! Because the JavaScript code already runs in window.onload in jsFiddle, you simply can access convert.
  2. And you set onclick to the return value of fillFun(). You don't must have brackets!

The corrected code: http://jsfiddle.net/qBFAe/1/

var converter = document.getElementById("convert");
var ff2 = document.getElementById('field2');
var ff1 = document.getElementById('field1');
converter.onclick = fillFun;

function fillFun(){
    ff2.value=ff1.value;

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜