David__
David__

Reputation: 375

Modifying all element in a class with js

I am trying to hide/show a class of elements in a form depending on a drop-down menu choice made by the user. See: http://jsfiddle.net/3FmHK/2/

I am new to js and have two problems, so maybe they are obvious, bear with me.

1) I am modifying by the div id, so only the first element changes (and not in this fiddle for some reason, but it does in the project). However I want all the elements of a class to modify and I haven't been able to make that work. So how do I modify the style="display" for an entire class, rather than a single element?

2) The remove does not work for newly added element, when the form is returned with values in the project, they are removable. Using firebug, the code looks identical for the GET return generated elements vs the user added elements, as far as I can tell. Why does the remove function not work for newly added elements?

Upvotes: 0

Views: 101

Answers (2)

Maresh
Maresh

Reputation: 4712

Try:

$(this).parent('div').first().remove();

Upvotes: 0

geilt
geilt

Reputation: 805

I recommend using jQuery for this if you can. You can use the .on() feature to bind actions ot newly created elements and use the class selector to .hide() all classes then .show() the currently selected on by id.

It would look something like this:

jQuery(document).ready( function() {
    jQuery(document).on('click', '.classname', function() {
        jQuery('.' + jQuery(this).attr('class') ).hide();
        jQuery(this).show();
        // Or you can use the following to show a specific ID element.
        //jQuery('#idtoshow').show();
    )};
});

This will hide all elements with the class name. You will need to include the jQuery library before your script. Although I am only using show and hide here, you can use .remove() as long as you bind your action with .on and not just .click. You need .on to bind to newly created elements.

http://api.jquery.com/on/

Hope this helps.

Upvotes: 2

Related Questions