Call a function in a if statement (banging my head)

I’ve been googling and googling and googling…*it all makes sense but none of it works. All I need to do is to be able to call a function from within an if statement that is in a click function.

Here’s the setup


	$('#new_task_button').click(function() {
		if ($('#project_start_date').val() === "" && $('#project_due_date').val() === "") {
			$('body').append('<div id="notice"><a href="#" class="close_notice recessed_button"><img src="/images/trans_x.png" /></a><h2>Form Error</h2><div class="content"><p>Please provide a project start and end date first.</p></div></div>');
		} else {
			//this is where i would want the duplicateField() to fire for the #new_task_button
		}
		return false;
	});


This was/is working just fine before like so


	$('#new_task_button').click(duplicateField);

I feel like I should be able to do something close to “$(this).duplicateField();” but my function isn’t setup to extend jquery so I know that’s not the answer.

Any help is appreciated. Thanks.

Could you post the code for the duplicateField function?

$('#new_task_button').click(function() {
        if ($('#project_start_date').val() === "" && $('#project_due_date').val() === "") {
            $('body').append('<div id="notice"><a href="#" class="close_notice recessed_button"><img src="/images/trans_x.png" /></a><h2>Form Error</h2><div class="content"><p>Please provide a project start and end date first.</p></div></div>');
        } else {
            duplicateField.call(this); // alternative 1
            duplicateField(this); // alternative 2
        }
        return false;
    });

By using call, you make sure this is preserved. Now you can do this:

function duplicateField(field) {
  var new_task_button = $(this); // alternative 1
  var new_task_button = $(field); // alternative 2
}

O…M…G… Thanks SO much, Raffles.

apparently .call() is what I was searching for (but didn’t know it). And oddly enough it was on the ‘5 ways to call a function’ page I was reading. Apparently I didn’t know what I was looking at.

Since Scallio asked and in case anyone else searching has the same issue, here’s my duplicate function


	function duplicateField() {
		var assoc   = $(this).attr('data-association');
    	var content = $('#' + assoc + '_fields_template').html();
    	var regexp  = new RegExp('new_' + assoc, 'g');
		var new_id = $(this).closest('div.listing_box').find('div.form_row').length

    	$(this).closest('div.listing_box').find('fieldset').append(content.replace(regexp, new_id));
    	return false;
	}


Once again…*THANK YOU for the help!