Reputation: 433
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
Reputation: 388326
Since you are cloning the 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();
});
Upvotes: 1