javascript - 根据文本框中的值创建 html 内容

标签 javascript jquery html

这是我的代码:

<!DOCTYPE html>
<html>
<body>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
	</script> 
	<script>
	 window.onload = function() {
	   function submited() {
	     console.log("submitted");
	     var textcontent = $('#textInput').val();
	     var firstnumber = $('#numberone').val();
	     var secondnumber = $('#numbertwo').val();
	     console.log(textcontent + ' '+firstnumber+ ' '+secondnumber);
	     //if there is more than one span vals, then also console.log the other text and numbers
	   }
	   
	   $('#amount').on('change', function() {
	     console.log('amount changed:')
	     var boxamount = $('#amount').val();
	     //display boxamount of the span vals
	   }
	 };
	</script>
	<form>
		<fieldset style=" margin: 0 0 5px 0;">
			<p>enter amount of text + number boxes: <input id="amount" step="1" style=" width: 45px;" type="number" value="1"><br>
			<br>
			<textarea id="textInput" placeholder="enter text here" style="width: 259px; margin: 0px; height: 15px;"></textarea><br>
			<span id="vals" style="margin-left: 40%;">number1: <input id="numberone" step="0.05" style=" width: 45px;" type="number" value="0.00"> number2: <input id="number2" step="0.05" style=" width: 45px;" type="number" value="0.00"></span><br>
			<br>
			<input class="button" id="submitBtn" onclick="submited();" style="margin-left: 85%;" type="button" value="Submit"></p>
		</fieldset>
	</form>
</body>
</html>

我希望代码输出#textInput、#numberOne 和#numberTwo 中的值。我已经尝试这样做,但是,它们没有被输出......

此外,根据 #amount 中的值,我希望制作该数量的跨度。而且,我也希望能够输出这些值。

以下是我的意思的示例:

例如,如果我在 #amount 中放入 2,我希望 html 看起来像这样:

enter image description here

当单击此示例的提交按钮时,输出应为:

金额已更改 已提交 测试1 0.1 -0.15 测试2 0.3 -0.45

请帮助我更正我的代码并添加此功能。 非常感谢。

最佳答案

我的第一个建议可能是,因为您希望动态生成行,所以从一开始就这样做。在我的 HTML 中,我有字段集和包含 div,但我没有任何用于文本/数字输入的表单元素。相反,我创建一个添加新行按钮(允许一次添加一行,附加到容器),然后触发该按钮。马上,第一件事。这样做会强制以我定义的一致格式显示单行。

使用金额数字框可能不是您的最佳解决方案 - 您打算如何实现?您想继续追加更多行,还是当用户更改数字时您想销毁任何现有行?相反,请考虑像我所做的那样——add-row-btn(并且在每一行上,可能有一个remove-row-btn)。

当单击提交按钮时,我想迭代所有行(它们是我的容器中的 div),从我一致定义的字段中获取值,然后显示它们。

乍一看,考虑到您为我们提供的工作内容,这至少应该为您提供一个起点......

$(function() {
  $("#submitBtn").on("click", submitted);
  // Created an 'add new row' button, which non-destructively adds a row to the container.
  $(".add-row-btn").on("click", function(evt) {
      evt.preventDefault();
      evt.stopPropagation();
      $(".container").append(createNewRow());
    })
  // Start with an initial value.
  $(".add-row-btn").trigger("click");
})


/*****
 * createNewRow() -- function to create a new row, composed of a text input,
 *    and two labels containing number inputs.
 *****/
var createNewRow = function() {
  /****
   * first, we'll define all the elements that will be placed
   *  in this row -- the text input, the labels and the inputs.
   ****/
  var lineTitleEl = $("<input>").attr("placeholder", "enter text here")
    .addClass("line-title");
  var labelEl = $("<label>");
  var inputEl = $("<input>").attr("step", "0.05").attr("type", "number")
    .addClass("line-number");

  // The firstNumberEl is a label containing an input. I can simply
  //   clone my label el, and input el, and use them. Don't need to,
  //   but i CAN.
  var firstNumberEl = labelEl.clone();
  firstNumberEl.text("number1: ").attr("class", "first-number-el").append(inputEl.clone());

  var secondNumberEl = labelEl.clone();
  secondNumberEl.text("number2: ").attr("class", "second-number-el").append(inputEl.clone());

  // Now create the row, which is a div containing those elements.
  var newRowEl = $("<div>").append(lineTitleEl, firstNumberEl, secondNumberEl);

  // Simply return that row -- the user can send it to the console or
  //  can append it wherever they like.
  return newRowEl;
}

/******
 * submitted() -- function to handle the submit button. We want to 
 *   iterate over all the rows, and given that they now have a consistent
 *   format, parse out the required data and display it.
 ******/
function submitted() {
  console.log("submitted");
  $(".container").children("div").each(function() {
    var title = $(this).find(".line-title").val();
    var firstNum = $(this).find(".first-number-el input").val();
    var secondNum = $(this).find(".second-number-el input").val();
    console.log(title + ", " + firstNum + ", " + secondNum);
  })

}
.line-title {
  width: 259px;
  margin: 0px;
  height: 15px;
  clear: left;
}

.line-number {
  width: 45px;
}

.container {
  margin: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <fieldset style=" margin: 0 0 5px 0;">

    <div class="container">

    </div>
    <button class="add-row-btn">
      Add row
    </button>
    <input class="button" id="submitBtn" style="margin-left: 85%;" type="button" value="Submit">
  </fieldset>
</form>

如果您更喜欢它作为 fiddle , here you go

编辑:根据您的要求,我删除了“输入您想要的行数”的内容以及处理它的代码。我的版本没有任何问题。您可能想看看正在触发的内容 - 如果您使用我在添加“添加新行”选项之前发布的版本,则我正在触发 #amount 来创建第一行。在第二次迭代(以及这一次)中,我改为触发 add-row-btn。

进一步编辑:对想法的彻底修改。您试图允许用户动态添加元素,并跟踪表单字段的值。在此版本中,我创建了一个不断更新的数组,以跟踪文本字段的内容。这样做,提交者不必知道页面的结构,无论是动态的还是静态的。

此外,我还添加了删除给定行的功能。这样做会更新 rowContents 数组,准确反射(reflect) DOM 的内容。

为了让这一切都有意义,我尝试对评论采取相当严厉的态度。再次,有一个 fiddle for that .

$(function() {
  // create an array to store all the row content information.
  var rowContents = [];
  /******
   * Handler for the submit button. I'm doing two things here now -- first, I
   *  simply dump the contents of the rowContents array. Second, I keep the
   *  existing handling. Both return the same results, as I've wired the form
   *  elements to update the rowContents array as they change.
   ******/
  $("#submitBtn").on("click", function() {
    console.log("The contents of the rowContents array:");
    console.log(JSON.stringify(rowContents) );
    console.log("The contents of the actual elements,via the submitted function:");
    submitted();
  });
  // Created an 'add new row' button, which non-destructively adds
  //   a row to the container.
  $(".add-row-btn").on("click", function() {
    // createNewRow has to be aware of the rowContents array, as we 
    //  need to create a new element in that array for this row.
    $(".container").append(createNewRow(rowContents));
  });
  // Created a button to delete the chosen row. This should
  //  remove the row, and remove the row's object in the rowContents
  //  array.
  $("body").on("click", ".del-row-btn", function(event) {
    // First, we get the clicked row's index, and use that to remove
    //  that row from the rowContents array.
    var rowToRemove = $(event.currentTarget).parents(".row");
    rowIndexToRemove = $(rowToRemove).index();
    rowContents.splice(rowIndexToRemove, 1);
    
    // Then, we simply call removeRow and pass it the row to remove.
    removeRow(rowToRemove);
  });
  /******
   * Any time the row's text inputs change, I want to update the
   *  rowContents object. I was using the change event, but the
   *  issue with that is, if you have a text field highlighted
   *  and click on submit, it doesn't register the change. This
   *  way is a little more processor-intensive, but it will work.
   *  Of course, being a number field, we still listen for change.
   *****/
  $("body").on("keyup change", ".row input", function(event) {
    // get the current row
    var rowToUpdate = $(event.currentTarget).parents(".row");

    // use the current row to get the input values.
    var title = rowToUpdate.find(".line-title").val();
    var firstVal = rowToUpdate.find(".first-number-el input").val();
    var secondVal = rowToUpdate.find(".second-number-el input").val();

    // using those values, create the row object.
    var rowObj = {
      "title": title,
      "firstVal": firstVal,
      "secondVal": secondVal
    }
    
    // destructively replace the current row in that rowContents array.
    rowContents[rowToUpdate.index()] = rowObj;
  });
  
  // Triggering the add-row-btn will display a single row.
  $(".add-row-btn").trigger("click");
})


/*****
 * createNewRow() -- function to create a new row, composed of a text input,
 *    and two labels containing number inputs.
 *****/
var createNewRow = function(rowContents) {
  /****
   * first, we'll define all the elements that will be placed
   *  in this row -- the text input, the labels and the inputs.
   ****/
  var lineTitleEl = $("<input>").attr("placeholder", "enter text here")
    .addClass("line-title");
  var labelEl = $("<label>");
  var inputEl = $("<input>").attr("step", "0.05").attr("type", "number")
    .addClass("line-number");

  // The firstNumberEl is a label containing an input. I can simply
  //   clone my label el, and input el, and use them. Don't need to,
  //   but i CAN.
  var firstNumberEl = labelEl.clone();
  firstNumberEl.text("number1: ").attr("class", "first-number-el").append(inputEl.clone());

  var secondNumberEl = labelEl.clone();
  secondNumberEl.text("number2: ").attr("class", "second-number-el").append(inputEl.clone());

  var removeBtnEl = $("<input>").attr("type", "button").val("X").addClass("del-row-btn")

  // Now create the row, which is a div containing those elements.
  var newRowEl = $("<div>").addClass("row").append(lineTitleEl, firstNumberEl, secondNumberEl, removeBtnEl);

  // Here, we want to create an empty row object, simply to
  //  function as a placeholder. This way, if someone clicks
  //  on the submit button, they won't see an empty array el.
  var newRowObject = {
    "title": "",
    "firstVal": "",
    "secondVal": ""
  };
  // Add that row object to the end of the array
  rowContents.push(newRowObject);

  // Simply return that row -- the user can send it to the console or
  //  can append it wherever they like.
  return newRowEl;
}

/******
 * removeRow() removes the given row from the DOM. We could
 *   place more functionality in here, but for our purposes, this will do.
 ******/
var removeRow = function(row) {
  // jQuery makes this pretty easy.
  $(row).remove();
};

/******
 * submitted() -- function to handle the submit button. We want to 
 *   iterate over all the rows, and given that they now have a consistent
 *   format, parse out the required data and display it.
 ******/
function submitted() {
  $(".container").children("div").each(function() {
    var title = $(this).find(".line-title").val();
    var firstNum = $(this).find(".first-number-el input").val();
    var secondNum = $(this).find(".second-number-el input").val();
    console.log(title + ", " + firstNum + ", " + secondNum);
  })

}
.line-title {
  width: 200px;
  margin: 0px;
  height: 15px;
  clear: left;
}

.line-number {
  width: 45px;
}

.container {
  margin: 10px;
}

.del-row-btn {
  float: right;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <fieldset style=" margin: 0 0 5px 0;">
    <div class="container">

    </div>
    <input value="Add row" type="button" class="add-row-btn">
    <input class="button" id="submitBtn" style="margin-left: 85%;" type="button" value="Submit">
  </fieldset>
</form>

关于javascript - 根据文本框中的值创建 html 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47398891/

相关文章:

javascript - 如何使用 Sequelize 正确设置 Winston 日志记录?

javascript - 如何将一个值发布到 WebService 中并解析另一个值?超文本标记语言

jquery - 持有 jQuery 对象的变量范围(通过选择器)不是全局的

javascript - 从 javascript 调用 python FUNCTION

javascript - Ajax 表单验证和提交

jquery - 单击表格获取 TD 的 ID

javascript - 如何为内容 slider 、内容轮播或内容滚动创建箭头导航

javascript - 检查 HTML 表列中是否存在值,jquery

html - 如何更改 svg 图像的颜色

html - 标签从盒子里掉出来