user6226210
user6226210

Reputation: 27

HTML display the input

I want to type something in the textfield and when I click the submit button to dispaly what I typed. For some reason It didn't display what I typed. I have two HTML files. the one file conatin "submited", the other conatins the function.

teach.html

<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
<meta charset="UTF-8">
</head>
<body>
<header>
 <h1>This is my site!</h1>
 </header>
 <section>
  <form name = "frm" method="post" action ="r.html">
 <h2>My site content</h2>
 <input type="text" id="nameInput">
   <button id="addName">Submit</button>
 <hr>
 </form>
 </section>
   </body>

r.html

  <!DOCTYPE html>
 <html lang="en">
 <head>
<meta charset="UTF-8">
 <title>Document</title>
 </head>
 <body>
<p id="name">name</p>

 <script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
 <script>
 $("#addName").click(function(){
  var myName = $("#nameInput").val();
 $("#name").html(myName);
 });
 </script>
  </body>
  </html>  

Upvotes: 0

Views: 70

Answers (2)

Leonardo Gazdek
Leonardo Gazdek

Reputation: 320

That's not how it works. You can either use a back-end language and display it on the other page, or you could use javascript and use a single page.

Here is a single-page solution with no back-end needed:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
    </head>
    <body>
        <header class="sec1">
            <h1>This is my site!</h1>
        </header>
        <section class="sec1">
            <h2>My site content</h2>
            <input type="text" id="nameInput">
            <button id="addName">Submit</button>
            <hr>
        </section>
        <section class="sec2">
            <p id="name">name</p>
        </section>

        <script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
        <script>
            $(".sec2").hide(); // this gets called when the page loads, hide anything that would be on page 2 for now
            $("#addName").click(function(){
                var myName = $("#nameInput").val();
                $("#name").html(myName);
                $(".sec1").hide(); // when the button is clicked, hide page 1 content
                $(".sec2").show(); // when the button is clicked, show page 2 content
            });
        </script>
    </body>
</html>

Upvotes: 0

user229044
user229044

Reputation: 239581

This is not at all how HTML and JavaScript works. You can't use JavaScript on your second page to access the form elements being submitted from your first page, submitting the form causes a full-page reload and the state of the first page is completely discarded before the JavaScript on the second page ever runs.

You need to combine both pages into one, and have the form-processing JavaScript prevent the submission of the form and then perform whatever dynamic processing you're interested in.

Upvotes: 1

Related Questions