0

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?

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Interesting! This worked. I had no idea that you could add " this" as a parameter. Thanks. Any recommendations for javascript learning resources ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.