简体   繁体   中英

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?

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!');

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');

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 :)

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