Reputation: 125
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
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
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
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