Dan382
Dan382

Reputation: 986

Add text to form label in jQuery

I'm trying to add text to a form input on load.

For instance I want to add "(Required)" after "Last Name" in this example:

<div class="agile-group required-control">
  <label class="agile-label" for="last-name">Last Name</label>

My attempts are overriding the entire label:

$('.agile-group label').text('test');

I'm assuming I need to first capture the existing value and then add to it but no idea how, I'd guess something like this?

var text = $( this ).text();
$('.form-view label').val( text + "test");

Upvotes: 1

Views: 17086

Answers (1)

Andy
Andy

Reputation: 30135

Yes, you could add it to text(). Or use .append()

$(function() {
  $('.agile-group label').append(' (Required)');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="agile-group required-control">
  <label class="agile-label" for="last-name">Last Name</label><br/>
  <label class="agile-label" for="last-name">Last Name</label><br/>
  <label class="agile-label" for="last-name">Last Name</label>
</div>

Upvotes: 7

Related Questions