根据文本框中的值创建html内容 [英] Creating html content based on value in textbox

查看:77
本文介绍了根据文本框中的值创建html内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:



<!DOCTYPE html>< ; HTML><身体GT; < script src =https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js> < /脚本> <脚本> 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); //(如果有多个跨度vals,那么还要console.log其他文本和数字} $('#amount')。on('change',function(){console.log('amount changed:') var boxamount = $('#amount')。val(); //显示span vals的boxamount}};< / script>< form>< fieldset style =margin:0 0 5px 0;> ;< p>输入字数+数字框:< input id =amountstep =1style =width:45px;type =numbervalue =1>< br> < br>< / textarea>< br>< spanl id< br>< / textarea&id =textInputplaceholder =在此处输入文字style =width:259px; margin:0px; height:15px; =valsstyle =margin-left:40%;> number1:< input id =numberonestep =0.05style =width:45px;type =numbervalue =0.00 > number2:< input id =number2step =0.05style =width:45px;type =numbervalue =0.00>< / span>< br>< br> < input class =buttonid =submitBtnonclick =submited();styl e =margin-left:85%;type =buttonvalue =Submit>< / p> < /字段集> < / form>< / html>

p>我希望代码在#textInput和#numberOne和#numberTwo中输出值。我试图这样做,但是,它们并没有被输出......



另外,根据#amount中的值,我希望得到这个量程。另外,我希望能够输出这些值。



以下是我的意思的示例:



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

>

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



进一步编辑:完全重构这个想法。 / strong>您试图允许用户动态添加元素,并跟踪表单字段的值。在这次修订中,我创建了一个不断更新的数组,以跟踪文本字段的内容。这样做,提交并不需要知道页面的结构,无论是动态的还是静态的。

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



我试图对评论非常苛刻,为了这一切,合理。再次,有一个小提琴



  .line-title {width:200px; margin:0px; height:15px; clear:left;}。line-number {width:45px;}。container {margin:10px;}。del-row-btn {float:right;}  

< pre class =snippet-code-html lang-html prettyprint-override> < script src =https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery .min.js>< /脚本><形式> < fieldset style =margin:0 0 5px 0;> < div class =container> < / DIV> < input value =Add rowtype =buttonclass =add-row-btn> < input class =buttonid =submitBtnstyle =margin-left:85%; type =buttonvalue =提交> < / fieldset>< / form>


Here is my code:

<!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>

I would like the code to output the values in #textInput and #numberOne and #numberTwo. I have tried to do that, however, they are not being outputted...

Also, depending on the value in #amount I would like that amount of span's made. And also, I would like to be able to output those values as well.

Here is an example of what I mean:

For example, if I put 2 in the #amount I would like the html to look like this:

And when the submit button is clicked for this example the output should be:

amount changed submitted test1 0.1 -0.15 test2 0.3 -0.45

Please help me correct my code and add in this feature. Many thanks.

解决方案

My first suggestion might be, since you want the rows to be dynamically generated, do so from the start. In my HTML, I have the fieldset and I have my containing div, but I don't have any of the form elements for the text/number inputs. Instead, I create an add-new-row button (which allows a single row at a time to be added, appending to the container), then I trigger that. Right off, first thing. Doing this forces a single row to display, in the consistent format I've defined.

Using the amount number box may not be your best solution -- how do you plan to implement that? Do you want to keep appending more rows, or when the user changes the number there do you want to destroy any existing rows? Instead, consider something like I did -- the add-row-btn (and on each row, maybe a remove-row-btn).

When the submit button is clicked, I want to iterate over all the rows (which are divs within my containers), get the values from the fields I've defined consistently, and display them.

At a glance, and given what you gave us to work with, this should at least give you a starting point...

$(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>

If you'd prefer it as a fiddle, here you go.

EDIT: Per your request, I removed the "enter how many rows you want" thing, and the code to handle it. Nothing broke in my version. You may want to take a look at what is being triggered -- if you used the version I'd posted BEFORE I added the 'add new row' option, I was triggering the #amount to create the first row. In the second iteration (and in this one), I trigger the add-row-btn instead.

FURTHER EDIT: A complete reworking of the idea. You are trying to allow users to add elements dynamically, and to keep track of the values of the form fields. In this revision, I've created an array that is constantly being updated, to track the contents of the text fields. Doing this, submitted doesn't have to be aware of the structure of the page, whether dynamic or static.

Further, I've added the ability to delete a given row. Doing so updates the rowContents array, reflecting the contents of the DOM accurately.

I've tried to be pretty heavy-handed with the comments, in order for this all to make sense. and again, there's a 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>

这篇关于根据文本框中的值创建html内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