当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Add alphabets dynamically as html row increments

问题描述:

How to ensure i have a dynamic increment of Alphabets in a new cell on left side, next to each cell in a row which is dynamically created based on the option chosen in Select. This newly generated alphabet will be considered as bullet points/serial number for that particular row's text box.

jsfiddle

js code

$(document).ready(function(){

var select = $("#Number_of_position"), table = $("#Positions_names");

for (var i = 1; i <= 100; i++){

select.append('<option value="'+i+'">'+i+'</option>');

}

select.change(function () {

var rows = '';

for (var i = 0; i < $(this).val(); i++) {

rows += "<tr><td><input type='text'></td></tr>";

}

table.html(rows);

});

});

html

<select id="Number_of_position">

</select> <table id="Positions_names">

</table>

网友答案:

This is essentially a base26 question, you can search for an implementation of this in javascript pretty easily - How to create a function that converts a Number to a Bijective Hexavigesimal?

alpha = "abcdefghijklmnopqrstuvwxyz";

function hex(a) {
  // First figure out how many digits there are.
  a += 1; // This line is funky
  var c = 0;
  var x = 1;      
  while (a >= x) {
    c++;
    a -= x;
    x *= 26;
  }

  // Now you can do normal base conversion.
  var s = "";
  for (var i = 0; i < c; i++) {
    s = alpha.charAt(a % 26) + s;
    a = Math.floor(a/26);
  }

  return s;
}

So you can do

$(document).ready(function(){

var select = $("#Number_of_position"), table = $("#Positions_names"); 
 for (var i = 1; i <= 100; i++){
        select.append('<option value="'+i+'">'+i+'</option>');
    }

    select.change(function () {
        var rows = '';
        for (var i = 0; i < $(this).val(); i++) {
            rows += "<tr><td>" + hex(i) + "</td><td><input type='text'></td></tr>";
        }
        table.html(rows);
    });

}); 

Heres the example http://jsfiddle.net/v2ksyy7L/6/

And if you want it to be uppercase just do

hex(i).toUpperCase();

Also - this will work up to any number of rows that javascript can handle

网友答案:

if i have understood you correctly, that's maybe what you want:

http://jsfiddle.net/v2ksyy7L/3/


I have added an array for the alphabet:

var alphabet = "abcdefghijklmnopqrstuvwxyz".split("");


and then added the output to your "render" loop:

 rows += "<tr><td>" + alphabet[i] + " <input type='text'></td></tr>";
分享给朋友:
您可能感兴趣的文章:
随机阅读: