Nick
Nick

Reputation: 702

How to update Label text that also contains an Input element

I am trying to update just the text within the label, but not touch the input value in any way.

<div id="shippingRates">
    <label>
        <input type="radio" name="shippingrate" class="shippingratequote" value="GUID1" />
        Text I want to Update
    </label>
    <label>
        <input type="radio" name="shippingrate" class="shippingratequote" value="GUID2" />
        Random Text
    </label>
</div>

Playing around in the console, this Javascript returns just the text of the label:

$('#shippingRates :input[value="GUID1"]').parent().text();

But what is happening is if I execute:

$('#shippingRates :input[value="GUID1"]').parent().text("TEXT UPDATED!");

It overwrites the entire contents of the Label element, including the input element.

How am I able to update just the text using jQuery/javascript?

EDIT: FYI, I am unable to make any changes to the HTML as it comes in from an external server-side function.

Thanks

Upvotes: 0

Views: 509

Answers (2)

palawer
palawer

Reputation: 125

Another way to do it...

$('#shippingRates :input[value="GUID1"]').parent().contents().filter(function(){ 
  return this.nodeType == 3; 
})[1].nodeValue = "The text you want to replace with"

Upvotes: 3

Rick Hitchcock
Rick Hitchcock

Reputation: 35680

You can use the DOM to grab the text node following the input:

$('#shippingRates :input[value="GUID1"]')[0].nextSibling.nodeValue= 'TEXT UPDATED!';
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="shippingRates">
    <label>
        <input type="radio" name="shippingrate" class="shippingratequote" value="GUID1" />
        Text I want to Update
    </label>
    <label>
        <input type="radio" name="shippingrate" class="shippingratequote" value="GUID2" />
        Random Text
    </label>
</div>

Upvotes: 3

Related Questions