MrMangado
MrMangado

Reputation: 993

Trouble creating elements with JQuery

I have this form:

<form>
  <input id="checkuser" type="text" name="user" placeholder="Your username"/>
</form>

And what I'm doing with JQuery is to check if the username that was written is avalible. This is the JQuery code:

 $('#checkuser').click(function (){

     $(this).change(function () {
     $.ajax( {
       url: '/check',
       type: 'POST',
       cache: false,
       data: { checkuser: $(this).val() },
       dataType: "json",
       complete: function() {

    },

    success: function(data) {

        var check = JSON.stringify(data.aval);

        if (check == "false") {

            $('<p>Not available.</p>').insertAfter('#checkuser');

        }

        else {

              $('<p> Available!</p>').insertAfter('#checkuser');

        }

    },
    error: function() {

       console.log('process error');

    }
   });   
  }); 
 });

The problem is: if the user is not available, the user has to rewrite the username and when jQuery recheck if is available, instead of rewrite the content of <p>, JQuery create another <p>next to the old <p>, ergo, this is the result: Not available.Available!, instead write only one of them. How can I resolve this?

Upvotes: 1

Views: 86

Answers (3)

AgnosticDev
AgnosticDev

Reputation: 1853

To solve this I would add a blank <p></p> tag after the input and update this tag when needed.

     <form>
       <input id="checkuser" type="text" name="user" placeholder="Your username"/>
       <p></p>
     </form>
     $('form p').text('Available!');

Upvotes: 2

Richard A.
Richard A.

Reputation: 1157

The insertAfter() method is working as designed: it finds the element (#checkuser in this case) and appends a new paragraph after it.

You probably need to create a DIV or SPAN element after your INPUT tag like this:

<span id="checkuser-validation"></span>

Then adapt your JavaScript code to look like this:

if (check == "false") {

        $('#checkuser-validation').Empty();
        $('#checkuser-validation').Html('Not Available');

}

... and so on. Hope that helps :)

Upvotes: 1

Sagiv Ofek
Sagiv Ofek

Reputation: 25270

insertAfter will append new html context to the div. instead create another div after the checkuser div and replace the html inside:

<input id="checkuser" type="text" name="user" placeholder="Your username"/>
<div id="msg"></div>

and then just:

$('#msg').text('your text if available or not here');

Upvotes: 2

Related Questions