简体   繁体   中英

Generated input element with jquery and for function

This code to generate input element with jquery and the amount of element is calculated from times of two other input

$('#generate').click(function () {
var a = parseInt($('#row').val());
var b = parseInt($('#col').val());
var val = a*b;

var innerhtml = '';
for (var i = 0; i < val; i++) {
    innerhtml += "<input type='text' class='seat' id='" + (i + 1) + "' name='" + (i + 1) + "'>";
        for (var j = 0; j = a; j++) {
            innerhtml += "xxx";
        }
}
$('#textbox_div').html(innerhtml);
});

If i fill input #row and #col with 2 & 3, jquery will generated 6 element (2*3 = 6). The output will be like this:

  • Input 1
  • Input 2
  • Input 3
  • Input 4
  • Input 5
  • Input 6

From the code above how to get output like this (Add xxx every after 2 row):

  • Input 1
  • Input 2
  • xxx
  • Input 3
  • Input 4
  • xxx
  • Input 5
  • Input 6

Like this:

var a = 4; //parseInt($('#row').val());
var b = 2; //parseInt($('#col').val());
var val = a*b;

var innerhtml = '';
for (var i = 0; i < val; i++) {
    innerhtml += "<input type='text' class='seat' id='" + (i + 1) + "' name='" + (i + 1) + "'>";
    if (i < val - 1 && i % 2 === 1 ) {
        innerhtml += "xxx";
    }
}
$('#textbox_div').html(innerhtml);

As you can see I replaced your inner for loop to an if statement. It tests two things:

  1. Don't put "xxx" to the end
  2. The remainder of i/2 is 1

Demo jsfiddle HERE . Demo with variable xxx step size HERE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM