0

I have a simple code in order to hide objects inside a div until a button is pressed.
The code works, but after execute the alert, the code roll back.
I understand there are several options to do the same, but same behavior occurs for others I have attempt (such as https://www.w3schools.com/jsref/prop_style_visibility.asp).
So I have attempt the removeAttribute style because it's easier to watch on Console.
I have attempt to put the script before the form, and after form, but same behavior occurs.
I have add some snapshots from Console in order to demonstrate it, please see below.
I am not sure what am I doing wrong. Tested on Chrome (89.0.4389.114) and Edge (89.0.774.75).

Any help is highly appreciated!
Thank you in advance.

PS. It is running inside a php code (using echo) due it has conditional values.
**PS. It works fine outside a form**
<body>
    <form ...
        (...)
        <div class="field" id="pwdDIV" style="visibility: hidden">
        ..somocode..
        </div>
        <button class="button" onclick="showPwd()">Show Password</button>
    </form>

<script>
function showPwd() {
    var z = document.getElementById('pwdDIV');
    alert("Get Style: "+z.style.visibility);
    if (z.style.visibility === 'hidden') {
        z.removeAttribute("style");
        alert("Change to Style: "+"visible");
    } else {
        (...)
    }
}
</script>
</body>

Before Press Show Password button Before Press Show Password button

After press Show Password button - executing alert parameter After press Show Password button - executing alert parameter

After execute Javascript code After execute Javascript code

Outside form sample (works fine outside forms)

<html>

<head>
  <script type="text/javascript">
    function showPwd() {
      var z = document.getElementById('pwdDIV');
      if (z.style.visibility === 'hidden') {
        z.removeAttribute("style");
      } else {
        z.setAttribute("style", "visibility: hidden");
      }
    }
  </script>
</head>

<body>
  <button onclick="showPwd()">Show Password</button>
  <div id="pwdDIV" style="visibility: hidden">
    <input type="password" id="pwd1" name="pwd1">
  </div>
</body>

</html>
Himanshu Saxena
  • 340
  • 3
  • 13

0 Answers0