Zameer Fouzan Zameer Fouzan - 4 months ago 19
Javascript Question

Jquery shift generated button values in circular manner

i am trying to make something fancy like this create button and shift values, so far i have reached till here FIDDLE

$("#submit").click(function() {
var n = $('#txtinp').val();
if ($.isNumeric(n)) {
//alert(n);
var btns = $('#btns');
for (var i = 1; i <= n; i++) {
btns.append('<input type="button" id="b' + i + '" value="' + i + '"/>');
}
} else {
alert("enter a number");
}
$("input[type='button']").click(function(e) {
var idClicked = e.target.id;
//alert($(this).attr("value"));
if (idClicked == 'b1' && $(this).attr("value") == 1) {
$(this).prop('value', n);
var lastBtn = 'b' + n;
for (var i = n; i > 1; i--) {
$('#b' + i).prop('value', i - 1);
}
} else {
var lastBtn = 'b' + n;
for (var i = n; i >= 1; i--) {
if ('b' + i == 'b1' && 'b' + n == n) {
$('#b' + i).prop('value', i);
} else {
$('#b' + i).prop('value', i - 1);
}
}
}
});

});


I am able to shift only once if clicked on very first created button, but the function or event does not work on second and further clicks. I have no prior Jquery experience, what is that i am doing wrong here?

please do not down vote if the question is too stupid.
thanks in advance

Answer

Here's one possible solution:

$(document).ready(function() {
  $("#submit").click(function() {
    var n = $('#txtinp').val();
    if ($.isNumeric(n)) {
      var btns = $('#btns').empty();
      for (var i = 1; i <= n; i++) {
        btns.append($('<button>').text(i));
      }
    } else {
      alert("enter a number");
    }

    $("#btns button").click(function(e) {
      var buttons = $('#btns button');
      buttons.each(function () {
        var currentValue = parseInt($(this).text());
        var newValue = currentValue - 1;
        if (newValue === 0) {
          newValue = buttons.length;
        }
        $(this).text(newValue);
      });
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="txtinp" />
<input type="button" id="submit" value="Submit" />
<div id="btns">

</div>