Null
Null

Reputation: 73

Adding and Removing Div inside a Bootstrap modal

I'm trying to show an alert on my modal (from bootstrap) about the account entered by the user (e.g Invalid Account).

However, (for example, I entered a wrong account) after getting an error response and prepend it and then enter a wrong account again, it won't remove the previous alert i prepend.

Here's what's happening:
Prepends alert every time i click the button

Here's my HTML Code:

<div class="modal-body modal-login">
  <?php include( 'login.php'); ?>
  <form name="test" action="" method="post" role="form" id="loginForm">
    <input type="text" class="form-control userTB" name="loginText" placeholder="Username/Email" required>
    <input type="password" class="form-control passTB" name="passText" placeholder="Password" required>
    <a href="javascript:void(0)" class="btn btn-info btn-md" id="submit_button">Login</a>
  </form>
</div>

My jQuery:

jQuery(function ($){
    $('#submit_button').click(function(){
        var post_url = 'login.php';

        $.ajax({
            type : 'POST',
            url : post_url,
            data: $('#loginForm').serialize(),
            dataType : 'html',
            async: true,
            success : function(data){
            	$('.modal-login').remove('.alert');
                $('.modal-login').prepend(data);
            }
        });
    })           
});

Note: That data from jQuery contains <div class="alert alert-danger">Wrong Account!</div>.

Upvotes: 1

Views: 1606

Answers (1)

Stryner
Stryner

Reputation: 7318

$(el).remove(selector) is somewhat confusing. It basically means "remove el from the document if it matches selector". This makes more sense if your jQuery object has multiple elements and you're filtering which ones to remove.

If you change your code to .remove('.modal-login'), you'll see that it removes the whole modal.

You should use .find then .remove:

$('.modal-login').find(".alert").remove();
$('.modal-login').prepend(data);

Upvotes: 2

Related Questions