To validate dynamic elements in the table - javascript

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;
}
}

Related

How to check if the function has executed completely and store completed flag in global variable in JavaScript

When a user clicks on the Break button, it executes the Break() function inside the JS. It then calls getData() and also 2 lines of code after getData with CSS. But if you see that 2 CSS btnLock which use to hide lock.png and btnUnlock which displays unlock.png. it is not waiting for getData() to complete and these 2 CSS is getting overridden with what we have in buildTable(). So the option I am looking for is to build the datatable medTable.draw() first and then check if the Break() has completed. If so, then use these 2 CSS to hide and display.
So for that, I want to use the global boolean variable to store the status of the Break function. I mean whether it completed or not so that I can use it after medTable.draw(); to check the Break function completed.
Index
<div id="breakDialog" style="display: none;">
<fieldset class="bd">
<div class="label"><label for="OverrideReason">Reason <em>*</em></label></div>
<option value="other">
Other
</option>
</div>
</div>
<div class="value">
<textarea id="OverrideComment" style="width: 400px; height: 100px;"></textarea>
</div>
</div>
<div class="ft">
<span class="yui-primary-button yui-push-button" id="override-button"><span class="first-child"><button tabindex="0" id="override-button-button" type="button" onClick="break();">Break </button></span></span>
</div>
</div>
<table style="border: none; padding-bottom: 20px;">
<tr>
<td nowrap="nowrap" style="padding-top: 2px;">
<p><span id="btnUnlock" style="display: none; font-family: arial"><input type="image" src="~/icons/unlock.png" alt="unlock" width="20" height="20" />Unlocked.</span></p>
<p><span id="btnLock" style="display: none; font-family: arial"><input type="image" src="~/icons/lock.png" alt="lock" width="20" height="20" />Locked</span></p>
</td>
</tr>
</table>
JavaScript
function break() {
if (validatePrivacyDialog()) {
$.ajax({
type: "POST",
url:breakUrl,
data: JSON.stringify({
reason: $('#OverrideReason').val(),
comment: $('#OverrideComment').val()
}),
success: function () {
var jsStartDate = moment($("#startDatePicker").val(), momentStartDateFormat).toDate();
var jsEndDate = moment($("#endDatePicker").val(), momentEndDateFormat).toDate();
getData(jsStartDate, jsEndDate);
$("#breakDialog").dialog('close');
$("#btnLock").css("display", "none");
$("#btnUnlock").css("display", "block");
},
contentType: "application/json"
});
}
}
////////////////////////////////////
function getData(startDate, endDate) {
medTable.clear().draw();
...
}).done(function (data) {
if (medArray != null & medArray.length > 0) {
if (requestsProcessed === pageData.Number) {
buildTable(medTable, medicationArray);
}
}
}
///////////////////////////////////////
function buildTable(medTable, medData) {
var dataLength = medData.length;
for (var key = 0; key < dataLength; key++) {
totalMedCount = totalMedCount + 1;
var med = medData[key];
var iconHTML = "<input class='cssUnlock' type='image' src='" + pathPrefix + "icons/information.png' alt='defaultInfo' width='20' height='20'></input>";
if (med.BlnFlag)
iconHTML = "<input class='cssUnlock' type='image' src='" + pathPrefix + "icons/information-red.png' alt='redInfo' width='20' height='20'></input>";
if (med.Lock === "Yes") {
iconHTML = "<input class='cssLock' type='image' src='" + pathPrefix + "icons/lock.png' alt='defaultLock' width='20' height='20'></input>";
if (med.BlnFlag)
iconHTML = "<input class='cssLock' type='image' src='" + pathPrefix + "icons/lock-red.png' alt='redLock' width='20' height='20'></input>";
$("#btnLock").css("display", "block");
}
else {
if (med.ViewConsent === "No") {
$("#btnUnlock").css("display", "block");
iconHTML = "<input class='cssUnlock' type='image' src='" + pathPrefix + "icons/unlock.png' alt='defaultUnlock' width='20' height='20'></input>";
if (med.BlnFlag)
iconHTML = "<input class='cssUnlock' type='image' src='" + pathPrefix + "icons/unlock-red.png' alt='redUnlock' width='20' height='20'></input>";
}
}
var blnViewConsent = (ViewConsent === "Yes") ? "Yes" : "No";
medTable.row.add([
med.Id,
med.Lock == "Yes" ? "" : med.DispenseTotal,
"<a>" + med.ItemStatus + "</a>",
med.MedTableHtml,
blnViewConsent,
med.MedTableHtml,
medicationUrl,
iconHTML
]);
}
medTable.draw();
$("#totalItemsElement").text(totalMedicationCount);
}
If you want to make sure
$("#btnLock").css("display", "none");
$("#btnUnlock").css("display", "block");
will not be overridden by css in buildTable().You can change getData like this:
function getData(startDate, endDate) {
medTable.clear().draw();
...
}).done(function (data) {
if (medArray != null & medArray.length > 0) {
if (requestsProcessed === pageData.Number) {
buildTable(medTable, medicationArray);
$("#btnLock").css("display", "none");
$("#btnUnlock").css("display", "block");
}
}
}
After buildTable(medTable, medicationArray);,it will change css.So that even the css in Break() will be overridden,the css in getData() will not.

Using input value with onkeyup to innerHTML a div

i have been watching some questions here about the same topic but i cant make my code works with the solutions,
I have a dynamic tr table, what i want to do is when i write on the last input of each row a div "result" overwrite like the values, that because i want to make later a connection that shows me users name on my db, like a data live search
JS
function createTable() {
var a;
var r;
a = document.getElementById('tb1').value;
var length = document.getElementById('table').rows.length;
if (a == "") {
alert("Please enter some numeric value");
} else {
var change = document.getElementById("trow1").style.visibility = 'visible';
//var change = document.getElementById("trow2").style.visibility = 'visible';
var changet = document.getElementById("table").style.visibility = 'visible';
var rows = "";
for (var i = 0; i < a; i++) {
r=i+length;
let tr = document.createElement("tr");
tr.innerHTML = "<td>"+r+"</td><td><input type='text' id='" + "parameter".concat(r) + "'></td><td id='tdlmin'><input type='text' id='" + "lmin".concat(r) + "'></td><td id='tdlmax'><input type='text' id='" + "lmax".concat(r) + "'></td><td><input type='text' id='" + "level".concat(r) + "'></td><td><select id='" + "relcal".concat(r) + "' style='width:100%;'><option value='NA'>NA</option><option value='SI'>SI</option></select></td><td><input type='text' id='" + "comment".concat(r) + "' cols=100></td><td><input type='text' id='" + "procown".concat(r) + "' onkeyUp='document.getElementById('result').innerHTML = this.value;'></div></td>";
document.getElementById("table").appendChild(tr);
}
}
}
HTML
<div class="container-fluid">
<div class="row align-items-start">
<div class="col-9">
Numero de Parametros: <input type="text" id="tb1"/>
<button type="button" onclick='createTable()'>Crear</button>
<table id="table" class="order-table table" name="table1" required style="visibility:hidden;">
<tr id="trow1" style="visibility:hidden; text-align: center;"><td>#</td><td>Parametro</td><td colspan="2"><table><tr><td colspan="2">Limite</td></tr><tr><td>Min.</td><td>Max.</td></tr></table></td><td><table style="width: 100%;"><tr><td>Nivel</td></tr><tr><td>1 - 4</td></tr></table></td><td>Relevante Calidad</td><td>Comentario</td><td>Dueño del Proceso</td></tr>
</table>
<button type="button" onclick='subir()'>Subir Parametros</button>
</div>
<div class="col-3">
<div id="result" name="result"></div>
</div>
</div>
</div>
Edit:
This is what i have tried yet:
$('"'+procownid+'"').on("keyup",function(){
var userlike = document.getElementById(procownid).value;
alert(userlike);
});
$("#table tr").on('keyup', procownid, function({
var userlike = document.getElementById(procownid).value;
alert(userlike);
result.innerHTML="<p>"+userlike+"</p>"
});
alert(userlike);
document.getElementById('result').innerHTML="<p>userlike:"+uselike+"</p>";
$.post('getUser',{accion:"ListarUserTPMD",userlike:userlike}, function(data){
result.innerHTML=data;
});
my question is, i can get that when i write on the input it trigger the onkeyup and show me for example the input.value, why i cant make it write on the div?

cant print rows in javascript when array is used

I am making a web page using HTML and js following is the code for that,
essentially I want to store the numbers generated by function and show it in column 6, so I am storing it in the array a and show it in column 6. But when I write to add the number for loop stops right there and control exits from the loop. ie. only one row and one column is displayed like
uid day time source destination bus
2
rand.html
<!DOCTYPE html>
<head>
<script type="text/javascript">
var abc = 0;
a = new Array();
var b = 0;
//Returns a random number
function CreateLottoValues()
{
return Math.floor(Math.random() * 20 + 1);
}
//create table
function UpdateTable()
{
document.write("<table border=1 id='myTable' > ")
document.write(" <tr><td > uid</td><td > day</td><td
> time</td><td > source</td><td > destination</td> <td
> bus</td></tr> ")
for (row=2; row<=30; row++) {
document.write("<tr>")
for (col=1; col<=6; col++) {
if(col==1){
document.write("<td >" +row+ "</td>")
}
else if(col==6){
for (var i = 0; i <= a.length; i++) {
document.write("<td>" + a[i] +"</td>")
}
}
else{
abc = CreateLottoValues();
a.add(abc);
//tmp =row + col;
//document.getElementById(tmp).innerHTML = CreateLottoValues();
document.write("<td >" + abc + "</td>")
}
}
document.write("</tr>")
}
document.write("</table>")
}
</script>
</head>
<body>
<center>
<div id="container">
<div id="header">
<h1>Welcome</h1>
<p id="demo"></p>
</div>
</div>
<input id="btn" type="button" value="Re-generate Numbers"
onClick="UpdateTable()" />
</center>
</body>
</html>
Can anyone help me? thank you for your suggestions.
On closer inspection, I found that your program won't run correctly because of this line:
a.add(abc);
This is because the variable a is an array, and to add elements to an array you use the push function
Replace a.add(abc) with a.push(abc). I've also made a few other changes which you can understand by comparing this with your code:
<!DOCTYPE html>
<head>
<script type="text/javascript">
var abc = 0;
a = new Array();
var b = 0;
//Returns a random number
function CreateLottoValues()
{
return Math.floor(Math.random() * 20 + 1);
}
//create table
function UpdateTable()
{
document.write("<table border=1 id='myTable' > ")
document.write(" <tr><td > uid</td><td > day</td><td> time</td><td > source</td><td > destination</td> <td> bus</td></tr> ")
for (row=2; row<=30; row++) {
document.write("<tr>")
for (col=1; col<=6; col++) {
if(col==1){
document.write("<td >" +row+ "</td>")
}
else if(col==6){
document.write("<td>");
for (var i = 0; i < a.length; i++) {
document.write(a[i])
}
document.write("</td>");
a = new Array();
}
else{
abc = CreateLottoValues();
a.push(abc);
//tmp =row + col;
//document.getElementById(tmp).innerHTML = CreateLottoValues();
document.write("<td >" + abc + "</td>")
}
}
document.write("</tr>")
}
document.write("</table>")
}
</script>
</head>
<body>
<center>
<div id="container">
<div id="header">
<h1>Welcome</h1>
<p id="demo"></p>
</div>
</div>
<input id="btn" type="button" value="Re-generate Numbers"
onClick="UpdateTable()" />
</center>
</body>
</html>

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>

HTML input value append to a bootstrap table

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

Categories