HTML input value append to a bootstrap table - javascript

I am trying to pass the value of an input a user provides to a bootstrap table. User provides a name and a score. Currently it is being displayed right below the table instead of within it. How would I go about doing this. I've tried to append it using javascript but cant seem to figure it out. Thanks

You have to append data you have in rankings to the table as rows trs using the following line :
$('table').append('<tr><td>' + rankPosition + '</td><td> ' +rankings[i].name + '</td><td>'
+ rankings[i].score + ' pts</td></tr>');
Note : Add $('table tbody').empty() before the loop to reset table content.
Hope this helps.
$(document).ready(function() {
var scoreboard;
var rankings = [];
var displayScoreboard = function(rankings) {
var rankPosition = 1;
var tieScore = 0
var previousScore = 0;
$('#rankings').html('')
$('table tbody').empty();
for (var i = 0; i < rankings.length; i++) {
if (i > 0 && rankings[i-1].score !== rankings[i].score) {
rankPosition = rankPosition + tieScore +1;
}
$('table').append('<tr><td>' + rankPosition + '</td><td> ' +rankings[i].name + '</td><td> ' + rankings[i].score + ' pts</td></tr>')
}
}
var sortRankings = function(rankings) {
rankings.sort(function(a, b) {
return b.score-a.score;
});
};
$('#add').on('click', function() {
var playerName = $('#eq-name').val();
var playerScore = $('#eq-score').val();
if (playerName.length > 0 && playerScore.length > 0) {
var playerStats = {name: playerName, score: playerScore};
rankings.push(playerStats);
sortRankings(rankings);
displayScoreboard(rankings);
$('#eq-name').val('');
$('#eq-score').val('');
} else {
alert("Please enter a name and a score");
}
});
$('#clear').on('click', function() {
$('#rankings').html('');
rankings = [];
});
});
.eq-input {
display:block;
text-align:center;
vertical-align:middle;
width:100%;
height:100%;
padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<meta charset="utf-8">
<title>EverQuoteTest</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="css/main.scss">
</head>
<body>
<div class="container eq-input">
<input type="text" id="eq-name" placeholder="Name">
<input type="number" id="eq-score" placeholder="Score" min=0>
<br>
<br>
<button class="btn btn-success" id="add">Add To Rankings</button>
<button class="btn btn-danger" id="clear">Clear Rankings</button>
<a id="add-game" class="btn btn-default ">Add Game</a>
</div>
<div class="container">
<div class="col-md-8 col-md-offset-4">
<h3>Leaderboard</h3>
</div>
<table class="table" border="1">
<thead>
<tr>
<th>Rank</th>
<th>Name</th>
<th>Score</th>
</tr>
</thead>
</table>
<ul class="list-unstyled" id="rankings"></ul>
</div>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<!-- <script src="http://cdnjs.cloudflare.com/ajax/libs/lodash.js/2.0.0/lodash.min.js"></script> -->
<script src="js/main.js"></script>
</body>
</html>

Add this code:
$('.table')
.append('<tr><td>' + rankPosition + '</td><td>' + rankPosition + '</td><td>' +rankings[i].name + ', ' + rankings[i].score + ' pts</tr>');
Fiddle: http://codepen.io/anon/pen/dGdabG

Related

How to display the result in another page after submit?

How can I display my data into another html after submit? I tried to store the value in local Storage and that didn't work out. How can i display the result in other page? In the below snippet i some how achieved to display data by using show and hide methods. But i'm looking to display my data in new HTML page.
var data = [
{
"username": "MADHU BABU POOJALA",
"skills": "BD",
"location": "Hyderabad",
"email": "rgw#yahoo.in",
"bscore": 856,
"ranking": 14652,
},
{
"username": "Mj",
"skills": ".net",
"location": "Hyderabad",
"email": "csaca#yahoo.in",
"bscore": 8540,
"ranking": 1452,
}
];
var result = [];
function Sort(val) {
result.sort(function (a, b) {
if (a[val] < b[val]) return -1;
if (a[val] > b[val]) return 1;
return 0;
});
searchResult(result);
}
function search(str) {
var str = str.trim().toUpperCase();
if (str !== '') {
var rslt = [];
for (var j = 0; j < result.length; j++) {
if (result[j].skills.toUpperCase().match(str)) {
rslt.push(result[j]);
}
}
searchResult(rslt);
} else {
searchResult(result);
}
}
function getResult() {
/* Read value from input fields */
var skills = $("#skills").val() || '',
email = $("#email").val() || '',
username = $("#username").val() || '',
location = $("#location").val() || '',
i;
result = []
for (i = 0; i < data.length; i++) {
if ((skills !== '' && data[i]["skills"].toUpperCase().indexOf(skills.toUpperCase()) !== -1) || (data[i]
["email"].toUpperCase() === email.toUpperCase()) || (data[i]["location"].toUpperCase() ===
location.toUpperCase()) || (
data[i]["username"].toUpperCase() === username.toUpperCase())) {
result.push(data[i]);
}
}
return result;
};
$('#submit').click(function onClick() {
$(".ip").hide();
$(".tb").show();
var output = getResult();
searchResult(output);
});
$("#back").click(function () {
$('input[type="text"]').val('').removeAttr('checked').removeAttr('selected');
$('input[type="email"]').val('').removeAttr('checked').removeAttr('selected');
$(".tb").hide();
$(".ip").show();
});
function searchResult(output) {
var html = '';
$.each(output, function (key, value) {
html += '<div style="border:1px solid #000;padding:10px;margin:10px;">';
html += '<span style="font-weight:bold;">' + value.username + '</span>' +
'<br/>';
html += '<span>' + 'Email :' + '</span>' + '<span>' + value.email + '</span>' +
'<br/>';
html += '<span>' + 'Skills :' + '</span>' + '<span>' + value.skills + '</span>' +
'<br/>';
html += '<span>' + 'Location :' + '</span>' + '<span>' + value.location + '</span>' +
'<br/>';
html += '<span>' + 'B-score :' + '</span>' + '<span>' + value.bscore + '</span>' +
'<br/>';
html += '<span>' + 'Ranking :' + '</span>' + '<span>' + value.ranking + '</span>' +
'<br/>';
html += '</div>';
});
$('#table').html(html);
}
$(document).ready(function () {
$('#submit').attr('disabled', 'disabled');
$('input[type="text"]').keyup(function () {
if ($(this).val() != '') {
$('input[type="submit"]').removeAttr('disabled');
}
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" integrity="sha384-mzrmE5qonljUremFsqc01SB46JvROS7bZs3IO2EmfFsd15uHvIt+Y8vEf7N7fWAU"
crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<style>
.results tr[visible='false'],
.no-result {
display: none;
}
.results tr[visible='true'] {
display: table-row;
}
.form-group {
position: fixed;
top: 30%;
left: 50%;
width: 1200px;
height: 200px;
background: #fff;
transform: translate(-15%, -50%);
}
</style>
</head>
<body>
<div class="ip">
<div class="form-group ">
<div class="col-4">
<label for="skills">Skills</label>
<input class="form-control" id="skills" type="text" placeholder="skills">
</div>
<div class="col-4">
<label for="email">Email</label>
<input class="form-control" id="email" type="text" placeholder="mail id">
</div>
<div class="col-4">
<label for="username">Username</label>
<input class="form-control" id="username" type="text" placeholder="username">
</div>
<div class="col-4">
<label for="location">location</label>
<input class="form-control" id="location" type="text" placeholder="location">
</div>
<br>
<div class="col-4">
<input id="submit" class="btn" type="submit" value="submit" disabled='disabled'>
</div>
</div>
</div>
<br>
<div style="display: none" class="tb">
<button class="btn" id="back">back to search</button>
<br>
<br>
<br>
<div class="container-fluid">
<div class="row">
<div class="left">
<label style="font-size: 20px;color: black;margin:0px">
Core Skills :
</label>
<input type="text" onkeyup="search(this.value)">
</div>
<div class="right">
<form>
<label style="font-size: 20px;color: black;margin:0px">
Sort By :
</label>
<select onchange="Sort(this.value)">
<option>-- select --</option>
<option value="username">A to Z</option>
<option value="bscore">B-score</option>
<option value="ranking">Ranking</option>
</select>
</form>
</div>
</div>
</div>
<div id="table">
</div>
</div>
</body>
</html>

Why my button is not working in the input form?

The expected behaviour of the code above is when I click the "Add" button the issue is created and is shown beneath the button. The problem is, nothing happens instead. I've been trying to search the web to find an answer but with no luck. Any idea what's wrong?
Here are my index.html and JavaScript:
document.getElementById('issueInputForm').addEventListener('submit', saveIssue);
function saveIssue(e) {
var issueDesc = document.getElementById('issueDescInput').value;
var issueSeverity = document.getElementById('issueSeverityInput').value;
var issueAssignedTo = document.getElementById('issueAssigntedToInput').value;
var issueID = chance.guid();
var issueStatus = 'Open';
var issue = {
id: issueID,
description: issueDesc,
severity: issueSeverity,
assignedTo: issueAssignedTo,
status: issueStatus
};
if (localStorage.getItem('issues') === null) {
//var issues = [];
issues.push(issue);
localStorage.setItem('issues', JSON.stringify(issues));
} else {
var issues = JSON.parse(localStorage.getItem('issues'));
issues.push(issue);
localStorage.setItem('issues', JSON.stringify(issues));
}
document.getElementById('issueInputForm').reset();
fetchIssue();
e.preventDefault();
}
function setStatusClosed(id) {
var issues = JSON.parse(localStorage.getItem('issues'));
for (var i = 0; i < issues.length; i++)
if (issues[i].id === id)
issues[i].status = 'Closed';
localStorage.setItem('issues', JSON.stringify(issues));
fetchIssue();
}
function deleteIssue(id) {
var issues = JSON.parse(localStorage.getItem('issues'));
for (var i = 0; i < issues.length; i++)
if (issues[i].id === id)
issues.splice(i, 1);
localStorage.setItem('issues', JSON.stringify(issues));
fetchIssue();
}
function fetchIssue() {
var issues = JSON.parse(localStorage.getItem('issues'));
var issuesList = document.getElementById('issuesList');
issuesList.innerHTML = '';
for (var i = 0; i < issues.length; i++) {
var id = issues[i].id;
var desc = issues[i].description;
var severity = issues[i].severity;
var assignedTo = issues[i].assignedTo;
var status = issues[i].status;
issuesList.innerHTML += '<div class="well">' +
'<h6> Issue ID: ' + id + '</h6>' +
'<p><span class="label label-info">' + status + '</span></p>' +
'<h3>' + desc + '</h3>' +
'<p><span class="glyphicon glyphicon-time"></span>' + severity + '</p>' +
'<p><span class="glyphicon glyphicon-user"></span>' + assignedTo + '</p>' +
'Close' +
'Delete'+
'</div>';
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Issue Tracker</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
</head>
<body onload="fetchIssue()">
<div class="container">
<h1>JS IssueTracker</h1>
</div class="jumbotron">
<h3>Add New Issue:</h3>
<form id="issueInputForm" >
<div class="form-group">
<label for="issueDescInput">Description</label>
<input type="text" class="form-control" id="issueDescInput" placeholder="Describe the issue...">
</div>
<div class="form-group">
<label for="issueSeverityInput">Severity</label>
<select id="issueSeverityInput" class="form-control">
<option value="Low">Low</option>
<option value="Medium">Medium</option>
<option value="High">High</option>
</select>
</div>
<div class="form-group">
<label for="issueAssignedToInput">Assigned to</label>
<input type="text" class="form-control" id="issueAssignedToInput" placeholder="Enter responsible">
</div>
<button type="button" class="btn btn-primary">Add</button>
</form>
<div class="col-lg-12">
<div id="issuesList"></div>
</div>
<div class="footer">
<p>© Ida Djurhuus</p>
</div>
<script src="http://chancejs.com/chance.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>
<script src="main.js"></script>
</body>
</html>
As #epascarello already mentioned
type="button" does not submit forms
So change the type to submit
<button type="submit" class="btn btn-primary">Add</button>
From MDN
button: The button has no default behavior. It can have client-side scripts associated with the element's events, which are triggered when the events occur.
submit: The button submits the form data to the server. This is the default if the attribute is not specified, or if the attribute is dynamically changed to an empty or invalid value.
in your code 2 problem
1) change type="button" to type="submit"
2) var issueAssignedTo = document.getElementById('issueAssigntedToInput').value;
chaneg this line in id
var issueAssignedTo = document.getElementById('issueAssignedToInput').value;
document.getElementById('issueInputForm').addEventListener('submit', saveIssue);
function saveIssue(e) {
debugger;
var issueDesc = document.getElementById('issueDescInput').value;
var issueSeverity = document.getElementById('issueSeverityInput').value;
var issueAssignedTo = document.getElementById('issueAssignedToInput').value;
var issueID = chance.guid();
var issueStatus = 'Open';
var issue = {
id: issueID,
description: issueDesc,
severity: issueSeverity,
assignedTo: issueAssignedTo,
status: issueStatus
};
if (localStorage.getItem('issues') === null) {
//var issues = [];
issues.push(issue);
localStorage.setItem('issues', JSON.stringify(issues));
} else {
var issues = JSON.parse(localStorage.getItem('issues'));
issues.push(issue);
localStorage.setItem('issues', JSON.stringify(issues));
}
document.getElementById('issueInputForm').reset();
fetchIssue();
e.preventDefault();
}
function setStatusClosed(id) {
var issues = JSON.parse(localStorage.getItem('issues'));
for (var i = 0; i < issues.length; i++) {
if (issues[i].id === id) {
issues[i].status = 'Closed';
}
}
localStorage.setItem('issues', JSON.stringify(issues));
fetchIssue();
}
function deleteIssue(id) {
var issues = JSON.parse(localStorage.getItem('issues'));
for (var i = 0; i < issues.length; i++) {
if (issues[i].id === id) {
issues.splice(i, 1);
}
}
localStorage.setItem('issues', JSON.stringify(issues));
fetchIssue();
}
function fetchIssue() {
var issues = JSON.parse(localStorage.getItem('issues'));
var issuesList = document.getElementById('issuesList');
issuesList.innerHTML = '';
for (var i = 0; i < issues.length; i++) {
var id = issues[i].id;
var desc = issues[i].description;
var severity = issues[i].severity;
var assignedTo = issues[i].assignedTo;
var status = issues[i].status;
issuesList.innerHTML += '<div class="well">' +
'<h6> Issue ID: ' + id + '</h6>' +
'<p><span class="label label-info">' + status + '</span></p>' +
'<h3>' + desc + '</h3>' +
'<p><span class="glyphicon glyphicon-time"></span>' + severity + '</p>' +
'<p><span class="glyphicon glyphicon-user"></span>' + assignedTo + '</p>' +
'Close' +
'Delete'+
'</div>';
}
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
<div class="container">
<h1>JS IssueTracker</h1>
</div class="jumbotron">
<h3>Add New Issue:</h3>
<form id="issueInputForm" >
<div class="form-group">
<label for="issueDescInput">Description</label>
<input type="text" class="form-control" id="issueDescInput" placeholder="Describe the issue...">
</div>
<div class="form-group">
<label for="issueSeverityInput">Severity</label>
<select id="issueSeverityInput" class="form-control">
<option value="Low">Low</option>
<option value="Medium">Medium</option>
<option value="High">High</option>
</select>
</div>
<div class="form-group">
<label for="issueAssignedToInput">Assigned to</label>
<input type="text" class="form-control" id="issueAssignedToInput" placeholder="Enter responsible">
</div>
<button type="submit" class="btn btn-primary">Add</button>
</form>
<div class="col-lg-12">
<div id="issuesList">
</div>
</div>
<div class="footer">
<p>© Ida Djurhuus</p>
</div>
<script src="http://chancejs.com/chance.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>
Have made few changes to your code:
Since element with type="button" cannot be associated with submit event, have changed the type as submit.
Added null check in fetchIssue function so that the code wont break when there are no issues.
Corrected a typo in the saveIssue function - document.getElementById('issueAssigntedToInput') to document.getElementById('issueAssignedToInput')
Declared variable "issues" in saveIssue function when the localStorage.getItem('issues') is null.
document.getElementById('issueInputForm').addEventListener('submit', saveIssue);
function saveIssue(e) {
var issueDesc = document.getElementById('issueDescInput').value;
var issueSeverity = document.getElementById('issueSeverityInput').value;
var issueAssignedTo = document.getElementById('issueAssignedToInput').value;
var issueID = chance.guid();
var issueStatus = 'Open';
var issue = {
id: issueID,
description: issueDesc,
severity: issueSeverity,
assignedTo: issueAssignedTo,
status: issueStatus
};
var issues = [];
if (localStorage.getItem('issues') !== null) {
issues = JSON.parse(localStorage.getItem('issues'));
}
issues.push(issue);
localStorage.setItem('issues', JSON.stringify(issues));
document.getElementById('issueInputForm').reset();
fetchIssue();
e.preventDefault();
}
function setStatusClosed(id) {
var issues = JSON.parse(localStorage.getItem('issues'));
for (var i = 0; i < issues.length; i++) {
if (issues[i].id === id) {
issues[i].status = 'Closed';
}
}
localStorage.setItem('issues', JSON.stringify(issues));
fetchIssue();
}
function deleteIssue(id) {
var issues = JSON.parse(localStorage.getItem('issues'));
for (var i = 0; i < issues.length; i++) {
if (issues[i].id === id) {
issues.splice(i, 1);
}
}
localStorage.setItem('issues', JSON.stringify(issues));
fetchIssue();
}
function fetchIssue() {
var issues = JSON.parse(localStorage.getItem('issues'));
if(typeof issues !== 'undefined' && issues !== null) {
var issuesList = document.getElementById('issuesList');
issuesList.innerHTML = '';
for (var i = 0; i < issues.length; i++) {
var id = issues[i].id;
var desc = issues[i].description;
var severity = issues[i].severity;
var assignedTo = issues[i].assignedTo;
var status = issues[i].status;
issuesList.innerHTML += '<div class="well">' +
'<h6> Issue ID: ' + id + '</h6>' +
'<p><span class="label label-info">' + status + '</span></p>' +
'<h3>' + desc + '</h3>' +
'<p><span class="glyphicon glyphicon-time"></span>' + severity + '</p>' +
'<p><span class="glyphicon glyphicon-user"></span>' + assignedTo + '</p>' +
'Close' +
'Delete'+
'</div>';
}
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Issue Tracker</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
</head>
<body onload="fetchIssue()">
<div class="container">
<h1>JS IssueTracker</h1>
</div>
<h3>Add New Issue:</h3>
<form id="issueInputForm" >
<div class="form-group">
<label for="issueDescInput">Description</label>
<input type="text" class="form-control" id="issueDescInput" placeholder="Describe the issue...">
</div>
<div class="form-group">
<label for="issueSeverityInput">Severity</label>
<select id="issueSeverityInput" class="form-control">
<option value="Low">Low</option>
<option value="Medium">Medium</option>
<option value="High">High</option>
</select>
</div>
<div class="form-group">
<label for="issueAssignedToInput">Assigned to</label>
<input type="text" class="form-control" id="issueAssignedToInput" placeholder="Enter responsible">
</div>
<button type="submit" class="btn btn-primary">Add</button>
</form>
<div class="col-lg-12">
<div id="issuesList">
</div>
</div>
<div class="footer">
<p>© Ida Djurhuus</p>
</div>
<script src="http://chancejs.com/chance.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>
<script src="main.js"></script>
</body>
</html>

Editable table not working

I made a table that you can add text to and edit it inside it.
However if you add more than three rows, It is stuck and not working anymore.
The errors comes from here:
document.getElementById('vda' + z).addEventListener('click', doSomething);
document.getElementById('cvda' + z).addEventListener('click', doSomething2);
It is only adding event listener to the last row added, so if you add more than one row. The not last row won't have a working edit button.
I checked the IDs by inspecting the edit and update buttons elements.
Try adding 3 rows then click on the edit button for one of the row.
you can look at the code here and also https://jsfiddle.net/3e6d4qsv/
<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 5px;
}
</style>
</head>
<body>
<div style="display:inline-flex;">
<form id="myForm">
<input id="inptext" type="text" placeholder="Your name..."></input>
<input id="inpadress" style="margin-left: 10px;" type="text" placeholder="Your email..."></input>
</form>
<button onclick="myFunction()"style="margin-left: 10px;" id="box">Add</button>
</div>
<br>
<div style="display: inline-flex">
<table id="tablename" style="width:80%; margin-top:15px;">
<tr>
<th>Name</th>
<th>Email</th>
</tr>
</table>
<div id="buttons" style="float:right;width: 300px; margin-top:50px;">
</div>
</div>
<script>
var z = 1;
function myFunction() {
var x = document.getElementById("inptext").value;
var y = document.getElementById("inpadress").value;
var form = document.getElementById("myForm");
form.reset();
document.getElementById("tablename").innerHTML = document.getElementById("tablename").innerHTML + '<tr><td id=acvda'+ z + '>' + x + '</td><td id=zcvda' + z + '>' + y + '</td></tr>';
var h = '<button style="margin-left:8px" class="edit" id=vda' + z + '>Edit</button>';
var f = '<div id=zzza'+z+' style=height:10px></div>';
var abc = '<button style="margin-left:-36px" class="update" id="cvda'+z+'">Update</button>';
var total = h + abc + f;
document.getElementById("buttons").innerHTML = document.getElementById("buttons").innerHTML + total;
document.getElementById('vda' + z).addEventListener('click', doSomething);
document.getElementById('cvda' + z).addEventListener('click', doSomething2);
document.getElementById('cvda' + z).style.visibility='hidden';
z = z + 1;
}
function doSomething() {
document.getElementById("inptext").value = document.getElementById("ac"+this.id).innerHTML;
document.getElementById("inpadress").value = document.getElementById("zc"+this.id).innerHTML;
document.getElementById(this.id).style.visibility='hidden';
document.getElementById('c'+this.id).style.visibility='visible';
}
function doSomething2() {
document.getElementById("a"+this.id).innerHTML = document.getElementById("inptext").value;
document.getElementById("z"+this.id).innerHTML = document.getElementById("inpadress").value;
document.getElementById(this.id).style.visibility='hidden';
form.reset();
var edit = this.id;
var edit2 = edit.replace("c", "");
document.getElementById(edit2).style.visibility='visible';
}
</script>
</body>
</html>
The following line remove all your listeners:
document.getElementById("buttons").innerHTML =
document.getElementById("buttons").innerHTML + total;
document.getElementById('vda' + z).addEventListener('click',
doSomething);
use this instead:
var div = document.createElement('div');
div.innerHTML = total;
document.getElementById("buttons").appendChild(div);

Javascript to jquery conversion

I'm trying to convert this javascript DOM into jquery, and my code isn't running for some reason. This is the DOM I am using.
document.getElementById("forma").onsubmit = function () {
var ime = document.getElementById("ime").value;
var priimek = document.getElementById("priimek").value;
var stranka = document.getElementById("stranka").value;
try {
var kandidat = Kandidat(ime, priimek, stranka);
DodajKandidataNaPolje(kandidat);
document.getElementById("seznam").innerHTML = OblikujIzpis(PridobiPolje());
document.getElementById("obvestila").innerHTML = "Uspešen Vnos!";
document.getElementById("obvestila").className = "bg-success";
}
catch (napaka) {
document.getElementById("obvestila").innerHTML = napaka.message;
document.getElementById("obvestila").className = "bg-danger";
}
document.getElementById("forma").reset();
}
document.getElementById("forma_isci").onsubmit = function () {
var iskani_niz = document.getElementById("iskalniNiz").value;
document.getElementById("seznam").innerHTML = OblikujIzpis(Isci(iskani_niz));
document.getElementById("obvestila").innerHTML = "Rezultat iskanja po iskalnem nizu " + iskani_niz;
document.getElementById("obvestila").className = "bg-info";
}
document.getElementById("pobrisi").onclick = function () {
IzbrisiPolje();
document.getElementById("obvestila").innerHTML = "Polje je bilo izbrisano!";
document.getElementById("obvestila").className = "bg-success";
document.getElementById("seznam").innerHTML = "";
document.getElementById("forma").reset();
}
This is what I tried writing in jquery.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("forma").submit(function(){
var ime=$("ime").val();
var priimek=$("priimek").val();
var stranka=$("stranka").val();
try{
var kandidat= Kandidat(ime, priimek, stranka);
DodajKandidataNaPolje(kandidat);
$("seznam").html(OblikujIzpis(PridobiPolje());
$("obvestila").html("Uspešen Vnos!");
$("obvestila").addClass("bg-success");
}
catch(napaka){
$("obvestila").html(napaka.message);
$("obvestila").addClass("bg-danger");
}
$("forma").reset();
$("forma_isci").submit=function(){
var iskani_niz=$("iskaniNiz").val();
$("seznam").html(OblikujIzpis(iskani_niz));
$("obvestila").html("Rezultat iskanja po iskalnem nizu " + iskani_niz);
$("obvestila").addClass("bg-info");
}
$("pobrisi".click=function(){
IzbrisiPolje();
$("obvestila").html("Polje je bilo izbrisano!");
$("obvestila").addClass("bg-success");
$("seznam").html("");
$("forma").reset();
}
}
});
});
</script>
here is my HTML file
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
<script src="funkcije.js"></script>
<script src="dom.js"></script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<title>JavaScript - DOM</title>
</head>
<body>
<div class="container">
<h1>Seznam predsedniških kandidatov!</h1>
<form action="#" id="forma_isci" class="form-inline">
<div class="form-group">
<input type="text" class="form-control" id="iskalniNiz" placeholder="Iskalni niz">
</div>
<button type="submit" class="btn btn-info">Išči</button>
</form>
<br />
<br />
<h3>Vnos novih kandidatov</h3>
<form action="#" id="forma" class="form-group">
<table class="table">
<tr>
<td>Ime:</td>
<td>
<input type="text" id="ime" placeholder="Ime kandidata" class="form-control" />
</td>
</tr>
<tr>
<td>Priimek:</td>
<td>
<input type="text" id="priimek" placeholder="Priimek kandidata" class="form-control" />
</td>
</tr>
<tr>
<td>Stranka:</td>
<td>
<select id="stranka" class="form-control" >
<option>Demokratska</option>
<option>Republikanska</option>
<option>Neodvisna</option>
</select>
</td>
</tr>
<tr>
<td>
<input type="submit" value="Dodaj" class="btn btn-info" />
</td>
<td>
<input type="reset" value="Ponastavi" class="btn btn-info" />
</td>
</tr>
</table>
</form>
<br />
<br />
<p id="obvestila"></p>
<br />
<br />
<h3>Seznam obstoječih kandidatov</h3>
<ul id="seznam" class="list"></ul>
<button class="btn" id="pobrisi">Pobriši seznam</button>
</div>
</body>
</html>
So anyway, I'm not going to post the functions here since they're not needed to be seen here.
The javascript code works, the site works then and the elements get added normally. But I would like to have the same effect but written in Jquery. I think some of the issues are in .className, which I replaced with .Addclass from jquery and .innerHTML where I write .html(function). If someone could convert this for me it would be great, since I am kinda new to jquery I'm having some issues.
update n1*
changed the Jquery to this
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script>
$(document).ready(function(){
$("#forma").submit(function(){
var ime=$("#ime").val();
var priimek=$("#priimek").val();
var stranka=$("#stranka").val();
try{
var kandidat= Kandidat(ime, priimek, stranka);
DodajKandidataNaPolje(kandidat);
$("#seznam").html(OblikujIzpis(PridobiPolje());
$("#obvestila").html("Uspešen Vnos!");
$("#obvestila").myClass("bg-success");
}
catch(napaka){
$("#obvestila").html(napaka.message);
$("#obvestila").myClass("bg-danger");
}
$("#forma").reset();
}
$("#forma_isci").submit=function(){
var iskani_niz=$("#iskaniNiz").val();
$("#seznam").html(OblikujIzpis(iskani_niz));
$("#obvestila").html("Rezultat iskanja po iskalnem nizu " + iskani_niz);
$("#obvestila").myClass("bg-info");
}
$("#pobrisi".click=function(){
IzbrisiPolje();
$("#obvestila").html("Polje je bilo izbrisano!");
$("#obvestila").myClass("bg-success");
$("#seznam").html("");
$("#forma").reset();
}
}
});
});
</script>
Added the # where there's an ID, and changed .addClass to .myClass. Add function is still not working. But some other functions are working.
The functions.
var polje = [];
function Kandidat(ime, priimek, stranka) {
if (ime ==="" || priimek === "") {
throw new Error("Podatki niso popolni!");
}
else {
var id = polje.length + 1;
var oseba = {id:id, ime:ime, priimek:priimek, stranka:stranka};
oseba.Izpis = function () {
return "(" + this.id + ")" + this.ime + " " + this.priimek + " pripada stranki " + this.stranka;
}
return oseba;
}
}
function DodajKandidataNaPolje(kandidat) {
polje.push(kandidat);
return true;
}
function PridobiPolje() {
return polje;
}
function OblikujIzpis(polje) {
var izpis = "";
for (var i = 0; i < polje.length; i++) {
izpis = izpis + "<li>" + polje[i].Izpis() + "</li>";
}
return izpis;
}
function Isci(iskalniNiz) {
var rezultat = [];
var oseba;
var vsebuje;
for (var i = 0; i < polje.length; i++) {
oseba = polje[i];
vsebuje = oseba.ime.search(iskalniNiz);
if (vsebuje != -1) {
rezultat.push(oseba);
}
else{
vsebuje = oseba.priimek.search(iskalniNiz);
if (vsebuje != -1) {
rezultat.push(oseba);
}
else{
vsebuje = oseba.stranka.search(iskalniNiz);
if (vsebuje != -1) {
rezultat.push(oseba);
}
}
}
}
return rezultat;
}
function IzbrisiPolje() {
polje = [];
return true;
}
in jQuery, in order to access an element, you need to use a selector. In your case, the form has an id of forma (which in jQuery selectors, you prefix it with #). In order to access your form, you need to do the following:
change this:
$("forma").submit(function(){
to this:
$("#forma").submit(function(){
Anywhere else you use jQuery to access an element in your code would have to be changed as well. use #myid for ids, .myclass for classes. See this for more information.
Here is your code (jQuery section only) with some things fixed:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var forma = $('#forma');
forma.submit(function(){
var ime=$("#ime").val();
var priimek=$("#priimek").val();
var stranka=$("#stranka").val();
try{
var kandidat= Kandidat(ime, priimek, stranka);
DodajKandidataNaPolje(kandidat);
$("#seznam").html(OblikujIzpis(PridobiPolje());
$("#obvestila").html("Uspešen Vnos!");
$("#obvestila").addClass("bg-success");
} catch(napaka){
$("#obvestila").html(napaka.message);
$("#obvestila").addClass("bg-danger");
}
forma[0].reset();
});
$("#forma_isci").submit(function(){
var iskani_niz=$("#iskaniNiz").val();
$("#seznam").html(OblikujIzpis(iskani_niz));
$("#obvestila").html("Rezultat iskanja po iskalnem nizu " + iskani_niz);
$("#obvestila").addClass("bg-info");
});
$("#pobrisi").click(function( ){
IzbrisiPolje();
$("#obvestila").html("Polje je bilo izbrisano!");
$("#obvestila").addClass("bg-success");
$("#seznam").html("");
forma[0].reset();
});
});
</script>

To validate dynamic elements in the table

I want to validate the dynamically created textarea, In the below mentioned code i can able to validate only the first row but i can't validate for the second row.How to validate/get all the row values.
Thanks in advance.
To create Dynamic elements click add question image.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title> new document </title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.1/jquery-ui.js"></script>
<script type="text/javascript">
$(document).ready(function ()
{
var i = 0;
$("#AddQuestion").click(function ()
{
$("#NoQuestions").remove();
++i;
var IdCount = i + ".)";
var newRowContent = "<tr id='SQRow"+i+"'"+" ><td>" + IdCount + "</td>" + "<td><textarea id='txtQuestions" + i + "'" + "style='height: 45px;width: 420px'></textarea> </td>" + "<td><select id='ddlDataType" + i + "'" + " style='margin-left: 47px'><option value=''>Select Data Type</option><option value='int'>Numeric</option><option value='Varchar'>Alpha Numeric</option></select> </td>" + "<td><div ><a href='#'><img src='/Images/1363247672_document-edit.png' width='26' height='27' alt='EditButton'/> </a><a href='#'><img src='/Images/1363247321_Remove.png' alt='DeleteButton'/></a> </div> </br><div style='display: none'><a href='#'><img src='/Images/Accept-iconSmall.png' width='26' height='27' alt='UpdateButton'/></a><a href='#'><img src='/Images/Button-Cancel-icon.png' width='26' height='27' alt='CancelButton' /></a></td>" + "</tr>";
$("#tblSecurityQuestions").append(newRowContent);
});
$("#btnUpdateQuestions").click(function ()
{
var txtAreaVal = $('textarea').val().length;
var ddlDataType = $('#tblSecurityQuestions select').val().length;
alert(txtAreaVal);
alert(ddlDataType + "The ddl is " );
if (txtAreaVal <= 0)
{
alert('Please add Questions');
return;
} else if (ddlDataType <= 0)
{
alert('Please select the data type');
return;
}
});
});
</script>
</head>
<body>
<form id="SQPageForm" name="SQPageForm" method="post" action="">
<div id="SecurityQuestions" style="height: auto;border-color: #f00;border: 1.5px;border-style: dotted">
<h3>Configure Security Questions</h3>
<div id="AddNewSecurityQuestions" style="">
<p style="float: left;margin-top: 11px">Add Question </p>
<img id="AddQuestion" src="/Images/document-add-icon.png" alt="Add Questions" width="35px" height="35px" style="cursor: pointer"/>
</div>
</br>
Security Questions?
</br>
<table border="1" id="tblSecurityQuestions">
<tr>
<th style="width: 25px">
ID
</th>
<th style="width: 424px">
Security Questions
</th>
<th style="width: 210px">
DataType
</th>
<th style="width :65px">
Actions
</th>
</tr>
</table>
</div>
</br>
</br>
<input type="button" id="btnUpdateQuestions" value="Set Security Question" style="margin-left: 300px" />
</body>
</html>
Try
$("#btnUpdateQuestions").click(function() {
$('#tblSecurityQuestions tr:gt(0)').each(function() {
var $this = $(this);
var txtAreaVal = $('textarea', $this).val().length;
var ddlDataType = $('select', $this).val().length;
alert(txtAreaVal);
alert(ddlDataType + "The ddl is ");
if (txtAreaVal <= 0) {
alert('Please add Questions');
return;
} else if (ddlDataType <= 0) {
alert('Please select the data type');
return;
}
})
});
var textAreaSize = $('#tblSecurityQuestions tr:gt(1)').size();
for (var j = 1; j <= textAreaSize; j++)
{
var txtAreaVal = $('#txtQuestions' + j).val();
var ddlDataType = $('#ddlDataType' + j).val();
if (txtAreaVal <= 0)
{
alert('Please add Questions');
return;
} else if (ddlDataType <= 0)
{
alert('Please select the data type');
return;
}
}
I came up with a solution, it is working for me now
Try to iterate all text areas, then check the same condition:
for(var i=0; i<NoOfquestions; i++){
var txtAreaVal = $('#txtQuestions'+i).val().length;
var ddlDataType = $('#tblSecurityQuestions select').val().length;
alert(txtAreaVal);
alert(ddlDataType + "The ddl is");
if (txtAreaVal <= 0)
{
alert('Please add Questions');
return;
}
else if (ddlDataType <= 0)
{
alert('Please select the data type');
return;
}
}

Categories