Stanley Tan
Stanley Tan

Reputation: 433

The show/hide function is not working with the clone function

I have a problem triggering the show() and hide () function in jQuery when I use it together with the .clone() function.

There isn't any problem showing or hiding the first id but when it comes to a cloned id, showing or hiding doesn't work on it.

Here's a sample js of it:

var $country = $('#country')
    $('#add-countries').on('click', function () {
    $(this).before($country.clone());
});

$('#morelocal').on('click', function () {
    $('#showzipcode').toggle();
    $('#morelocal').hide();
});

$('#hidezipcode').on('click', function () {
    $('#morelocal').show();
    $('#showzipcode').hide();
});

Full jsfiddle here: http://jsfiddle.net/stan255/Wh274/7/

Upvotes: 0

Views: 69

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388326

Since you are cloning the elements

  • It is better to use classes instead of ids because id of an element must be unique
  • And need to use event delegation to support dynamically added elements

so

<div>
    <!-- use class instead of id -->
    <a href="#" class='morelocal'>
        Track ZIP/Postal code
    </a>
    <!-- use class instead of id -->
    <span class='showzipcode'>
        <input type="text" placeholder="e.g: 30196"/>
        <a href="#" class='hidezipcode'>cancel</a>
    </span>
</div>

then

var $country = $('#country')
$('#add-countries').on('click', function () {
    var $clone = $country.clone().removeAttr('id');
    $(this).before($clone);
    $clone.find('.morelocal').show();
    $clone.find('.showzipcode').hide();
});
//use event delegation
$(document).on('click', '.morelocal', function () {
    var $div = $(this).closest('div');
    $div.find('.showzipcode').show();
    $div.find('.morelocal').hide();
});

$(document).on('click', '.hidezipcode', function () {
    var $div = $(this).closest('div');
    $div.find('.morelocal').show();
    $div.find('.showzipcode').hide();
});

Demo: Fiddle, Fiddle2

Upvotes: 1

Related Questions