简体   繁体   中英

In Javascript can you add an element using DOM Manipulation then access that element?

So I am trying to build a form which when you click family it would add a number input. Based on that number input it would build more text entries. For example, if I clicked on family, then typed in 4 for the number input that would appear. It would create 4 different text entries that would require you to type in your family's name. So my question is can you create a element then store the value of that element in a variable to use later. Here is my code: Html:

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>repl.it</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh"
     crossorigin="anonymous">
    <style>
    </style>
</head>

<body>
    <div class = "container">
    <form>
      <p>Is this membership for an individual or a family?</p>
      <p>Individual - $60: <input type = "radio" id = "individual-selector" value = "individual" name = "type"></p>
      <p>Family - $150: <input type = "radio" id = "family-individual-selector" value = "family" name = "type"></p>
      <div id = "family-number"></div>
      <div class = "form-start">
        <p>Full Name: <input type = "text" required name = "name" placeholder = "First Last"></p>
        <p>Address: <input type = "text" required name = "address" placeholder = "eg - 123 Main Street"></p>
        <p>City: <input type = "text" required name = "city" placeholder = "New York"></p>
        <p>State: <input type = "text" required name = "state" placeholder = "NY"></p>
        <p>Zip Code: <input type = "text" required name = "zip" placeholder = "10030"></p>
        <p>Phone Number: <input type="tel" id="phone" name="phone" placeholder="123-459-6780" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" required></p>
        <p>Email: <input type = "email" name = "email" id = "email" placeholder = "random1234@gmail.com" required></p>
      </div>
      <input type = "submit" value = "Purchase">
      <input type = "reset">
    </form>
    </div>
    <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
  <script src="script.js"></script>
  </body>
</html>

JS:

var family = document.querySelector("#family-individual-selector");
var individual = document.querySelector("#individual-selector");
var form = document.querySelector(".form-start");
var familyNumber = document.querySelector("#family-number");
individual.addEventListener("click",function(){
    familyNumber.innerHTML = "";
})
family.addEventListener("click",function(){
  familyNumber.innerHTML = "<p>Input Number Of Family Members: <input type = 'number' id = 'family-num'></p>"
  var familyNum = document.querySelector("#family-num");
  })

you can use jquery to this task with append function

first we need to create parent element to store the input member

<div id="family-member"></div>

and then get the family amount that need to be added

// create array to store the input member
var families = [];
$("#family-num").on('change', function() {
    // reset the view and the array every change detected
    $("#family-member").empty();
    families = [];
    for(let i = 1; i<=this.value; i++) {
      $("#family-member").append("<p>Member "+ (i) +": <input type = 'text' id = 'family-member-"+(i)+"'></p>")
      families.push($("#family-member-"+i));
    }
})

with this method you will append new input to #family-member

finally you can use the families array, if you want to get it values, you can do by this

var family_values = [];
families.forEach(function(member) {
   family_values.push(member.value);
});

You access values of input boxes using the value property
Change
var familyNum = document.querySelector("#family-num");
to
var familyNum = document.querySelector("#family-num").value;
or in jQuery
var familyNum = $("family_num").val()

TL;DR

Use document.createElement() to create <input> elements and Node.appendChild() to append them in DOM.


Once you get number of elements you can create that many <input> elements and add them to DOM.

HTML:

<div id="inputContainer"></div>

JS:

let inputContainer =
document.querySelector('#inputContainer');


function createInputs(n){
    for(let i= i<n;i++){
       let input = 
       document.createElement('input');
       inputContainer.appendChild(input);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM