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

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

2 Comments

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.
Thenks @freedomn-m for your intervention don't hesitate to edit the post directely by adding your explication.
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>

6 Comments

Why do you use concat instead of +?
"This is a standard way to concatenate string in javascript" - no, it's not.
.concat() is used for Arrays, for strings you use the +
maybe i should delete the answer then??
@Transformer you can read refer to this stackoverflow.com/questions/16124032/…
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.