I am trying to copy a value of one span to another where the value of the first span is a number. There are multiple class string divs, i want the span value from the first one in each case.
This is my HTML structure that I have to work with
<button id="btn">Press it</button>
<div class="object">
<div class="header">
<span class="name">0</span>
</div>
<div class="children">
<div class="string">
<div class="header">
<span class="name">Cheese</span>
</div>
</div>
<div class="string"></div>
<div class="string"></div>
<div class="string"></div>
<div class="string"></div>
</div>
</div>
<div class="object">
<div class="header">
<span class="name">Biscuits</span>
</div>
<div class="children">
<div class="string">
<div class="header">
<span class="name">Cheese</span>
</div>
</div>
<div class="string"></div>
<div class="string"></div>
<div class="string"></div>
<div class="string"></div>
</div>
</div>
<div class="object">
<div class="header">
<span class="name">0</span>
</div>
<div class="children">
<div class="string">
<div class="header">
<span class="name">Cheese</span>
</div>
</div>
<div class="string"></div>
<div class="string"></div>
<div class="string"></div>
<div class="string"></div>
</div>
</div>
This is my code that I have so far, and its not working. Not sure where to go next.
jQuery(function ($) {
$('#btn').click(function () {
if ( $.isNumeric($('div object div.header span.name').text()) ) {
$('div.object div.children div.string div.header span.name').html($('div.object div.header span.name').html());;
}
});
});
You can use callback function .text()
to return the text value based on condition:
$('#btn').click(function () {
$('.object > .header .name').text(function(i,o){
if($.isNumeric(o)){
return $(this).parent().next().find('.header .name').text();
}
})
});
I would do something like this:
var text_from_span = $('.object .header span.name').text();
if ($.isNumeric(text_from_span)){
var spans_to_fill = document.getElementsByClassName('string');
for(var i = (spans_to_fill.length - 1); i >= 0; i--){
spans_to_fill[i].innerHTML = text_from_span;
}
}
It would be much easier if you could give an id
to <span>
. Then you could read the value as
var txt = $('#idofspan').text();
and set as
$('#otherspan').val(txt);
JS Fiddle: https://jsfiddle.net/Lwwy8909/
Goes a little like this:
With the use of an each loop and match to extract a number with any length of digit from the text.
jQuery(function ($) {
$('#btn').click(function () {
$('.object').each(function() {
if ( $.isNumeric($(this).find('.name:first').text().match(/\d+/)) ) {
$(this).find('div.children').find('span.name').text($(this).find('.name:first').text().match(/\d+/));
}
});
});
});
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.