首页 > 解决方案 > Create a custom/prettier confirm() and use it in if() statement

问题描述

The closest I found researching for what I was looking for is this: Making a confirm box Unfortunately, I could not make it do exactly what I wanted or I didn't understand. I am new to Java/Javascript and HTML. I am using Google Scripts to create a custom user interface for, Google Sheets to make capturing the input needed user friendly. I am stuck on trying to include a custom confirm in my validation code. To test it I just created a simple web app with below code: (I created some Psuedo code and commented it out in the myFunction function within the code below)

function doGet(){
  var template = HtmlService.createTemplateFromFile('Basic'); 
  return template.evaluate()
      .setTitle('Example App')
      .setSandboxMode(HtmlService.SandboxMode.IFRAME);    
}
<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
        <!--Import Google Icon Font-->
      <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
      
      <!-- Compiled and minified CSS -->
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">

      <!--Let browser know website is optimized for mobile-->
      <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <style>
    .confirmBox {
      display: none;
      background-color: rgba(0, 0, 0, 0.40);
      border: 1px solid #ddd;
      position: fixed;
      -webkit-transition: -webkit-box-shadow .25s;
      transition: -webkit-box-shadow .25s;
      transition: box-shadow .25s;
      transition: box-shadow .25s, -webkit-box-shadow .25s;
      border-radius: 2px;
      width: 250px;
      left: 50%;
      margin-left: -100px;
      padding: 6px 8px 8px;
      box-sizing: border-box;
      text-align: center;
      color: #ffffff;
      font-size: 24px;
      z-index:99;
    }
      
    .confirm .message {
      text-align: left;
    }
  </style>
  </head>
  <body>
    <div id="cfrmBox" class="confirmBox">
      <div id="cfrmBoxMsg" class="message"></div>
      <button id="idYesButton" class="btn waves-effect waves-light z-depth-5" >Yes</button>
      <button id="idNoButton" class="btn waves-effect waves-light z-depth-5" >No</button>
    </div>
    
    <div class="container">
      <div class="row">
        <div class="col s12">
          <br><br>
          <div class="card">
            <div class="card-image">
              <span class="card-title">Timer</span>
                <a class="btn-floating halfway-fab waves-effect waves-light teal z-depth-5 tooltipped"
                   data-position="top"
                   data-tooltip="Press to start and stop timer" onclick="startStopTimer()">
                <i id="idStopWatch" class="large material-icons">access_time</i></a>
            </div>
            <div id ="idCardContent" class="card-content" style="color: #4db6ac;
                                                                 font-weight: bold;
                                                                 font-weight: 150%">
              <p id = "idCardContentP">04:10:24</p>
            </div>
          </div> 
           
          <button class="btn waves-effect waves-light z-depth-5" id="btnNextTask" onclick="myFunction()">Next Task
            <i class="material-icons right">music_note</i>
          </button>
        </div> <!-- END col END -->
      </div> <!-- END row END -->
    </div> <!-- END Container -->
        
    <!-- Compiled and minified JavaScript -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"> </script>
  <script>
  
    function appearNow(tMessage){
      var x = document.getElementById('cfrmBoxMsg');
      x.innerHTML = tMessage;
      var y = document.getElementById('cfrmBox');
      y.style.display = "inline";
    }
    
    function myFunction() {
      var stTime = document.getElementById('idCardContentP').innerHTML;
      if (stTime != "") {
        //Had function left in front. Corrected 
        appearNow('Do you want to save your time for this task?')
        
        // This is where I want to capture if the 'yes' or 'no' button was pressed
        //Psuedo code below
        /*
        if(document.getElementById('idYesButton').click == true){
          y.style.display = "none";
          M.toast({html: 'You clicked YES and time has been saved and here is the next task'});
        } else {
          y.style.display = "none";
          M.toast({html: 'You clicked NO and we will do nothing'});
        }
        */
        //Continue with more validation code
        
      } else {
        M.toast({html: 'Since the timer has not started you can freely move to the next task'});
      }
    }
  
    function startStopTimer() {
      M.toast({html: 'Timer is hard coded to be greater than 0 for testing!'});
    }
  </script>
  </body>
</html>

I greatly appreciate any help.

标签: javascripthtml

解决方案


It really seems like nested if statements to create one function to do one particular set of validations isn't really workable in this world since once a function is called it has to complete unless the built-in confirm() is called which is practical but ugly. So I had to rethink my logic route and realized to do what I want and have a custom confirm box I can't make it a nice reusable, neat and tidy function. I have to create a separate function for each validation and create a new '

<div id="cfrmBox" class="confirmBox">

' each time I want to use it, with the buttons that call a specific function with the 'onclick' each time specific to that validation. This can, in my opinion, make the code bulky. But, it works.

