Adam
Adam

Reputation: 1975

Remove a dynamic element with jQuery

I am trying to remove a dynamically created element using jQuery.

Here is my example: http://jsfiddle.net/4uxbu/

When you click submit it highlights the required fields and displays the text This field is required. after the input. When the user clicks on the input the red box goes away, I want the text below the input to go away as well.

The message is set using the following code:

$('#' + required[i]).after('<p style="font-weight:bold;" id="' + required[i] + '_error">' + emptyerror + '</p>');

and I've tried to remove it with:

$('p#' + required[i] + '_error').remove();

But I can't get it to work properly.

Required is as below

required = ["vidHeight", "title", "vidWidth", "vidLen", "thumb", "file"];

Please see the fiddle for the full code.

Thanks

Upvotes: 0

Views: 271

Answers (3)

PCasagrande
PCasagrande

Reputation: 5402

I would not store the names, but rather an array of the error messages. If you kept an array of actual items being added then you would reduce the number of DOM queries and have an easy way to address them. You could even create an object that associates the controls with the messages.

Upvotes: 0

aquinas
aquinas

Reputation: 23796

$('p#' + required[i] + '_error').remove();

Well, required[i] doesn't make any sense because you aren't in a loop where i is defined anymore. Try this:

$('#' + $(this).attr("id") + '_error').remove();

See: http://jsfiddle.net/4uxbu/1/

EDIT

Updated to handle the case of showing multiple errors when submitting multiple times with errors: http://jsfiddle.net/4uxbu/2/

Upvotes: 3

travis
travis

Reputation: 51

The [i] will have no affect while not in the for loop, so I would suggest changing the following:

$(this).removeClass("needsfilled");
$('#' + required[i] + '_error').remove();

To something more like:

$(this).removeClass("needsfilled").next('#'+$(this).attr('id')+'_error').remove();

Upvotes: 0

Related Questions