Jarnail Singh
Jarnail Singh

Reputation: 85

JavaScript string concatenation not working

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); 
}

Upvotes: 3

Views: 1818

Answers (2)

Transformer
Transformer

Reputation: 3760

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>

Upvotes: 0

Zakaria Acharki
Zakaria Acharki

Reputation: 67525

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>

Upvotes: 5

Related Questions