html - Pass Value of Input Automatically With Javascript -


i working on passing value put text input box, text input box user types. got work on jsfiddle reason can't work if use anywhere else. im using pure javascript, not jquery.

so, here html code

    <input id="imput1" type="text" class="firstbox">     <p>box retrieve input</p>     <br />      <input id="gift_card_recipient" type="text" class="replica" value="box1" />     <input type="text" class="replica2" value="box2" /> 

and javascript using pass value user types, first box, second box:

(function() { var var1   = document.getelementbyid('imput1'),     var2   = document.getelementbyid('gift_card_recipient'),     callback = function () {         var2.value = this.value;     };  if (var1.addeventlistener) {     var1.addeventlistener('keyup', callback); } else {     var1.attachevent('onkeyup', callback); } }()); 

again, got work on jsfiddle, , here demo of looks like, reason, if use on pc on html file, or on server, wont work. linking js file in header, , inspected in chrome. here error got chrome:

uncaught typeerror: cannot read property 'addeventlistener' of null 

not sure why throwing that. here jsfiddle have works. doesn't on server or pc: http://jsfiddle.net/c3spm/

include script block @ end of body (or after elements in question). or wrap code in onload/ondomready handler.

the specific error getting because code running before elements in question have been parsed, means document.getelementbyid('imput1') returns null because can't find element. reason works in fiddle default jsfiddle wraps js in onload handler, when code runs elements have been parsed (you can change setting in jsfiddle using drop-down on left under "frameworks & extensions").


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -