简体   繁体   中英

Changing text after an input field

How do I change the "2 Year Subscription" to "2 year:" without losing the input field

<div class="radioOption subscription1Col3">
<input class="buyNow" type="radio" name="product2" value="6_0" checked="">2 Year Subscription</div>

This is relatively simple, and I'd suggest the following (though currently untested):

var input = $('.radioOption.subscription1Col3 input'),
    text = input[0].nextSibling.nodeValue,
    newText = text.replace(/ subscription/i,': ');
input[0].nextSibling.nodeValue = newText;

JS Fiddle demo .

Or possibly this version might be preferred, since it leaves the adjusted text wrapped in a label element, which aids UI and makes it easier to target that text content in future:

var input = $('#inputID'),
    label = $('<label />',{'for' : 'inputID'})
    .text(input[0].nextSibling.nodeValue.replace(/ Subscription/i,': '));
input.parent().empty().append(input, label);

JS Fiddle demo .

This does, though, require the input to have an id attribute so that the label is semantically attached to that input .

另一种方法是更改textContent

$('.buyNow')[0].nextSibling.textContent = "New Content"

jQuery doesn't support accessing text nodes, only elements, so you would need to use the DOM methods in Javascript to access the text node:

var nodes = $('.radioOption')[0].childNodes;
nodes[nodes.length-1].nodeValue= '2 Year';

Demo: http://jsfiddle.net/Guffa/PDqQW/

If you put an element around the text:

<div class="radioOption subscription1Col3">
  <input class="buyNow" type="radio" name="product2" value="6_0" checked="">
  <span>2 Year Subscription</span>
</div>

Then you can use just jQuery to access it:

$('.radioOption span').text('2 Year');

Demo: http://jsfiddle.net/Guffa/tRdYa/

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