function doGet(){
  var template = HtmlService.createTemplateFromFile('Basic'); 
  return template.evaluate()
      .setTitle('Example App')
      .setSandboxMode(HtmlService.SandboxMode.IFRAME);    
}
<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
        <!--Import Google Icon Font-->
      <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
      
      <!-- Compiled and minified CSS -->
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">

      <!--Let browser know website is optimized for mobile-->
      <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <style>
    .confirmBox {
      display: none;
      background-color: rgba(0, 0, 0, 0.40);
      border: 1px solid #ddd;
      position: fixed;
      -webkit-transition: -webkit-box-shadow .25s;
      transition: -webkit-box-shadow .25s;
      transition: box-shadow .25s;
      transition: box-shadow .25s, -webkit-box-shadow .25s;
      border-radius: 2px;
      width: 250px;
      left: 50%;
      margin-left: -100px;
      padding: 6px 8px 8px;
      box-sizing: border-box;
      text-align: center;
      color: #ffffff;
      font-size: 24px;
      z-index:99;
    }
      
    .confirm .message {
      text-align: left;
    }
  </style>
  </head>
  <body>
    <div id="cfrmBox" class="confirmBox">
      <div id="cfrmBoxMsg" class="message"></div>
      <button id="idYesButton" class="btn waves-effect waves-light z-depth-5" value="yes" onclick="confirmYesNo(this.value)">Yes</button>
      <button id="idNoButton" class="btn waves-effect waves-light z-depth-5" value="no" onclick="confirmYesNo(this.value)">No</button>
    </div>
    
    <div id="idContainer" class="container">
      <div class="row">
        <div class="col s12">
          <br><br>
          <div class="card">
            <div class="card-image">
              <span class="card-title">Timer</span>
                <a id="idStopWatchBtn" class="btn-floating halfway-fab waves-effect waves-light teal z-depth-5 tooltipped"
                   data-position="top"
                   data-tooltip="Press to start and stop timer" onclick="startStopTimer()">
                <i id="idStopWatch" class="large material-icons">access_time</i></a>
            </div>
            <div id ="idCardContent" class="card-content" style="color: #4db6ac;
                                                                 font-weight: bold;
                                                                 font-weight: 150%">
              <p id = "idCardContentP">04:10:24</p>
            </div>
          </div> 
          
          <div class="row">
            <div class="col s12">
              <div id="idCardPanel" class="card-panel teal">
                <span id="idCardPanelSpan"class="white-text">Task 1: Do something fun
                </span>
              </div>
            </div>
          </div>
            
          <button class="btn waves-effect waves-light z-depth-5" id="btnNextTask" onclick="myFunction()">Next Task
            <i class="material-icons right">music_note</i>
          </button>
        </div> <!-- END col END -->
      </div> <!-- END row END -->
    </div> <!-- END Container -->
    
    <!-- Compiled and minified JavaScript -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"> </script>
  <script>
  
    function appearNow(tMessage){
      var x = document.getElementById('cfrmBoxMsg');
      x.innerHTML = tMessage;
      var y = document.getElementById('cfrmBox');
      y.style.display = "inline";
    }
    
    function myFunction() {
      var stTime = document.getElementById('idCardContentP').innerHTML;
      if (stTime != "") {
        document.getElementById("idStopWatchBtn").classList.add("disabled");
        document.getElementById("btnNextTask").classList.add("disabled");
        appearNow('Do you want to save your time for this task?')
      } else {
        document.getElementById('idCardPanelSpan').innerHTML = "Task 2: Do something even funner!";
        M.toast({html: 'Since the timer has not started you can freely move to the next task'});
      }
    }
  
    function startStopTimer() {
      M.toast({html: 'Timer is hard coded to be greater than 0 for testing!'});
    }
    
    function confirmYesNo(btnValue){
      switch (btnValue) {
        case "yes":
          document.getElementById('idCardContentP').innerHTML = '';
          showHideElements('cfrmBox');
          M.toast({html: 'You clicked yes.'});
          //Since timer is blank it will hit code to move to next task
          myFunction();
          break;
        case "no":
          showHideElements('cfrmBox');
          M.toast({html: 'You clicked no so nothing happens'});
          break;
        default:
          M.toast({html: 'Oops this should not happen'});
      } 
      document.getElementById("idStopWatchBtn").classList.remove("disabled");
      document.getElementById("btnNextTask").classList.remove("disabled");
    }
    
    function showHideElements(showHideWhat) {
      //Be careful with this function if you start with display block versus inline
      var x = document.getElementById(showHideWhat);
      if (x.style.display !== "none") {
        x.style.display = "none";
      } else {
        x.style.display = "inline";
      }
    }
  </script>
  </body>
</html>


推荐阅读