Steve Kim
Steve Kim

Reputation: 5591

jQuery foreach values in variables

So, I have the following html:

<div class="all_names">
    <span class="name" data-name="1">Steve</span>
    <span class="name" data-name="2">Mike</span>
    <span class="name" data-name="3">Sean</span>
    <span class="name" data-name="4">Emily</span>
</div>
<div class="show_names"></div>

Then for js:

jQuery(document).on( 'click', '.all_names', function(e) {
    var name = jQuery(this).html(); ????    
    var name_number = jQuery(this).data("name");????

    var show_names ='<div class="show" id="'+ name_number + '">'+ name + '<div>';  ????           

    jQuery('.show_names').html(show_names);

}

Then the desired end result should be as following:

<div class="show_names">
    <div class="show" id="1">Steve<div>   
    <div class="show" id="2">Mike<div>   
    <div class="show" id="3">Sean<div>   
    <div class="show" id="4">Emily<div>   
</div>

Here is my question:

When the class all_names is clicked, I want to save all the names (and corresponding name number) into variables.

Then, I want to use these values to load the html portion for individual values as shown in the desired end result.

How do I achieve this? Any help will be much appreciated.

Thanks!

Upvotes: 0

Views: 235

Answers (2)

n-dru
n-dru

Reputation: 9420

You can use this code (building the string of html code out of each span inner texts and its data-name attributes:

jQuery(document).on( 'click', '.all_names', function(e) {
    var string = '';
    jQuery(this).find('span').each(function(){
        string += '<div class="show" id="'+ jQuery(this).attr("data-name") + '">'+ jQuery(this).text() + '</div>';
    });
    jQuery('.show_names').html(string);
});

By the way - beware using integer as the element's id, it is not advised! If you do have to do this, I recommend you to get acquainted with the methods of css selecting those elements by id:

How to select an element that has id starting with a digit (css)?

Upvotes: 0

Nitin Varpe
Nitin Varpe

Reputation: 10694

You can write following code inside click even of div with class all_names. You can use .each to iterate throght all spans with class .name. Then can use append to append html to div with class .show_names.

jQuery( "span.name" ).each(function( index ) {
  var html = '<div class="show" id="'+ jQuery(this).data("name")+ '">'+ jQuery(this).text()+ '</div>';
  $( "div.show_names" ).append(html);
});

FIDDLE

Upvotes: 1

Related Questions