Reputation: 5943
Problem:
Adding a CSS class to an input field once a jQuery script has been completed. The script is a dice function that will randomly generate 1 to 6 upon clicking on it. The number will be stored in a variable called result. I want to check the number in result and add a class to the input field that has that number in the value attribute.
JS code:
<script type="text/javascript">
$(document).ready(function()
{
$('.dice').on('click','li',function(){
$('.cube').attr('class','cube '+$(this).attr('data-opt'))
}).on('click','.select',function(){
$('.dice').toggleClass($(this).attr('data-opt'))
}).on('click','#spin',function(){
var result = Math.round(Math.random()*5 + 1)
, angle = {}
$(this).data('n',$(this).data('n')?0:5);
var n = $(this).data('n');
$('.cube').attr('style','');
angle = {x:360*n,y:360*n}
switch (result){
case 1:
break;
case 2:
angle.y = 360*n + 90;
break;
case 3:
angle.x = 360*n - 90;
break;
case 4:
angle.x = 360*n + 90;
break;
case 5:
angle.y = 360*n - 90;
break;
case 6:
angle.x = 360*n + 180;
break;
}
$('.cube').css({'-webkit-transform':'translateZ(-100px) rotateX(' + angle.x + 'deg) rotateY(' + angle.y + 'deg)','-webkit-transition':'3s'})
$.ajax ({
url: 'savedice.php',
data: {"diceId": result},
type: 'post',
success: function(data) {
//Success
}
});
})
});
</script>
HTML code:
<input class="number" name="alternative[]" type="text" value="1">
<input class="number" name="alternative[]" type="text" value="2">
<input class="number" name="alternative[]" type="text" value="3">
<input class="number" name="alternative[]" type="text" value="4">
<input class="number" name="alternative[]" type="text" value="5">
<input class="number" name="alternative[]" type="text" value="6">
I have looked at and tried to use addClass() but I haven't been able to figure out how I check first the variable result against the different input field.
If the variable result has number 4 then I want to add a CSS class to input field that has value 4. Not requesting a solution, but appreciate rather guidance in this issue.
Upvotes: 0
Views: 58
Reputation: 62498
Assuming that you have the value of the input fields in result
, as you are saying in the question
try like this:
$('input.number[value="'+result+'"]').addClass("MyClass");
Upvotes: 1
Reputation: 44740
Like this -
if(result == 4){
$('.number').filter(function(){return this.value === result;}).addClass('someClass');
}
Upvotes: 1
Reputation: 82251
try this:
if(result == 4){
$('input[value="4"]').addClass('someclass');
}
Upvotes: 1