3

This javascript code to concatenate isn't working. I tried an alert before closure of script tag, it's displayed but the code below that I want to display the result in third or different text field.

HTML:

<input type="text" id="field"><br>
<input type="text" id="str2"><br>
<input type="text" id="str3"><br>
<button onclick="concate()">Concatenate</button>

JavaScript:

var s=document.getElementById("field").value;
var t=document.getElementById("str2").value;
var st=document.getElementById("str3").value;

function concate()
{
    st=s+t;
    document.getElementById("str3").value.innerHTML=st;
    console.log(st);
    document.write(st); 
}
freedomn-m
  • 27,664
  • 8
  • 35
  • 57

2 Answers2

5

There's no function .value.innerHTML should be :

document.getElementById("str3").value = st;

Also you should get the fields value inside function and close your function definition using }, check example bellow.

Hope this helps.


function concate()
{
     var s=document.getElementById("field").value;
     var t=document.getElementById("str2").value;

     document.getElementById("str3").value=s+t;
}
<input type="text" id="field"><br>
<input type="text" id="str2"><br>
<input type="text" id="str3"><br>
<button onclick="concate()">Concatenate</button>
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
  • 1
    To confirm and clarify: when you get the values (in the question code), is when the script first runs (probably on load and most likely blank), not when you run `concat`. So any changes to the inputs occurs after you have already populated `s` and `t`. By putting them inside the function, you read the current values when the function is called. – freedomn-m Feb 18 '16 at 10:04
  • Thenks @freedomn-m for your intervention don't hesitate to edit the post directely by adding your explication. – Zakaria Acharki Feb 18 '16 at 10:07
0

function concate() {
    var s=document.getElementById("field").value;

    var t=document.getElementById("str2").value;

    var st=document.getElementById("str3").value;
    // this is a standard way to concatenate string in javascript
    var result = s+t;
    document.getElementById("str3").value=result;

}
<input type="text" id="field"><br>
<input type="text" id="str2"><br>
<input type="text" id="str3" readonly><br>
<button onclick="concate()">Concatenate</button>
Transformer
  • 3,642
  • 1
  • 22
  • 33