使用不同的id在循环中创建多个textareas

时间:2017-11-11 14:57:45

标签: javascript jquery unique

我创建了一个eshop的结帐页面,我有一个循环,在其中我显示用户已添加到购物车的产品。在循环内部,我显示产品的信息,我有一个文本区域,以便用户可以选择每个产品的数量。问题是每个文本区域的id必须是唯一的。如何在具有不同ID的循环中创建多个textareas?

textarea:

<form name='txtAreaForm' method='GET'>
  <textarea disabled name='textArea' id='counter'></textarea>
</form>

另外,我有两个按钮(+ - )来改变textarea的值,这是.js文件:

var counter = 1;

// Display total
$("#counter").text(counter);

// When button is clicked
$("#plusButton").click(function(){
    counter = counter + 1;
    $("#counter").text(counter);
});


//Subtract
$("#minusButton").click(function(){
    if (counter>1) {
        counter = counter - 1;
        $("#counter").text(counter);
    }
});

4 个答案:

答案 0 :(得分:1)

虽然我不清楚这个问题,但您可以执行以下操作:

var counter = 1;

// Display total
$("#counter").text(counter);

var counter = counter + 1;
for(var i=0; i<5; i++){
	$("form").append('<textarea name=textArea"+counter+" id=counter"+counter+">1</textarea><input class="plus" type="button" value="+" /><input class="minus" type="button" value="-" /><br>');
}
// When button is clicked
$(".plus").click(function(){
  var txtArea = $(this).prev('textarea').text();
  $(this).prev('textarea').text(parseInt(txtArea)+1);  
});


//Subtract
$(".minus").click(function(){
  var txtArea = $(this).prev().prev('textarea').text();
  if(txtArea >=2){
    $(this).prev().prev('textarea').text(parseInt(txtArea)-1);
	}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name='txtAreaForm' method='GET'>
  
</form>

答案 1 :(得分:0)

您只需使用JavaScript即可根据需要使用id呈现包含尽可能多的textareas的表单,并将操作设置为与每个表单相关的每个按钮。

参见此演示:

(function() {
  // Set the plus action on every button with the class name «plus».
  function setPlusAction() {
    function plus(e) {
      var textarea = e.target.previousSibling; // Find the textarea element related to the button clicked.
      textarea.value = textarea.value * 1; // Convert the value into number.
      textarea.value++; // Increment its value.
    }
    var elems = document.getElementsByClassName("plus"), i, len = elems.length, button;
    for (i = 0; i < len; i++) {
      button = elems[i]; // Find the current button.
      button.onclick = plus; //Set the «plus» function on every button which has been found.
    }
  }

  // Set the minus action on every button with the class name «minus».
  function setMinusAction() {
    function minus(e) {
      var textarea = e.target.previousSibling.previousSibling; // Find the textarea element related to the button clicked.
      textarea.value = textarea.value * 1; // Convert the value into number.
      if (textarea.value > 1) {
        textarea.value--; // Decrement its value.
      }
    }
    var elems = document.getElementsByClassName("minus"), i, len = elems.length, button;
    for (i = 0; i < len; i++) {
      button = elems[i]; // Find the current button.
      button.onclick = minus; //Set the minus function on every button which has been found.
    }
  }
  
  // Render a form with the quantity of textareas required.
  function buildForm(textareas) {
    var html = "<form name=\"txtAreaForm\" method=\"GET\">", i;
    for (i = 0; i < textareas; i++) {
      html += "<div><textarea disabled name=\"textArea\" id=\"textarea";
      html += i;
      html += "\">1</textarea><button class=\"plus\" type=\"button\">+</button><button class=\"minus\" type=\"button\">-</button></div>";
    }
    html += "</form>";
    return html; // Return the html content with the form.
  }
  
  /*
   1. Render the form with document.getElementById("div").innerHTML = buildForm(50);
   2. Once the form is renderd call setPlusAction() function;
   3. And call setMinusAction() function;
   */
  document.getElementById("div").innerHTML = buildForm(50); // Set 50 textareas.
  setPlusAction();
  setMinusAction();
})();
#div div {
  border: solid 1px #ccc;
  margin: 2px;
  padding: 2px;
}

button.plus,
button.minus {
  cursor: pointer;
}
<div id="div"></div>

<强>更新

jQuery版本:

$(function() {
  // Render a form with the quantity of textareas required.
  function buildForm(textareas) {
    var html = "<form name=\"txtAreaForm\" method=\"GET\">", i;
    for (i = 0; i < textareas; i++) {
      html += "<div><textarea disabled name=\"textArea\" id=\"textarea";
      html += i;
      html += "\">1</textarea><button class=\"plus\" type=\"button\">+</button><button class=\"minus\" type=\"button\">-</button></div>";
    }
    html += "</form>";
    return html; // Return the html content with the form.
  }

  $("#div").html(buildForm(50)); // Render the form with 50 textareas.

  $(".plus").on("click", function() {
    var texarea = $(this).prev(), value = texarea.val() * 1;
    value++;
    texarea.val(value);
  });
  
  $(".minus").on("click", function() {
    var texarea = $(this).prev().prev(), value = texarea.val() * 1;
    if (value > 1) {
      value--;
      texarea.val(value);
    }
  });
});
#div div {
  border: solid 1px #ccc;
  margin: 2px;
  padding: 2px;
}

