如何通过文本输入设置进度条值?

How do I set a progress bar value by text-type input?

我正在开发一个应用程序,用户必须在其中输入名称,然后有一个进度条必须设置输入文本类型(或数字类型)的值。我希望进度条自动具有该值。

我使用了这个 HTML 代码:

<table id="table">
    <thead>
        <tr>
           <th>Name</th>
           <th>Score</th>
        </tr>
    </thead>
</table>

<label class="form-control-label" for="name">Name:</label>
<input class="form-control" name="name" id="name" type="text">
<button class="btn btn-primary" onclick="addHtmlTableRow();">Add Data</button>

<label class="form-control-label" for="score">Score:</label>
<input class="form-control" name="score" id="score" type="number">
<button class="btn btn-primary" onclick="addHtmlTableRowScore();">Add Score</button>

我的 javascript 代码是:

function addHtmlTableRow(){
var table = document.getElementById("table"),
    newRow = table.insertRow(table.length),
    cell1 = newRow.insertCell(0),
    cell2 = newRow.insertCell(1),
    name = document.getElementById("name").value;

cell1.innerHTML = name;
cell2.innerHTML = "<div class=\"progress\"><div class=\"progress-bar\" id=\"score-progress\" role=\"progressbar\"  aria-valuemin=\"0\" aria-valuemax=\"100\"></div></div>";
}

function addHtmlTableRowScore(){
var student_score = document.getElementById("score-progress");
student_score.value = document.getElementById("score").value;
}

最好使用一个函数添加数据,以便于验证并且不需要元素 ID

你不能使用 document.getElementById("score").value 因为它不是 <progress> 标签,使用属性 style="width: 50%".

function addHtmlTableRow() {
  var score = document.getElementById('score').value,
    name = document.getElementById('name').value;

  //validate score
  if (!name || !score) {
    console.log('name and score are required!');
    return;
  }

  var table = document.getElementById('table'),
    newRow = table.insertRow(table.length),
    cell1 = newRow.insertCell(0),
    cell2 = newRow.insertCell(1);

  cell1.innerHTML = name;
  cell2.innerHTML =
    '<div class="progress"><div class="progress-bar" style="width: ' +
    score +
    '%" role="progressbar"  aria-valuemin="0" aria-valuemax="100"></div></div>';
}
body{padding: 10px;}
table, td, th {
  border: 1px solid #bbb;
}

table {
  width: 100%;
  border-collapse: collapse;
}

td:nth-child(2){
  width: 80%;
  padding: 5px;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" />

<table id="table">
  <thead>
    <tr>
      <th>Name</th>
      <th>Score</th>
    </tr>
  </thead>
</table>

<label class="form-control-label" for="name">Name:</label>
<input class="form-control" name="name" id="name" type="text" />
<label class="form-control-label" for="score">Score:</label>
<input class="form-control" name="score" id="score" type="number" />
<br />
<button class="btn btn-primary" onclick="addHtmlTableRow();">
      Add Row Data
    </button>