Stephan-v
Stephan-v

Reputation: 20299

Append to a class attribute with jquery

I'm working on a multistep form with jquery and I'm trying to add classes to keep count of the formsteps that I have. Currently my Jquery is adding step-0, step-1 etc. classes to every .step class.

But I want to append the i counter to the .step class that is already there having a single attribute instead of adding an entire class atttribute and having 2 attributes. Although it must be simple I can't really find how to do this cleanly.

HTML:

<!--multistep form-->
<form id="multistepform" method="post">
    <div class="step">
        First name: <input type="text" name="firstname"><br>
        Last name: <input type="text" name="lastname">
    </div>

    <div class="step">
        First name: <input type="text" name="firstname"><br>
        Last name: <input type="text" name="lastname">
    </div>

    <div class="actions">
        <input type="submit" value="submit data">
    </div>
</form>

Jquery:

$(document).ready( function() {
    var steps = $("#multistepform .step");

    var count = steps.length;

    steps.each(function(i) {
        $(this).addClass("step-" + i);
    })

});

Upvotes: 0

Views: 3129

Answers (2)

Quentin
Quentin

Reputation: 943193

jQuery doesn't provide a UI to modify the name of a class.

Add a new one and remove the old one instead.

steps.each(function(i) {
    var el = $(this);
    el.addClass("step-" + i);
    el.removeClass("step");
})

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

You can't modify a class, but instead remove .step and add .step-<i> class

steps.each(function(i) {
    $(this).removeClass('step').addClass("step-" + i);
})

Upvotes: 2

Related Questions