50

I am trying to create a simple JavaScript function. When someone inserts a number in an input field, the value of another field should change to that value. Here is what I have at the moment:

function updateInput(ish) {  
    fieldname.value = ish;  
}  
<input type="text" name="fieldname" id="fieldname" />  
<input type="text" name="thingy" onchange="updateInput(value)" /> 

Somehow this does not work, can someone help me out?

Cray
  • 2,774
  • 7
  • 22
  • 32
Jay Wit
  • 2,987
  • 7
  • 32
  • 34
  • 4
    **For googlers** who look for how to listen to an input element's change/input event: [check this answer](http://stackoverflow.com/a/25453163). – totymedli Nov 11 '15 at 14:33

3 Answers3

62

You can't access your fieldname as a global variable. Use document.getElementById:

function updateInput(ish){
    document.getElementById("fieldname").value = ish;
}

and

onchange="updateInput(this.value)"
Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487
  • 3
    Actually, for every DOM element with "id" attribute, a matching variable is created on the global Window object. (open the console and type "mainbar" on this page). more than this, for modern browsers you can just type "value" and leave the "this". – YardenST Apr 28 '13 at 21:00
  • 1
    I normally add this to my page for ease: `function id(id){return document.getElementById(id);}` and use it like this `id("whatever").whatever` – DividedByZero Oct 17 '14 at 17:16
8

for jQuery we can use below:

by input name:

$('input[name="textboxname"]').val('some value');

by input class:

$('input[type=text].textboxclass').val('some value');

by input id:

$('#textboxid').val('some value');
Aditya P Bhatt
  • 21,431
  • 18
  • 85
  • 104
1
<input type="text" name="fieldname" id="fieldtobechanged" />  
<input type="text" name="thingy"  id="inputfield" />

I have used following code and it works instantly without any delay.

var timeoutID = null;
    
function findMember(str) {
    document.getElementById("fieldname").innerHTML = str;
}

$('#inputfield').keyup(function(e){
    clearTimeout(timeoutID);
    timeoutID = setTimeout(findMember.bind(undefined, e.target.value), 500);
});
Observer
  • 345
  • 1
  • 4
  • 21