Jquery: Madness

Hi all.

I have the following click event in JQuery and wish to duplicate it 6 times.

if($(‘#booking_customer_date_of_birth_1_display’).length > 0)
{
$(‘#booking_customer_date_of_birth_1_display’).click(function()
{
$(this).hide();
$(‘#booking_customer_date_of_birth_1_editable’).show();
});
}

Replacing the number part with the number of each loop iteration i.e. booking_customer_date_of_birth_1_display becomes booking_customer_date_of_birth_2_display etc…

However have tried putting this in a for-loop but it does not work.

for($i = 2; i <= 6; i++)
{
if($(‘#booking_customer_date_of_birth_’ + i + ‘display’).length > 0)
{
$('#booking_customer_date_of_birth
’ + i + ‘display’).click(function()
{
$(this).hide();
$('#booking_customer_date_of_birth
’ + i + ‘_editable’).show();
});
}
}

Can anyone suggest how this can be done in JQuery.

Thanks.
Phil.

Your loop assigns a variable called $i, but I think you intended to use it as i

Replace:


for($i = 2; i <= 6; i++)

With:


for(var i = 2; i <= 6; i++)

I’m also not sure why you are starting at 2.

One possible way is to search for all elements that start with the same identifier.
Something like this should do.


function attachShowEvent(el) {
    if ($(el).length > 0) {
        $(el).click(function () {
            var editable = el.id.replace('display', 'editable');
            $('#' + editable).show();
            $(this).hide();
        });
    }
}

$('[id^="booking_customer_date_of_birth_"]').each(function () {
    if (this.id.substr(-7) === 'display') {
        attachShowEvent(this);
    }
});

When the function being passed to clicked is called i will be 6. In order to have the correct vale requires a closure with self invocation and a binding the state of i. This has nothing to do with jQuery but JavaScript 101. That is why you should learn JavaScript before jQuery…


for($i = 2; i <= 6; i++) {
	if($('#booking_customer_date_of_birth_' + i + '_display').length > 0) {
		$('#booking_customer_date_of_birth_' + i + '_display').click((function(item) {
			return funtion() {
				$(this).hide();
				$('#booking_customer_date_of_birth_' + item + '_editable').show();
			};
		})(i));
	}
}