Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

html/javascript how to display user input with a method on button click?

I'm trying to get an alert window to display the first and last name a user inputs after they click "submit". I'm trying to do this using methods in javascript, but I can't get it to display after the user clicks the button.

Here is my code:

<html>
<head>
    <meta charset = 'utf-8'>
    <title>Form</title>
    <script type = 'text/javascript'>
        var firstName; //first name
        var lastName; //last name
        function getFirstName() { //get first name
            return document.getElementById("first_name").value;
        }
        function getSecondName()    { //get last name
            return document.getElementById("last_name").value;
        }
        function display()  { //get the names and display them
            firstName = getFirstName();
            lastName = getLastName();
            window.alert(firstName + lastName);
        }
        document.getElementById("Submit").onclick = display();
    </script>

</head>
<body>
    <form id='form' method = 'post'>
        <p> First Name: <input type='text' id = "first_name"/></p>
        <p> Last Name: <input type='text' id = "last_name"/> </p>
        <p><input id ="Submit" type = "button" value = 'clickme' /></p>
    </form>
</body>
</html>
like image 549
Oscar A Garcia Avatar asked Aug 02 '26 18:08

Oscar A Garcia


1 Answers

http://jsfiddle.net/wqymjL32/

<form id='form' method = 'post'>
    <p> First Name: <input type='text' id = "first_name"/></p>
    <p> Last Name: <input type='text' id = "last_name"/> </p>
    <p><input id ="submit" type = "button" onclick="display()" value='clickme'/></p>
</form>

Slight change to the html, so that the onclick attribute / event is added to the submit button.

var firstName; //first name
var lastName; //last name
function getFirstName() {
    return document.getElementById("first_name").value;
}
function getSecondName() {
    return document.getElementById("last_name").value;
}
function display() {
    firstName = getFirstName();
    lastName = getSecondName();
    window.alert(firstName + lastName);
    document.getElementById("form").submit();

} 

Slight change to the javascript to call getSecondName instead of getLastName

like image 123
Ben Temple-Heald Avatar answered Aug 04 '26 08:08

Ben Temple-Heald



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!