user2856111
user2856111

Reputation: 205

display text in text field using javascript for multiple characters

I would like to use JavaScript to display text in an input text field using JavaScript. I can achieve this using individual lines of code for each character(9, 10, e...), but I can't consolidate this into one line of code which I know is possible. When I try consolidating, nothing shows up in the text area or it will just flash, but doesn't stay on the screen.

Here's my working code which works great, but I don't want to type this code for every character I want.

HTML

<form name="frm">
  <input type="text" name="result">
  <input type="button" name="3" value="7" onClick="run7()">
  <input type="button" name="4" value="8" onClick="run8()">
  <input type="button" name="3" value="9" onClick="run9()">
</form>

Javascript:

function run7(){
document.frm.result.value += "7";
}
function run8(){
document.frm.result.value += "8";
}
function run9(){
document.frm.result.value += "9";

Here's a list of things I triedI tried but did not work:

var character = document.getElementById('id').value;
document.frm.result.value = character;

I even changed the inputs to buttons

var character = document.getElementById('id').innerHTML;
document.frm.result.value = character;

var character = document.getElementById('id').innerHTML.value;
document.frm.result.value = character;

var character = document.getElementById('id').value.innerHTML;
document.frm.result.value = character;

var textField = document.frm.result;
function runEverything() {
 textField.onclick(function) {
   textField = document.getElementById('id').innerHTML;
 }
}

Of course I'm still a virgin to Javascript. But seriously, what I'm I missing here?

Upvotes: 0

Views: 184

Answers (1)

Paulo Segundo
Paulo Segundo

Reputation: 448

try this:

<form>
    <input type="button" name="3" value="7" onClick="run(this)">
    <input type="button" name="4" value="8" onClick="run(this)">
    <input type="button" name="3" value="9" onClick="run(this)">
</form>

function run(src){
    document.frm.result.value += src.value;
}

Upvotes: 1

Related Questions