How to change named class in javascript on button click?
I have a div that
<div class="add1"></div> I want add1 to become add + thenumber of an example length:
var n= $('.add1').length + 1; $('.add1').click(function(){ so what i did
$('.add+n').click(function(){ but it does not work, please help me :(
You can save the number in the data attribute and increase it each time you click. Change the class attribute from the data attribute value.
HTML
<div id="myDiv" data-num='1' class="add1">click me</div> Js
document.getElementById('myDiv').addEventListener('click', function(){ var num = Number(this.getAttribute('data-num')); num++; this.setAttribute('data-num', num) this.setAttribute('class', 'add' + num); }); try it
$('.add'+n).click(function(){ }); n must be out of quotation marks, otherwise it will interpret it as a string. For example:
$('.add' + n).click(function(){ At first, I read your question incorrectly, and I thought that you want to change the div class accordingly. What could you do like this:
var n = 1; var n= $('.add'+1).length + 1; $('.add' + n).click(function(){ $(this).attr('class', 'add' + n); //for if you also want to change the class of the div }); Here it is! try it. I am following you.
<input type="text" style="display:none;" name="qty" value="0" />
<p id="inc" class="">It class will be Increased[concate with number]</p>
<input type="button" id="btn" name="btn" value="increase"/> Now follow the Main script that will help you.
var incrementVar = 0; $(function() { $("#btn").click(function() { var value = parseInt($(":text[name='qty']").val()) + 1; $(":text[name='qty']").val(value); $('#inc').removeClass('a' + (value-1)); $('#inc').addClass('a' + value); // I believe class names cannot start with a number incrementVar = incrementVar + value; }); });
var incrementVar = 0; $(function() { $("#btn").click(function() { var value = parseInt($(":text[name='qty']").val()) + 1; $(":text[name='qty']").val(value); $('#inc').removeClass('a' + (value-1)); $('#inc').addClass('a' + value); // I believe class names cannot start with a number incrementVar = incrementVar + value; }); }); I posted this code also at www.codedownload.in
Thanks.
Use . addClass () to add and . removeClass () to remove classes
$('.add1').click(function(){ var n= $('.add1').length + 1; //reads n $(".add1").addClass("add"+n); //adds new class $(".add"+n).removeClass("add1"); //removes existing class }); Here is an example: https://jsfiddle.net/danimvijay/ssfucy6q/
If you want to select a class with a variable combination, use $('.add'+n) instead of $('.add+n') .
$('.add'+n).click(function(){ //place code here }); Here is an example: http://jsfiddle.net/danimvijay/a0j4Latq/