The initial elements on the page are a container, a form with an input text field and radio button pair, a div that is used as our clone host, and a hidden div that is hidden or revealed by toggling the radio buttons.
The logic simply clones the div block with an id of "host1" and appends it at the end of (but still inside) the div with an id of "container". The number of clones is determined by user input. The logic gets the value of the user input as well as the number of existing divs (initially just 1). Two variables hold the value of the existing divs, and the value of the requested divs, and these are used in a calculation to determine how many divs need to be cloned.
So if I already have 4 clones on the page, and the user submits 5, it will only create one more clone. During the cloning process (which is in a loop) the logic changes the id of the new cloned div, changes the id of the div that is shown or hidden, and also changes the class and names of the radio button sets inside the div.
My problem is the newly named radio buttons are attempting to target the newly named hidden div, but it can't seem to find it. The (currentHosts + a) seems to be the issue, because it is never the right number. Hope this all makes sense. Any help is greatly appreciated.
Cheers!
The HTML:
<body>
<form>
<input type="text" size="1" maxlength="2" name="total_number" class="total_number" />
<div id="container">
<div id="host1" class="hosts">
<div>
<h5>Show or Hide Div</h5>
<input type="radio" name="dhcp_name1" class="dhcp1" value="yes" />
<input type="radio" name="dhcp_name1" class="dhcp1" value="no" />
</div>
<div id="hostSpans1" class="hostSpans" style="display:none;">
<h4>Hello There!</h4>
</div>
</div><!-- close host1 -->
<!-- cloned divs will be appended here -->
</div>
</form>
</body>
The jQuery:
$(document).ready(function(){
$('.total_number').keyup(function(){
var currentHosts = $('#container > div').length;
var numberOfHosts = $('.total_number').val();
alert("Requested number is " + (numberOfHosts));
alert("Existing number is " + (currentHosts));
if(numberOfHosts > currentHosts){
var diff = numberOfHosts - currentHosts
for(a=1;a<=diff;a++){
var newHost=$('#host1').clone().attr('id','host' + (currentHosts + a)).appendTo('#container');
newHost.find('.hostSpans').attr('id', 'hostSpans' + (currentHosts + a));
newHost.find('.dhcp1').each(function(){
$(this).attr('class', 'dhcp' + (currentHosts + a));
$(this).attr('name', 'dhcp_name' + (currentHosts + a));
});
newHost.find('.dhcp' + (currentHosts + a)).bind("click", function(){
if($(this).val() == "yes"){
$('#hostSpans' + (currentHosts + a)).show();
}else{
$('#hostSpans' + (currentHosts + a)).hide();
}
});
}
}
});
$('.dhcp1').click(function(){//this is the logic for the initial dom elements
if($(this).val() == "yes"){
$('#hostSpans1').show();
}else{
$('#hostSpans1').hide();
}
});
});

New Topic/Question
Reply



MultiQuote



|