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:
You assignBecause the JavaScript code already runs inonclick
toconvert
and not toconverter
!window.onload
in jsFiddle, you simply can accessconvert
.- And you set
onclick
to the return value offillFun()
. 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;
}
精彩评论