Generate Twitter-Bootstrap Alert within the script itself by clicking a button

Asked

Viewed 480 times

2

I wonder if it is possible to create and open a Twitter-Bootstrap alert (.Alert) with a custom message within the script itself, without having to create the custom div outside the script and call it? By clicking the "meuInput" button, create and open Alert with a message with the example below:

<input type='text' name='meuInput' id='meuInput'>

<button id='meuBtn' class='btn btn-default'>Continuar</button>

<script>
$(document).ready(function(){

    var meuInput = $("#meuInput").val();

    $("#meuBtn").on('click',function(){

      if(meuInput == "") {
        [ chamar um alerta com a mensagem personalizada dentro do script ]      
      }

    });
});
</script>

1 answer

1

There was a problem with your code that only checked the value of input page loading, but, just put it in the event button to be checked at all times of the click on the button if you have value typed in the input, example:

$(document).ready(function() {
  $("#meuBtn").on('click', function() {
    var meuInput = $("#meuInput").val();
    if (meuInput == "") {
      $(".bs-example-modal-sm").modal('show');
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.js"></script>

<input type='text' name='meuInput' id='meuInput' class="form-control">
<button id='meuBtn' class='btn btn-default'>Continuar</button>

<div class="modal fade bs-example-modal-sm" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel">
  <div class="modal-dialog modal-sm" role="document">
    <div class="modal-content">
      <div class=modal-header> <button type=button class=close data-dismiss=modal aria-label=Close><span aria-hidden=true>&times;</span></button>
        <h4 class=modal-title id="myLargeModalLabel">Alerta</h4>
      </div>
      <div class="modal-body">
        <p>Digite meu Input</p>
      </div>
    </div>
  </div>
</div>

  • Thanks for the tip, it did work, but it’s the use of Alert, not modal, and I would really like the message from Alert, in the case of your example, to be passed straight from a javascript var to div.modal-body.

  • @Eliseub pass what value?

  • In the example I did, the "myInput" input is checked to be empty, so pass value into Alert, for example "The myInput field is empty". I got here how to do, thanks for the help.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.