简体   繁体   中英

Prevent modal from closing if value contains dot

I have modal with input

  function check(){ if($("#columnName").val().indexOf(".") != -1){ alert("Column name cann't contain commas!"); return false; } } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" id="columnName" class="form-control"> and button <input type="button" id="applyButton" value="Apply" class="btn btn-default" onclick="check();"> 

But even though I return false if the value contains dot, the popup still closes. I want it to stay opened until user deletes dots

your function never returns true , so your check() will always fail.

function check(){
  if($("#columnName").val().indexOf(".") != -1){
    alert("Column name cann't contain commas!");
    return false;
  }
  return true
}

some examples powered by me and @charlietfl

https://jsfiddle.net/xe7uwr87/1/

greetings

Use this example

 $('#ModalId').on('hide.bs.modal', function (e) {
      if($("#columnName").val().indexOf(".") != -1){
        e.preventDefault();
        e.stopPropagation();
        return false;
      }
        return true;
    });

Hope this help

function check(){
   if($("#columnName").val().indexOf(".") != -1){
    alert("Column name cann't contain commas!");
    return false;
   }else {
       $('.modal').modal('hide');
   }
}

There are various ways.

Firstly, to utilize your own example: you should be writing onclick="return check()" instead of onclick="check()" and method should return true in the else part.

Another thing you can do is to listen to 'hide.bs.modal' event and then add this code and then prevent the modal from closing by stopping the event propagation and bubbling as answered by @jalay-oza

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