dadde
dadde

Reputation: 659

Add HTML after an input element with jQuery

I'm trying to add some HTML after an input field using jQuery but it's not working and I don't understand why.

<input type="text" value="secret password" maxlength="255" id="ripo" title="Password" class="ms-long ms-spellcheck-true">
$(document).ready(function() {
  jQuery("input[title='Password']").append('<P>test</P>');
});

Upvotes: 1

Views: 4497

Answers (3)

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48367

You have to use .after() method.

append method insert content to the end of each element in the set of matched elements.

after method insert content after each element in the set of matched elements.

$(document).ready(function() {
  jQuery("input[title='Password']").after('<p>test</p>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="secret password" maxlength="255" id="ripo" title="Password" class="ms-long ms-spellcheck-true">

Also, you can use insertAfter method in the following way.

$(document).ready(function() {
      $('<p>test</p>').insertAfter($("input[title='Password']"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="secret password" maxlength="255" id="ripo" title="Password" class="ms-long ms-spellcheck-true">

Upvotes: 3

Andrew Monks
Andrew Monks

Reputation: 666

You cannot append HTML to an input. But you can do this (if you wanted to actually set the value):

$(document).ready(function() {
  jQuery("input[title='Password']").val('test');
});

Although this does not answer the edited question, other answers address appending an element after the input.

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337560

append() is used to add content within an element, however form inputs do not contain any content. Normally you'd use val() to set their values.

However to achieve what you require use the after() method instead to insert content in to the DOM after the selected element:

$(function() {
  $("#ripo").after('<P>test</P>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="secret password" maxlength="255" id="ripo" title="Password" class="ms-long ms-spellcheck-true">

Upvotes: 3

Related Questions