简体   繁体   中英

Unable to execute scripts depending on Thymeleaf variables <script th:inline=“javascript”>

I have 2 simple scripts and 2 Thymeleaf variables, I want one script to be executed if thymeleaf variable is true, then again if other variable is true - related script to be executed and so on. But I get the following result - if one variable is true and script executed then second script won't be execudet even if second variable is true. So shortly, only one of scripts is executed, but need both (in sequence, not the same time). Here is the code:

    <script th:inline="javascript">
    var flag = [[${invalidInput}]]; //Thymleaf variable
    window.onload = function() {
        if(!flag)
            return; 
        openForm(); 
    };
</script>

<script th:inline="javascript">
    var flag = [[${exists}]];
    window.onload = function() {
        if(!flag)
            return;
        openForm();
    };
</script>



<!-- MODAL -->
<div class="form-popup" id="myForm">
    <form id="registration" th:action="@{/registrate}" th:object="${newUser}" method="post" class="form-container">
        <h1>Registration</h1>

        <div class="alert" th:if="${exists}">
            User already exists! Please try again.
        </div>

        <div class="invalidInput" th:if="${invalidInput}">
            Username or password too short.
        </div>
************************************************************
<script>
    function openForm() {
        document.getElementById("myForm").style.display = "block";
    }
@PostMapping("/registrate")
    public String login (@ModelAttribute(value = "newUser") User newUser, BindingResult bindingResult, Model model) {
        userValidator.validate(newUser, bindingResult);

         if(usrService.isUserPresent(newUser.getUsername())){
            model.addAttribute("exists",true);
            return "login";
        }
         else if(bindingResult.hasErrors()){
             model.addAttribute("invalidInput",true);
            return "login";
        }

I don't think you can set the window.onload variable twice... one will simply overwrite the other. You can either combine your logic like this:

<script th:inline="javascript">
  var invalidInput = [[${invalidInput}]]; //Thymleaf variable
  var exists = [[${exists}]];

  window.onload = function() {
    if(invalidInput) {
      openForm(); 
    } else if (exists) {
      openForm();
    }
  };
</script>

Or alternatively you could use something like jQuery, which has this functionality built in for you.

https://api.jquery.com/ready/

When multiple functions are added via successive calls to this method, they run when the DOM is ready in the order in which they are added.

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