button.plus,
button.minus {
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="div"></div>

请记住: ID必须是唯一的。

enter image description here

答案 2 :(得分:0)

我更喜欢使用类,因为我认为代码更清晰。

示例:package main import ( "bytes" "strconv" "strings" "testing" ) func linesStringCount(s string) string { n := strings.Count(s, "\n") if len(s) > 0 && !strings.HasSuffix(s, "\n") { n++ } return strconv.Itoa(n) } func linesStringByRune(s string) string { n := 0 for _, r := range s { if r == '\n' { n++ } } if len(s) > 0 && !strings.HasSuffix(s, "\n") { n++ } return strconv.Itoa(n) } func linesBytesCount(s []byte) string { nl := []byte{'\n'} n := bytes.Count(s, nl) if len(s) > 0 && !bytes.HasSuffix(s, nl) { n++ } return strconv.Itoa(n) } var data = []byte(`Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.`) func BenchmarkStringCount(b *testing.B) { text := string(data) b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { _ = linesStringCount(text) } } func BenchmarkStringByRune(b *testing.B) { text := string(data) b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { _ = linesStringByRune(text) } } func BenchmarkBytesToText(b *testing.B) { b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { _ = string(data) } } func BenchmarkBytesCount(b *testing.B) { text := data b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { _ = linesBytesCount(text) } }

我更喜欢使用数据与计数区域和+ / - 按钮建立链接。

&#13;
&#13;
my_set_Of_Text_area.add ('<div><span> Ananas : </span>','</div>');
&#13;
$(function() {

  class TxtAreaFab {
    constructor(Form_ID, TextAreaPrefix, BtPlusClass, BtMinusClass) {
      this._ref = 0;
      this._TaP = TextAreaPrefix;
      this._BtPlus = BtPlusClass;
      this._BtMinus = BtMinusClass;
      this._$ID = $('#' + Form_ID);
    }

    add(before, after) {
      var elements = before;
      this._ref++;
      elements += "<textarea disabled id='TxtArea_" + this._ref + "'>1</textarea>";
      elements += "<button class=" + this._BtPlus + " data-ref=\"TxtArea_" + this._ref + "\">+</button>";
      elements += "<button class=" + this._BtMinus + " data-ref=\"TxtArea_" + this._ref + "\">-</button>";
      elements += after;
      $(elements).appendTo(this._$ID);
    }
    /* ----- not used , just here for sample
			clear () {
				this._$ID.html('');
				this._ref = 0;
			}
    */
  };

  var my_set_Of_Text_area = new TxtAreaFab('txtAreaForm', 'zoneTA_', 'ClassBtPlus', 'ClassBtMinus');

  my_set_Of_Text_area.add('<div><span> Apples :  </span>', '</div>');
  my_set_Of_Text_area.add('<div><span> Oranges : </span>', '</div>');
  my_set_Of_Text_area.add('<div><span> Pears :   </span>', '</div>');
  my_set_Of_Text_area.add('<div><span> Bananas : </span>', '</div>');

  $('#txtAreaForm').on('click', "button", function(e) {
    e.stopPropagation();
    var $txtArea = $("#" + $(this).data("ref")),
      v = parseInt($txtArea.val());
    if ($(this).hasClass('ClassBtPlus')) $txtArea.val(++v);
    if ((v > 1) && ($(this).hasClass('ClassBtMinus'))) $txtArea.val(--v);
    return false;
  });

  my_set_Of_Text_area.add('<div><span> Ananas : </span>', '</div>');
});
&#13;
#txtAreaForm div {
  clear: both;
  height: 30px;
}

