I am developing an application where the user has to input a name and then there is a progress bar that must be set the value in the input text type (or numeric type). I want the progress bar to automatically have that value.
I used this HTML code:
<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>
and my javascript code is :
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;
}
it better to add the data using one function so it easy to validate and doesn't require element ID
.
You can't use document.getElementById("score").value
because its not <progress>
tag, use attribute 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>