简体   繁体   中英

jquery add an element next to an input element

I have this html inputs.

<input type='text' class='req-in' name='fname'>
<input type='text' class='req-in' name='lname'>

I am trying to do to add somr element next to the input field. I tried append() and prepend() but it goes wrong.

this is my code:

$('.req-in').blur(function() {
        $(this).append('<p>some text here for this field only!</p>');   
    });

is this possible? my ideal output would be like this

<input type='text' class='req-in' name='fname'><p>some text here for this field only!</p>
<input type='text' class='req-in' name='lname'>

You need to use .after() method.

Insert content, specified by the parameter, after each element in the set of matched elements.

$('.req-in').blur(function() {
    $(this).after('<p>some text here for this field only!</p>');   
});

or .insertAfter()

Insert every element in the set of matched elements after the target.

$('.req-in').blur(function() {
 $('<p>some text here for this field only!</p>').insertAfter($(this));
});

Try this one

    <!DOCTYPE html>
<html>
<title>Stack HTML</title>
<link rel="stylesheet" href="../repo/css/bootstrap.css" type="text/css" />
<script src="https://code.jquery.com/jquery-2.1.3.js"></script>
<script src="../repo/js/bootstrap.js"></script>
<script src="../repo/js/jquery.validate.js"></script>
<head></head>
<body>

    <input type='text' class='req-in' name='fname'>
    <input type='text' class='req-in' name='lname'>

    <script>
        $(document.body).on('blur', '.req-in' ,function(){
            $(this).after('<p>some text here for this field only!</p>');
        });
    </script>
</body>
</html>

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