0

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!

1
  • The desired end result HTML (IDs now have the values that data-name had before) and your description "I want to save all the names (and corresponding name number) into variables" have nothing to do with each other. Commented Jan 12, 2016 at 9:19

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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)?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.