jqueryappendinsertafter

How can I append an alement after another element?


<div>
   <label for="form_username" class="required">Username</label>
   <input type="text" id="form_username" name="form[username]" required="required" class="form-control">
</div>

I try to append an element to the input field with the name "form[username]:

$( "<p>Test</p>" ).insertAfter('input[name=form[username]]');

But it is not working. Nothing happens.

I expect this result:

<div>
   <label for="form_username" class="required">Username</label>
   <input type="text" id="form_username" name="form[username]" required="required" class="form-control">
   <p>Test</p>
</div>

Solution

  • Since your input tag has an id form_username, you don't have to use [name] attribute as a selector anymore.

    $( "<p>" ).text("Test").insertAfter('#form_username');
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <div>
       <label for="form_username" class="required">Username</label>
       <input type="text" id="form_username" name="form[username]" required="required" class="form-control">
    </div>


    Or if you have only 1 input tag, you could try:

    $( "<p>" ).text("Test").insertAfter('input');
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <div>
       <label for="form_username" class="required">Username</label>
       <input type="text" id="form_username" name="form[username]" required="required" class="form-control">
    </div>


    Or if you want to use attribute name, you could rename the value form[username] to form_username, like this:

    $( "<p>" ).text("Test").insertAfter('[name=form_username]');
    $( "<p>" ).text("Test").insertAfter('input[name=form_username]');
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <div>
       <label for="form_username" class="required">Username</label>
       <input type="text" id="form_username" name="form_username" required="required" class="form-control">
    </div>


    If you don't want to rename the name attribute value, you could try:

    $( "<p>" ).text("Test").insertAfter('input[name*="username"]');
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <div>
       <label for="form_username" class="required">Username</label>
       <input type="text" id="form_username" name="form[username]" required="required" class="form-control">
    </div>