将 Class 构造函数中的选定信息显示到 table - Javascript

Displaying selected info from Class Constructor into a table - Javascript

我试图将 html 表单中下拉列表中的选定选项与通过 JS 中的 class 构造函数创建的对象相关联。我正在努力 link 这两个,我只设法显示一些名字,并且都在 html table 的一行中。

理想情况下,我想将我的 display() 函数中的项目关联起来并显示来自我的对象的值,而不是直接使用来自表单的值。

这是我的完整代码:

/* See/add options, remove options, 
see overview of options and price
 */
// VARIABLES 
let button = document.getElementById("submit");
let choice = document.getElementById("choice");
let optionChosen = document.getElementById("option");
let optionPrice = document.getElementById("optionPrice");

// OPTIONS CLASS CONSTRUCTOR
class CarOptions {
    constructor(optionName, price) {
        this.optionName = optionName;
        this.price = price;
    }
}
// create 6 options
let option = new CarOptions("", 0);
let vac = new CarOptions("vac", 150);
let trunk = new CarOptions("trunk", 2000);
let seat = new CarOptions("seat", 550);
let night = new CarOptions("night", 360);
let wifi = new CarOptions("wifi", 1200);
let park = new CarOptions("park", 600);
// Array of all objects
let allOptions = [option, vac, trunk, seat, night, wifi, park];
// Array of all object names
let allOptionsName = [option.optionName, vac.optionName, trunk.optionName, seat.optionName, night.optionName, wifi.optionName, park.optionName];

// EVENTS
// On submit event
button.addEventListener("click", (e) => {
    e.preventDefault();
    const selected = document.querySelectorAll('#choice option:checked');
    // Displaying options names in the table
    // CURRENTLY ALL DISPLAYS IN ONE ROW 
    allOptionsName.forEach(function () {
        for (let i = 0; i < allOptionsName.length; i++) {
            const values = Array.from(selected).map(el => el.value);
            optionChosen.innerHTML = values;
            console.log(values);
            console.log("this value: " + values);
            display();
        }
    });
})

function display(element) {
    if (values.value != "") {
        optionChosen.innerHTML = element.optionName;
        optionPrice.innerHTML = element.price;
    }
    return;
}
body {
    background-color: black;
    color: white;
    font-family:'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif
}
#form {
    display: flex;
    flex-direction: column;
    width: 250px;
    align-items: center;
}
#choice {
    height: 120px;
}
.results {
    width: 300px;
    border: 2px dotted green;
    margin: 10px;
    text-align: center;
}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Car Selection</title>
</head>

<body>
    <h1>Car Choice</h1>
    <h2>Ready to buy your dream car?</h2>
    <div class="select">
        <!-- Selection of food or drink -->
        <form class="flexColumn" id="form">
            <select name="choice" id="choice" multiple="true">
                <option value="" name="">--Please choose an option--</option>
                <option id="vac" value="vac" name="vac">Built-in Vacuum (€150)</option>
                <option value="trunk" name="trunk">Automatic Opening Trunk (€2000)</option>
                <option value="seat" name="seat">Massaging Seats (€550)</option>
                <option value="night" name="night">Nightvision Dashboard System (€360)</option>
                <option value="wifi" name="wifi">WiFi/Entertainment/Navigation (€1200)</option>
                <option value="park" name="park">Self-Parking System (€600)</option>
            </select>
            <button id="submit" class="submit" submit>SUBMIT</button>
        </form>
        <p>Your current selected options:</p>
        <div id="selection" class="selection">
            <table class="results" style="width:200px">
                <tr>
                    <th>Option</th>
                    <th>Price (€)</th>
                </tr>
                <tr id="emptyRow">
                    <td id="option"></td>
                    <td id="optionPrice"></td>
                </tr>
                <tr>
                    <td>TOTAL:</td>
                    <td id="totalPrice"></td>
                </tr>
            </table>
        </div>
    </div>

    <script type="text/javascript" src="script.js"></script>

</body>

</html>

