Pavel_K
Pavel_K

Reputation: 21

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

Upvotes: 0

Views: 49

Answers (4)

Shashank Agrawal
Shashank Agrawal

Reputation: 25797

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

Upvotes: 0

messerbill
messerbill

Reputation: 5629

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

Upvotes: 1

Adaleni
Adaleni

Reputation: 976

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

Upvotes: 0

Jalay Oza
Jalay Oza

Reputation: 772

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

Upvotes: 0

Related Questions