Mael
Mael

Reputation: 125

jQuery toggleClass on input values

I want to add a class to an input depending on the value of the text input. My problem is that the input renders all the classes. Here is the html part :

<form name="imcForm" id="imc">
    <p>poids: <input type="text" name="poids" size="10"></p>
    <p>taille: <input type="text" name="taille" size="10"></p>
    <p><input type="button" id="calcul" value="Calculer" onClick="calculImc()"></p>
    <p>result : <input type="text" name="imc" size="10" id="imcResult"></p>
    <p>Interprétation: <input type="text" name="interpretation" size="25" id="interpretation"></p>
</form>

And here is the javascript/jQuery

$('#calcul').on("click", function() {
    $("#interpretation:input[value=itemA]").toggleClass('a');
    $("#interpretation:input[value=itemB]").toggleClass('b');
    $("#interpretation:input[value=itemC]").toggleClass('c');
    $("#interpretation:input[value=itemD]").toggleClass('d');
    $("#interpretation:input[value=itemE]").toggleClass('e');
    $("#interpretation:input[value=itemF]").toggleClass('f');
    $("#interpretation:input[value=itemG]").toggleClass('g');
});

Also, look at what render the input :

<input type="text" id="interpretation" size="25" name="interpretation" class="denutrition normale moderee severe morbide">

So why does each element recieve each class on click?

Upvotes: 1

Views: 1396

Answers (3)

Bui Cuong
Bui Cuong

Reputation: 149

try this:

$('#calcul').on("click", function() {

    var target = $("#interpretation");
    var val =  target.val();
    var className = "";
    if(val == "itemA")                     
    {
        className = "a";
    }
    else if(val == "itemB")                     
    {
        className = "b";
    }
    else if(val == "itemC")                     
    {
        className = "c";
    }
    //............
    target.attr("class", className );
});

Upvotes: 0

tkone
tkone

Reputation: 22728

You're missing a > at the end of your <button> input.

Also you can greatly simplify the code you've got, especially if the class name is always the last letter of what's in the input field.

$('#calcul').on'click', function(){
    var class = $('#interpretation').val().slice(-1).toLowerCase();
    $('#interpretation').toggleClass(class);
});

Upvotes: 1

Steve Wellens
Steve Wellens

Reputation: 20620

It's hard to tell exactly what you are doing.

But the problem may be that you have two click handlers, one from jQuery and one 'hard-coded': onClick="calculImc()"

Upvotes: 0

Related Questions