选项显示在一行中,因为您只选择了一行 table 并在其中插入了所有值。您必须为每个值创建 table 行。要按行显示值,试试这个:-

/* See/add options, remove options, 
see overview of options and price
 */
// VARIABLES 
let button = document.getElementById("submit");
let choice = document.getElementById("choice");
let row = document.getElementById('emptyRow');
let totalPriceElement = document.getElementById('totalPrice');

// OPTIONS CLASS CONSTRUCTOR
class CarOptions {
    constructor(optionName, price) {
        this.optionName = optionName;
        this.price = price;
    }
}
// create 6 options
let option = new CarOptions("", 0);
let vac = new CarOptions("vac", 150);
let trunk = new CarOptions("trunk", 2000);
let seat = new CarOptions("seat", 550);
let night = new CarOptions("night", 360);
let wifi = new CarOptions("wifi", 1200);
let park = new CarOptions("park", 600);
// Array of all objects
let allOptions = [option, vac, trunk, seat, night, wifi, park];
// Array of all object names
let allOptionsName = [option.optionName, vac.optionName, trunk.optionName, seat.optionName, night.optionName, wifi.optionName, park.optionName];

// EVENTS
// On submit event
button.addEventListener("click", (e) => {
    e.preventDefault();
    const selected = document.querySelectorAll('#choice option:checked');
    // Displaying options names in the table
    // CURRENTLY ALL DISPLAYS IN ONE ROW 

   
        for(let i = 0; i < selected.length;i++){
            
            const values = Array.from(selected).map(el => el.value);
            const element = allOptions.filter(option => {
                return option.optionName == values[i];
                
            });
          
            var tableRow = document.createElement('TR');
            var tableCellName = document.createElement('TD');
            var tableCellPrice = document.createElement('TD');
            tableCellName.setAttribute('class','option');
            tableCellName.innerText = values[i];
            tableCellPrice.setAttribute('class','price');
            tableCellPrice.innerText = element[0].price;
            tableRow.appendChild(tableCellName);
            tableRow.appendChild(tableCellPrice);
            row.appendChild(tableRow);
          

         
            if(i == selected.length - 1){
                display(values);
            }
       }
        
   
})

function display(values) {
    const elements = allOptions.filter(option => {
       
        for(let i = 0; i < values.length; i++){
            if(option.optionName == values[i]){
                return option; 
            }
            else{
                continue;
            }
        }
    })
    let totalPrice = 0;
    for(let i = 0; i<elements.length;i++){
        totalPrice += elements[i].price;
    }
    totalPriceElement.innerText = totalPrice;
    return;
}
body {
    background-color: black;
    color: white;
    font-family:'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif
}
#form {
    display: flex;
    flex-direction: column;
    width: 250px;
    align-items: center;
}
#choice {
    height: 120px;
}
.results {
    width: 300px;
    border: 2px dotted green;
    margin: 10px;
    text-align: center;
}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Car Selection</title>
</head>

<body>
    <h1>Car Choice</h1>
    <h2>Ready to buy your dream car?</h2>
    <div class="select">
        <!-- Selection of food or drink -->
        <form class="flexColumn" id="form">
            <select name="choice" id="choice" multiple="true">
                <option value="" name="">--Please choose an option--</option>
                <option id="vac" value="vac" name="vac">Built-in Vacuum (€150)</option>
                <option value="trunk" name="trunk">Automatic Opening Trunk (€2000)</option>
                <option value="seat" name="seat">Massaging Seats (€550)</option>
                <option value="night" name="night">Nightvision Dashboard System (€360)</option>
                <option value="wifi" name="wifi">WiFi/Entertainment/Navigation (€1200)</option>
                <option value="park" name="park">Self-Parking System (€600)</option>
            </select>
            <button id="submit" class="submit" submit>SUBMIT</button>
        </form>
        <p>Your current selected options:</p>
        <div id="selection" class="selection">
            <table class="results" style="width:200px">
                <tr>
                    <th>Option</th>
                    <th>Price (€)</th>
                </tr>
                <tbody id="emptyRow">
                    
                </tbody>
                <tr>
                    <td>TOTAL:</td>
                    <td id="totalPrice"></td>
                </tr>
            </table>
        </div>
    </div>

    <script type="text/javascript" src="script.js"></script>