#txtAreaForm div span {
  display: block;
  float: left;
  width: 120px;
  font-weight: bold;
  text-align: right;
  padding-right: 10px;
}

#txtAreaForm textarea {
  display: block;
  float: left;
  width: 40px;
  height: 16px;
  font-weight: bold;
  text-align: center;
  resize: none;
}
&#13;
&#13;
&#13;

答案 3 :(得分:0)

特别有趣的解决方案! (但是真的)。​​

我只使用了9行JavaScript / jQuery,而在CSS中使用了更多。 并且不需要textarea id。 (好的,我的2个"if"语句只有1行。

对于HTML部分,每个文本框都放在"p"(段落)中,就是这样:

<p><textarea disabled > 1 </textarea></p>
<p><textarea disabled > 2 </textarea></p>
<p><textarea disabled > 3 </textarea></p>

诀窍在我使用:after:before的CSS中,如"+""-"按钮。   放置在每个框"p"的右侧。

form p:after {
    right: -22px;
    content:'+';
... 
form p:before {
    right: -43px;
    content:'-';

在jQuery部分。

我使用鼠标单击的相对位置来确定操作应该是加号还是减号。对于小故事:-- $ (this) .outerWidth (); --是有用的。

当然,在每个文本区域添加ID仍然会更好;但经过反思,我觉得这些输入字段可以在PHP服务器上生成(?)。

所以,看起来很奇怪,这个解决方案非常严重。的;)

所有内容都在摘录中。

$(function() {
  $('form p').click(function(e) {
    var
      posX = (e.pageX - $(this).offset().left) - $(this).outerWidth();
    Sign = (posX > 22) ? "moins" : (posX > 0) ? "plus" : "none",
      Valn = parseInt($(this).children('textarea').text());

    if (Sign === 'plus') $(this).children('textarea').text(++Valn);
    if ((Sign === 'moins') && (Valn > 1)) $(this).children('textarea').text(--Valn);
  });
});
textarea,
form,
p,
textarea {
  font-family: Tahoma, sans-serif;
  font-size: 16px;
}

textarea {
  float: left;
  width: 40px;
  height: 22px;
  font-weight: bold;
  text-align: center;
  resize: none;
  line-height: 20px;
}

form p {
  box-sizing: border-box;
  display: block;
  float: left;
  clear: both;
  position: relative;
  border: 0;
  margin: 5px 0 0 20px;
  padding: 0;
}

form p:before,
form p:after {
  position: absolute;
  top: 2px;
  width: 20px;
  height: 20px;
  display: block;
  color: white;
  background-color: darkslategray;
  text-align: center;
  font-size: 18px;
}

form p:after {
  right: -22px;
  content: '+';
  line-height: 18px;
}

form p:before {
  right: -43px;
  content: '-';
  line-height: 16px;
}
<form name="txtAreaForm" method='GET'>
  <p><textarea disabled> 1 </textarea></p>
  <p><textarea disabled> 2 </textarea></p>
  <p><textarea disabled> 3 </textarea></p>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>