0

I have a script posted down below, and I want the user to add a new field, when the new field gets added I want a new var to be added. Live example: User clicks on the "add new field" var gets added below var Reason2 called Reason3, Reason4, etc. "Reason Three: " +Reason3+ gets added below Reason Two on line 51.

I don't have an idea of how to do the above honestly.

<!DOCTYPE html>
<html lang="en">
<form name="TRF" method="post">
  <p style="color:white">
    <div class="container">
      <div class="row">
        <div class="col-lg-12">
          <div class="jumbotron">
            <h1 class="text-center">Accepted Format</h1>
            <hr>
            <div class="row">
              <h6 class="text-uppercase"><strong><center>Accepted Format</center></strong></h6>
              <table style="width:100%" id="theTable">
                <tr>
                  <td>Applicant's Name:</td>
                  <td><input type="text" name="accname" size="75" placeholder="" required></td>
                </tr>
                <tr>
                  <td>Reason 1:</td>
                  <td><input type="text" name="R1" size="75" placeholder="" required></td>
                </tr>
                <tr>
                  <td id="bla">Reason 2:</td>
                  <td><input type="text" name="R2" size="75" placeholder="" required></td>
                </tr>

              </table>
              <h3>CODE:</h3>
              <textarea  id="box" cols="100" rows="10"></textarea>
              <p><a class="btn btn-success btn-lg" onclick="generateCode2()" role="button">GENERATE CODE</a></p>


            </div>
            <button id="newField">
            add new field
            </button>
            </center>
          </div>
        </div>
      </div>
    </div>
<html>
<head>
<script>
function generateCode2() {
    var AccoutName = document.forms["TRF"]["accname"].value;
    var Reason1 = document.forms["TRF"]["R1"].value;
      var Reason2 = document.forms["TRF"]["R2"].value;



    document.getElementById("box").value =
"[center][img width=500 height=500]https://i.imgur.com/FuxDfcy.png[/img][/center]"+
"[hr]"+
"\n"+
"[b]Dear[/b] "+AccoutName+
"\n"+
"After reading your Application, Imperials staffs have decided to [color=green][b]Accept[/b][/color] you. "+
"\n"+
"Reason One: " +Reason1+
"\n"+
"Reason Two: " +Reason2+
"\n"+
"Welcome to the Family. "+
"\n"+

""
}
var newField = document.getElementById("newField");
var counter = 3;

function createNewField() {
  var tr = document.createElement("tr");
  var td1 = document.createElement("td");
  var td2 = document.createElement("td");
  td1.innerHTML = "Reason " + counter + ":";
  var inp = document.createElement("input");
  inp.type = "text";
  inp.size = "75";
  inp.name = "R" + counter;
  inp.value=document.getElementById("box").value;
  td2.appendChild(inp);

  document.getElementById("theTable").appendChild(tr);

  tr.appendChild(td1);
  tr.appendChild(td2);

  counter++;
}
newField.addEventListener("click", createNewField);
(function () {
    var onload = window.onload;

    window.onload = function () {
        if (typeof onload == "function") {
            onload.apply(this, arguments);
        }

        var fields = [];
        var inputs = document.getElementsByTagName("input");
        var textareas = document.getElementsByTagName("textarea");

        for (var i = 0; i < inputs.length; i++) {
            fields.push(inputs[i]);
        }

        for (var i = 0; i < textareas.length; i++) {
            fields.push(textareas[i]);
        }

        for (var i = 0; i < fields.length; i++) {
            var field = fields[i];

            if (typeof field.onpaste != "function" && !!field.getAttribute("onpaste")) {
                field.onpaste = eval("(function () { " + field.getAttribute("onpaste") + " })");
            }

            if (typeof field.onpaste == "function") {
                var oninput = field.oninput;

                field.oninput = function () {
                    if (typeof oninput == "function") {
                        oninput.apply(this, arguments);
                    }

                    if (typeof this.previousValue == "undefined") {
                        this.previousValue = this.value;
                    }

                    var pasted = (Math.abs(this.previousValue.length - this.value.length) > 1 && this.value != "");

                    if (pasted && !this.onpaste.apply(this, arguments)) {
                        this.value = this.previousValue;
                    }

                    this.previousValue = this.value;
                };

                if (field.addEventListener) {
                    field.addEventListener("input", field.oninput, false);
                } else if (field.attachEvent) {
                    field.attachEvent("oninput", field.oninput);
                }
            }
        }
    }
})();
</script>
</head>
</color>
</font>
      </div>
    </div>
  </div>
