Skip to content Skip to sidebar Skip to footer

Creating Html Content Based On Value In Textbox

Here is my code: 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, de

Solution 1:

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.
 ******/functionsubmitted() {
  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;
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><form><fieldsetstyle=" margin: 0 0 5px 0;"><divclass="container"></div><buttonclass="add-row-btn">
      Add row
    </button><inputclass="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 rowvar 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.
 ******/functionsubmitted() {
  $(".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;
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><form><fieldsetstyle=" margin: 0 0 5px 0;"><divclass="container"></div><inputvalue="Add row"type="button"class="add-row-btn"><inputclass="button"id="submitBtn"style="margin-left: 85%;"type="button"value="Submit"></fieldset></form>

Solution 2:

<!DOCTYPE html><html><body><scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script>functionsubmited() {
         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
     }
     window.onload = function() {
       $('#amount').on('change', function() {
         console.log('amount changed:')
         var boxamount = $('#amount').val();
         //display boxamount of the span vals
       });
     };
    </script><form><fieldsetstyle=" margin: 0 0 5px 0;"><p>enter amount of text + number boxes: <inputid="amount"step="1"style=" width: 45px;"type="number"value="1"><br><br><textareaid="textInput"placeholder="enter text here"style="width: 259px; margin: 0px; height: 15px;"></textarea><br><spanid="vals"style="margin-left: 40%;">number1: <inputid="numberone"step="0.05"style=" width: 45px;"type="number"value="0.00"> number2: <inputid="numbertwo"step="0.05"style=" width: 45px;"type="number"value="0.00"></span><br><br><inputclass="button"id="submitBtn"onclick="submited();"style="margin-left: 85%;"type="button"value="Submit"></p></fieldset></form></body></html>

Post a Comment for "Creating Html Content Based On Value In Textbox"