Concatenate multiple HTML text inputs with stored variable

守給你的承諾、 提交于 2019-11-29 12:47:42

Here is a solution, so get the elements using document.getElementById(), attach an event handler to the click event using element.onclick = function () {} and alert() to show a message box.

jsFiddle

JavaScript

var button = document.getElementById('test');
var name = document.getElementById('name');
var age = document.getElementById('age');
var location = document.getElementById('location');

button.onclick = function () {
    var str = 'Hello ' + name.value + 
        ', you are ' + age.value +
        ' years old and from ' + location.value;
    alert(str);
};

HTML

<label>
    Enter name: 
    <input id="name" />
</label>
<br />
<label>
    Enter age: 
    <input id="age" />
</label>
<br />
<label>
    Enter location: 
    <input id="location" />
</label>
<br />
<button id="test">Test</button>

Edit

To output it to the page use element.innerHTML to set the contents of an element.

jsFiddle

output.innerHTML = str;

function yes() {
var button = document.getElementById('test');
var name = document.getElementById('name');
var age = document.getElementById('age');
var location = document.getElementById('location');
    var str = 'Hello ' + name.value + 
        ', you are ' + age.value +
        ' years old and from ' + location.value;
    document.getElementById('test').innerHTML=str;
};
<html>
<body>
<label>
    Enter name: 
    <input id="name" />
</label>
<br />
<label>
    Enter age: 
    <input id="age" />
</label>
<br />
<label>
    Enter location: 
    <input id="location" />
</label>
<br />
<button onclick="yes()">Test</button>
<p id="test"></p>
</body>
</html>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!