简体   繁体   中英

Why does my Submit button require 2 clicks before running desired script the first time?

I am new to java-script and have made this script to popup this custom message when a visitor submits an e-mail. However, for some reason the 'display:block' only happens after the second time the user clicks "Submit" and not after the first click. However, each subsequent time after that (unless the page is reloaded) the function works with only 1 click. The only way I have been able to make it function as desired is by adding onLoad="eSubmit" to hte body tag (essentially taking the place of the first click), but I don't want to have to do that. All applicable code I have is below... I would appreciate any help, thanks.

<head>
<style type="text/css">
.alertbox{
position:absolute;
top:0;
left:0;
width:100%;
height:100%;
background-color:rgba(0,0,0,.6);
z-index:100;
display:none;
}
</style>

<script type="text/javascript">

function eSubmit() {
    var msgBox = document.getElementById("msgSend");
    var responseTxt = document.getElementById("thanks");

   if(msgBox.style.display == 'block' || msgBox.style.display ==''){
      msgBox.style.display = 'none';}

   else{
      msgBox.style.display = 'block';}

   if(responseTxt.innerHTML == 'Returning to page...'){
        responseTxt.innerHTML = 'Thank you for submitting your e-mail.';}
}

function txtChange(){
    var E = setTimeout("eSubmit()",1000);
    var responseTxt = document.getElementById("thanks");

    if(responseTxt.innerHTML == 'Thank you for submitting your e-mail.'){
        responseTxt.innerHTML = "Returning to page...";
        E;} 
}

</script>
</head>

<body>
<input type="button" value="Send" onclick="eSubmit()">

<div id="msgSend" class="alertbox">
    <div onClick="txtChange()">
        <p id="thanks">Thank you for submitting your e-mail.</P>
    </div>
</div>

</body>

Just guessing, but look into this

   if(msgBox.style.display == 'block' || msgBox.style.display ==''){
      msgBox.style.display = 'none';}

The display property is set to an empty string even if there's an explicit setting inside . According to the W3C recommendation, .style-properties are only reflecting properties set inside the style=""-attribute of the element itself, not any computed or inherited settings defined elsewhere.

Because of that the if-statement becomes true and sets display to none on the first click.

Solution: change your if-else-logic or initialize the CSS display property as a style-attribute matching your needs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM