Home > Software engineering >  using eventlistener and DOM to change text on another html
using eventlistener and DOM to change text on another html

Time:05-25

I am trying to get input in one html form and then using event listener on a button to move to another html page as well as change the innerHTML of the 2nd html page to the input from 1st page but only the page switches but the innerHTML doesnt change this is main html

    <form>
        <label for="fname">First name:</label><br>
        <input type="text" id="fname" name="fname"><br>
        </form>
    <button  id="Butn1" onclick="location.href = 'resume.html';">Submit</button>
<script src="main.js"></script>

this is the 2nd html page

 <div>
        Name: <br>

        <p id="fname1">hello</p>

    </div>
<script src="main.js"></script>

and this is the js file

document.getElementById("Butn1").addEventListener("click",func1);
var a=document.getElementById("fname").value;
function func1(){
    
    document.getElementById("fname1").innerHTML = a;

}

CodePudding user response:

you can use this way.
if this is your first page:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form>
        <label for="fname">First name:</label><br>
        <input type="text" id="fname" name="fname"><br>
        </form>
    <button  id="Butn1" onclick="handleClick()">Submit</button>
    <script>
        function handleClick()
        {
            location.href = 'secondPage.html?name='   document.getElementById("fname").value;
        }
    </script>
</body>
</html>

this one would be your second page

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        const urlParams = new URLSearchParams(window.location.search);
        const myParam = urlParams.get('name');
        alert(myParam);
    </script>
</body>
</html>

but it is not recommended to use this if your string is too long.

  • Related