</body>

</html>

此代码将使您的选项与价格和总价一起显示在多行中。

像下面的片段一样尝试:

/* See/add options, remove options, 
see overview of options and price
 */
// VARIABLES 
let button = document.querySelector("#submit");
let choice = document.querySelector("#choice");

// OPTIONS CLASS CONSTRUCTOR
class CarOptions {
  constructor(optionName, price) {
    this.optionName = optionName;
    this.price = price;
  }
}
// create 6 options
let option = new CarOptions("", 0);
let vac = new CarOptions("vac", 150);
let trunk = new CarOptions("trunk", 2000);
let seat = new CarOptions("seat", 550);
let night = new CarOptions("night", 360);
let wifi = new CarOptions("wifi", 1200);
let park = new CarOptions("park", 600);
// Array of all objects
let allOptions = [option, vac, trunk, seat, night, wifi, park];
// Array of all object names
let allOptionsName = [option.optionName, vac.optionName, trunk.optionName, seat.optionName, night.optionName, wifi.optionName, park.optionName];

// EVENTS
// On submit event
button.addEventListener("click", (e) => {
  e.preventDefault();
  const selected = document.querySelectorAll('#choice option:checked');
  const values = Array.from(selected).map(el => el.value);
  const res = allOptions.filter(a => values.includes(a.optionName))
  const total = res.reduce((acc, v) => acc += v.price, 0 )
  display(res, total);
})
function createTr() {
  let tbodyRef = document.querySelectorAll("#cars");
  let newRow = tbodyRef[0].insertRow();
  return newRow
}
function createTd(el, newTr) {
  let newel = document.createElement('td');
  let elementid = document.querySelectorAll("td").length
  newel.setAttribute('id',elementid);
  newel.innerHTML = el
  newTr.appendChild(newel);
}
function display(element, total) {
  element.forEach(e => {
    const newTr = createTr()
    createTd(e.optionName, newTr)
    createTd(e.price, newTr)
  })
  const tot = document.querySelector("#totalPrice")
  tot.innerHTML = total
}
body {
    background-color: black;
    color: white;
    font-family:'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif
}
#form {
    display: flex;
    flex-direction: column;
    width: 250px;
    align-items: center;
}
#choice {
    height: 120px;
}
.results {
    width: 300px;
    border: 2px dotted green;
    margin: 10px;
    text-align: center;
}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Car Selection</title>
</head>

<body>
    <h1>Car Choice</h1>
    <h2>Ready to buy your dream car?</h2>
    <div class="select">
        <!-- Selection of food or drink -->
        <form class="flexColumn" id="form">
            <select name="choice" id="choice" multiple="true">
                <option value="" name="">--Please choose an option--</option>
                <option id="vac" value="vac" name="vac">Built-in Vacuum (€150)</option>
                <option value="trunk" name="trunk">Automatic Opening Trunk (€2000)</option>
                <option value="seat" name="seat">Massaging Seats (€550)</option>
                <option value="night" name="night">Nightvision Dashboard System (€360)</option>
                <option value="wifi" name="wifi">WiFi/Entertainment/Navigation (€1200)</option>
                <option value="park" name="park">Self-Parking System (€600)</option>
            </select>
            <button id="submit" class="submit" submit>SUBMIT</button>
        </form>
        <p>Your current selected options:</p>
        <div id="selection" class="selection">
            <table class="results" style="width:200px">
                <tr>
                    <th>Option</th>
                    <th>Price (€)</th>
                </tr>
                <tbody id="cars">
                <tbody>
                <tfoot>
                  <tr>
                    <td>TOTAL:</td>
                    <td id="totalPrice"></td>
                  </tr>
                </tfoot>
            </table>
        </div>
    </div>

    <script type="text/javascript" src="script.js"></script>

</body>

</html>