</html>

User clicks on the "add new field" var gets added below var Reason2 called Reason3, Reason4, etc. "Reason Three: " +Reason3+ gets added below Reason Two on line 51.

2
  • do you want to use vanilla js or is jquery ok Commented May 16, 2019 at 14:09
  • It doesn't really matter honestly, as long as I can get the result I want. Commented May 16, 2019 at 14:50

1 Answer 1

1

In Javascript it's possible to create html elements at runtime using the createElement() function. In your case we need to create quite a lot of individual elements to replicate the structure of the table. Those are <tr> <td> <input>. The tr element needs to be added to the table, the td containing the text 'Reason #:' as well as the td holding the input element are childs of tr. To add a dynamically created element to the DOM, the appendChild() function is used.

The input element needs some special treatment because it contains an unique id. The two html-made elements you have are 'R1' and 'R2' - so a new one should follow that pattern and start with 3. This is done by setting up a global variable , appending it to the name and increment it afterwards.

Finally we need to add a 'Create new field' button.

Take a look at this example (you have to scroll down to see the button):

var newField = document.getElementById("newField");
var counter = 3;

function createNewField() {
  var tr = document.createElement("tr");
  var td1 = document.createElement("td");
  var td2 = document.createElement("td");
  td1.innerHTML = "Reason " + counter + ":";
  var inp = document.createElement("input");
  inp.type = "text";
  inp.size = "75";
  inp.name = "R" + counter;
  td2.appendChild(inp);

  document.getElementById("theTable").appendChild(tr);

  tr.appendChild(td1);
  tr.appendChild(td2);

  counter++;
}
newField.addEventListener("click", createNewField);

function generateCode2() {
  var AccoutName = document.forms["TRF"]["accname"].value;
  var reasons = "";

  for (var a = 1; a < counter; a++) {
    reasons += "Reason " + a + ": " + document.forms["TRF"]["R" + a].value + "\n";
  }

  document.getElementById("box").value =
    "[center][img width=500 height=500]https://i.imgur.com/FuxDfcy.png[/img][/center]" +
    "[hr]" +
    "\n" +
    "[b]Dear[/b] " + AccoutName +
    "\n" +
    "After reading your Application, Imperials staffs have decided to [color=green][b]Accept[/b][/color] you. " +
    "\n" + reasons +
    "Welcome to the Family. " +
    "\n" +
    ""
}
<form name="TRF" method="post">
  <p style="color:white">
    <div class="container">
      <div class="row">
        <div class="col-lg-12">
          <div class="jumbotron">
            <h1 class="text-center">Accepted Format</h1>
            <hr>
            <div class="row">
              <h6 class="text-uppercase"><strong><center>Accepted Format</center></strong></h6>
              <table style="width:100%" id="theTable">
                <tr>
                  <td>Applicant's Name:</td>
                  <td><input type="text" name="accname" size="75" placeholder="" required></td>
                </tr>
                <tr>
                  <td>Reason 1:</td>
                  <td><input type="text" name="R1" size="75" placeholder="" required></td>
                </tr>
                <tr>
                  <td id="bla">Reason 2:</td>
                  <td><input type="text" name="R2" size="75" placeholder="" required></td>
                </tr>

              </table>
              <h3>CODE:</h3>
              <textarea id="box" cols="100" rows="10"></textarea>
              <p><a class="btn btn-success btn-lg" onclick="generateCode2()" role="button">GENERATE CODE</a></p>


            </div>
            <button id="newField">
            add new field
            </button>
            </center>
          </div>
        </div>
      </div>
    </div>

Sign up to request clarification or add additional context in comments.

7 Comments

Exactly what I wanted, except that I want to add what the user types into the text area above the "generate code" text. Reason Three: "User Input"
Do you have a way to do that?
When I enter the input for Reason 3, Reason 4, etc. The input is not put in the "text area". It only displays Reason One: Reason Two: While the other reasons added by the user are not displayed.
Ah I understand. Take a look at the updated generateCode2() function in my snippet above.
The script is exactly what I wanted, except that when I generate, Reason 1 looks like this: "undefinedReason 1: " I want to remove the "Undefined"
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.