razzezz
razzezz

Reputation: 21

jQuery addClass and removeClass onchange issue

I'm trying to get jQuery's addClass and removeClass to work in a form select environment with little success.

I want to modify the parent div's class and was trying to pass the ID in the function but all my attempts have been futile. Any direction and assistance would be much appreciated.

<div id="MaxAge" class="SearchFormStyle">
                <select name="maxage" onchange="addClass(MaxAge);">
                    <option value="0">Age</option>
                    <option value="1" >1 Year Old</option>
                    <option value="2" >2 Years Old</option>
                </select>
                    <span class="ThisValue">
                        <a href="#" onclick="RemoveClass(MaxAge)">VALUE ENTERED HERE</a>
                    </span>
                </div>

<script>
    function addClass (id) { 
        div = "#" + id; 
        $(div).addClass("InputSet"); 
    }
    function RemoveClass (id) { 
        div = "#" + id; 
        $(div).removeClass("InputSet"); 
    }
</script>

Upvotes: 2

Views: 9498

Answers (3)

Felix Kling
Felix Kling

Reputation: 816940

addClass(MaxAge) will pass the value of the variable MaxAge to addClass, not the string 'MaxAge'.

Besides, you really should use jQuery to bind event handlers instead of inline event handlers:

$("select[name='maxage']").change(function() {
    addClass('MaxAge');
});

$('.ThisValue a').click(function(event) {
    RemoveClass('MaxAge');
    event.preventDefault();
});

To learn more about event handlers, I recommend to read the articles at quirksmode.org.


There are also other problems, like the div variable in addClass and RemoveClass being global. Don't forget var when you are declaring variables. Also the naming of the function is inconsistent add vs Remove.

The MDN JavaScript Guide is very good for learning the JavaScript basics.

Upvotes: 3

Andreas Eriksson
Andreas Eriksson

Reputation: 9027

You're never instantiating the div variable.

Try this:

var div = "#" + id; 

Upvotes: 0

Manuel van Rijn
Manuel van Rijn

Reputation: 10315

you're almost doing it the right way. Here's what I would do (with some comments for you)

// onchange event of the selectbox with id = maxage
$("#maxage").change(function() {
    $("#MaxAge").addClass("InputSet");
});

// the click event for the a element within span with class ThisValue
$("span.ThisValue a").click(function(e) {
    // prevent doing default behaviour like going to another location...
    e.preventDefault();
    $("#MaxAge").removeClass("InputSet");
});

Upvotes: 0

Related Questions