I am stuck in a problem where I have to create text boxes dynamically into the table cell. Along with the data which I am fetching from the DB.
It should be something like:
Number of rows are dynamic and I am able to generate it using Array. I am capturing all values into the array of records for each row and pushing it into the table. But I don't know what to do to add empty text boxes.
I was thinking if I can add "textboxes" to the array and insert along with text to the table cell. I am not sure what other options available.
I am open to answer any queries to you which might help me to get the answer.
EDIT:
Below is the code which I used to generate table:
function generateTable(fundDetails){
var tbody_holder = document.getElementById("tbody_holder");
for(var row = 0; row < fundDetails.length; row++){
var tr = document.createElement("tr");
for(var col = 0; col < fundDetails[row].length; col++){
var td = document.createElement("td");
var tn = document.createTextNode(fundDetails[row][col]);
td.appendChild(tn);
tr.appendChild(td);
}
tbody_holder.appendChild(tr);
}
}
fundDetail is a 2D array. Each element in array contains all the data for the one row of table. Next array element contains data for next row. I want to insert text boxes in each rows.
TIA
I think it will be your answer for creating the records dynamically.
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Cache-control" content="no-cache">
<script src="jquery/jquery-1.10.2.js"></script>
<script src="jquery/canvasjs.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="bootstrap/css/bootstrap.css">
<link rel="stylesheet" href="font-awesome/css/font-awesome.css">
<script src="jquery/jquery-ui.js"></script>
<script type="text/javascript" src="jquery/html2canvas.min.js"></script>
<script type="text/javascript" src="jquery/jquery.plugin.html2canvas.js"></script>
<link rel="stylesheet" href="jquery/jquery-ui.css">
<style>
input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
-webkit-appearance: none;
margin: 0;
}
input[type="text"], input[type="number"] {
border: none;
}
tbody tr{
background:#f7f7f7;
}
.navbar{
border-radius:0px !important;
border:none;
}
thead{
background:#8b99a0;
color:white;
}
.navbar{
background:#323E4E;
}
table{
border-radius:4px !important;
}
a.canvasjs-chart-credit {
display: none;
}
#chartContainer{
border-bottom:1px dashed #8b99a0;
border-right:1px dashed #8b99a0;
}
.stuck{
position:fixed;
z-index:100;
width:100%;
top:0;
}
hr {
margin-top: 0px;
margin-bottom: 0px;
}
</style>
<script>
$(window).scroll(function() {
if ($(window).scrollTop() > 50) {
$("#bar").addClass('stuck');
} else {
$('#bar').removeClass('stuck');
}
});
</script>
</head>
<body>
<nav class="navbar navbar-inverse" id="bar">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<img src="images/records.png" style="width:50px;height:45px;float:left;" class="navbar-logo">
<a class="navbar-brand" href="#" title="calculation">Student Records</a>
</div>
</div>
</nav>
<div class="container">
<div class="row">
<div class="col-md-12">
<h2 style="text-align:center;color: #323E4E;">Student marksheet</h2>
</div>
<div class="col-md-12" style="margin-bottom:2px;">
<div class="col-md-2">
<button class="btn btn-primary" id="addbtn" style="float:left;margin-right:10px;"><i class="fa fa-user-plus" aria-hidden="true"></i> Add Row</button>
</div>
<div class="col-md-8">
<div class="form-group">
<input type="text" class="search form-control" id="search" placeholder="What you looking for?" style="box-shadow:5px 5px 5px #f7f7f7;">
</div>
</div>
<div class="col-md-2">
<button class="btn btn-primary" id="btnExport" style="float:right;"><a style="text-decoration:none;color:#fff;"><i class="fa fa-download"></i> Download</span></a></button>
</div>
</div>
<div class="col-md-12" style="margin-bottom:30px !important;">
<div class="col-md-10">
<div id="dvData">
<table class="table table-hover" id="tblData">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Mark1</th>
<th>Mark2</th>
<th>Total</th>
<th>Average</th>
<th>Status</th>
</tr>
</thead>
<tbody id="frm">
</tbody>
</table>
</div>
</div>
<div class="col-md-2">
<label>Result Chart</label>
<hr>
<div id="chartContainer" style="width:100%;height:200px;"></div>
</div>
</div>
</div>
</div>
</body>
<script>
var aa=0, z=1, numb=1, id="ping";
var x, ab ,bc,cd,tr,ty,tg,we ,er;
var id1,id2,id0,stat="mark",num="1";
var mnc="avg",mno="total", abcd=1;
var msg="status",pa=0,fa=0, stanum;
$("#addbtn").click(function(e){
var i=aa;
var zz=z+aa;
for(i;i<zz;i++){
var head= document.createElement("TR");
ab="tear";
bc=zz;
cd=ab.concat(bc);
head.setAttribute("id",cd);
document.getElementById("frm").appendChild(head);
var did= document.createElement("TD");
var pin=id.concat(numb);
did.setAttribute("id",pin);
document.getElementById(cd).appendChild(did);
document.getElementById(pin).innerHTML=numb;
numb++;
for(var p=0;p<6;p++){
if(p<3){
var lab= document.createElement("TD");
tr="tead";
ty=p;
we=zz;
er=tr.concat(ty);
tg=er.concat(we);
lab.setAttribute("id",tg);
document.getElementById(cd).appendChild(lab);
}else if(p==3)
{
var lab= document.createElement("TD");
tr="tead";
ty=p;
we=zz;
er=tr.concat(ty);
tg=er.concat(we);
lab.setAttribute("id",tg);
var ctot=mno.concat(abcd);
lab.setAttribute("id",ctot);
document.getElementById(cd).appendChild(lab);
}else if(p==4)
{
var lab= document.createElement("TD");
tr="tead";
ty=p;
we=zz;
er=tr.concat(ty);
tg=er.concat(we);
lab.setAttribute("id",tg);
var cpo=mnc.concat(abcd);
lab.setAttribute("id",cpo);
document.getElementById(cd).appendChild(lab);
}else if(p==5)
{
var lab= document.createElement("TD");
var meg=msg.concat(i);
lab.setAttribute("id",meg);
document.getElementById(cd).appendChild(lab);
}
if(p==0)
{
x= document.createElement("INPUT");
x.setAttribute("type","text");
id0=stat.concat(num);
num++;
x.setAttribute("id",id0);
document.getElementById(tg).appendChild(x);
}else if(p==1)
{
x= document.createElement("INPUT");
x.setAttribute("type","number");
id1=stat.concat(num);
num++;
x.setAttribute("id",id1);
document.getElementById(tg).appendChild(x);
}else if(p==2)
{
x= document.createElement("INPUT");
x.setAttribute("type","number");
id2=stat.concat(num);
num++;
x.setAttribute("id",id2);
document.getElementById(tg).appendChild(x);
}
}
}
abcd++;
aa++;
});
var xx;
$("#tblData").change(function(e){
var n=1;var qq=0;xx=0;
for(var rr=1;rr<=aa;rr++){
var m0=stat.concat(n);
n++;
var m1=stat.concat(n);
n++;
var m2=stat.concat(n);
n++;
var az=document.getElementById(m0).value;
document.getElementById(m0).innerHTML=az;
var a=document.getElementById(m1).value;
document.getElementById(m1).innerHTML=a;
var b=document.getElementById(m2).value;
document.getElementById(m2).innerHTML=b;
if(a=="")
{
a=0;
}else if(b==""){
b=0;
}
else{}
var c=Number(a)+Number(b);
var d=(Number(a)+Number(b))/2;
var mp=mno.concat(rr);
document.getElementById(mp).innerHTML=c;
var cp=mnc.concat(rr);
document.getElementById(cp).innerHTML=d;
stanum=msg.concat(qq);
if((a<50)||(b<50)){
document.getElementById(stanum).innerHTML="Fail";
qq++;
}else{
document.getElementById(stanum).innerHTML="Pass";
qq++;
}
}
xx=qq;
});
$("#tblData").change(function(e){
fa=0,pa=0;
var county=$('#tblData tr').length;
for(var mob=0;mob<county-1;mob++){
var mom=msg.concat(mob);
if(document.getElementById(mom).innerHTML=="Pass"){
pa++;
}
if(document.getElementById(mom).innerHTML=="Fail"){
fa++;
}
}
var chart = new CanvasJS.Chart("chartContainer",
{
animationEnabled: true,
title:{
text: "students vs pass / fail"
},
data: [
{
type: "column", //change type to bar, line, area, pie, etc
dataPoints: [
{ label: "pass", y: pa },
{ label: "fail", y: fa }
]
}
]
});
chart.render();
});
</script>
<script type="text/javascript">
$("#resbtn").click(function(e){
html2canvas($("#tblData"), {
onrendered: function(canvas) {
theCanvas = canvas;
canvas.toBlob(function(blob) {
saveAs(blob, "pretty image.png");
});
}
});
});
</script>
<script>
$(document).ready(function()
{
$('#search').keyup(function()
{
searchTable($(this).val());
});
});
function searchTable(inputVal)
{
var table = $('#tblData');
table.find('tr').each(function(index, row)
{
var allCells = $(row).find('td');
if(allCells.length > 0)
{
var found = false;
allCells.each(function(index, td)
{
var regExp = new RegExp(inputVal, 'i');
if(regExp.test($(td).text()))
{
found = true;
return false;
}
});
if(found == true)$(row).show();else $(row).hide();
}
});
}
</script>
<Script>
$("#btnExport").click(function (e) {
var dt = new Date();
var day = dt.getDate();
var month = dt.getMonth() + 1;
var year = dt.getFullYear();
var hour = dt.getHours();
var mins = dt.getMinutes();
var postfix = day + "." + month + "." + year + "_" + hour + "." + mins;
//creating a temporary HTML link element (they support setting file names)
var a = document.createElement('a');
//getting data from our div that contains the HTML table
var data_type = 'data:application/vnd.ms-excel';
var table_div = document.getElementById('dvData');
var table_html = table_div.outerHTML.replace(/ /g, '%20');
a.href = data_type + ', ' + table_html;
//setting the file name
a.download = 'exported_table_' + postfix + '.xls';
//triggering the function
a.click();
//just in case, prevent default behaviour
e.preventDefault();
});
</script>
</html>
Related
I wrote my code in Bootstrap v3, however, upon realising that it doesn't support Spinners and many of the CSS elements I've envisioned didn't have the style that I wanted, I want to switch to Bootstrap v4. I added all of the required scripts / css links to the head, however I noticed that one whole table from my code has frankly just disappeared. And I have no idea why. The table is on a separate html element, and works in Bootstrap v3 but not sure why it's not displaying with v4.
Code:
main2.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js"></script>
<style>
</style>
</head>
<body>
<div id="header" style="background-color: white; width:100%; height:auto; position:fixed;">
<p id="statusText">Preparing supermarkets from Google Drive...</p>
<div id="form-group">
<input type="text" class="form-control" id="searchInput" placeholder="Search by Name or ID of Supermarket"/>
</div>
</div>
<!-- <div class="d-flex justify-content-center align-items-center" style="visibility:hidden;">
<div class="spinner-border" id="spinner" role="status">
</div> -->
</div>
<div class="container">
<div id="addsupermarket" style="" class=""></div>
</div>
<div id="foot" style="background-color:white; width:100%; height:auto; position:fixed; top:447px;">
<button type="button" class="btn btn-primary" style="float:right;" id="btnAdd">Add Supermarkets</button>
</div>
<script>
var data;
var checkedItems = new Map();
function loadView(options) {
var id = typeof options.id === "undefined" ? "addsupermarket" : options.id;
var cb = typeof options.callback === "undefined" ? function(){} : options.callback;
google.script.run.withSuccessHandler(function(html) {
document.getElementById("addsupermarket").innerHTML = html;
typeof options.params === "undefined" ? cb() : cb(options.params);
})[options.func]();
}
function setDataForSearch() {
checkedItems = new Map();
showSpinner();
document.getElementById("statusText").innerHTML = "Loading..."
google.script.run.withSuccessHandler(function(dataReturned) {
data = dataReturned.slice();
var searchResultsBox = document.getElementById("searchResults");
var templateBox = document.getElementById("rowTemplate");
var template = templateBox.content;
data.forEach(function(r) {
var tr = template.cloneNode(true);
var supermarketCheckColumn = tr.querySelector(".supermarketCheck");
var supermarketNameColumn = tr.querySelector(".supermarketName");
var supermarketIDColumn = tr.querySelector(".supermarketID");
var supermarketStatusColumn = tr.querySelector(".supermarketStatus");
var supermarketCheckbox = tr.querySelector(".supermarketCheckbox");
supermarketNameColumn.textContent = r[0];
supermarketIDColumn.textContent = r[1];
supermarketStatusColumn.textContent = r[2];
supermarketCheckbox.dataset.supermarketID = r[1];
searchResultsBox.appendChild(tr);
});
document.getElementById("statusText").innerHTML = "Found " + data.length + " results";
hideSpinner();
}).getDataForSearch();
}
function loadAddSupermarketView() {
loadView({func: "loadAddSupermarketView", callback: setDataForSearch});
}
loadAddSupermarketView();
document.getElementById("searchInput").addEventListener("input", inputEventHandler);
function inputEventHandler(e) {
if (e.target.matches("#searchInput")) {
search();
}
}
function showSpinner() {
document.getElementById("spinner").style.visibility = "visible";
}
function hideSpinner() {
document.getElementById("spinner").style.visibility = "hidden";
}
function search() {
var searchInput = document.getElementById("searchInput").value;
var resultsArray = data.filter(function(r) {
return (r[0].toString().toLowerCase().indexOf(searchInput.toString().toLowerCase()) !== -1 || (r[1].toString().indexOf(searchInput.toString()) !== -1));
});
document.getElementById("statusText").innerHTML = "Loading..."
var searchResultsBox = document.getElementById("searchResults");
var templateBox = document.getElementById("rowTemplate");
var template = templateBox.content;
searchResultsBox.innerHTML = "";
resultsArray.forEach(function(r) {
var tr = template.cloneNode(true);
var supermarketCheckbox = tr.querySelector(".supermarketCheckbox");
var supermarketCheckColumn = tr.querySelector(".supermarketCheck");
var supermarketNameColumn = tr.querySelector(".supermarketName");
var supermarketIDColumn = tr.querySelector(".supermarketID");
var supermarketStatusColumn = tr.querySelector(".supermarketStatus");
supermarketCheckbox.dataset.supermarketID = r[1];
supermarketNameColumn.textContent = r[0];
supermarketIDColumn.textContent = r[1];
supermarketStatusColumn.textContent = r[2];
searchResultsBox.appendChild(tr);
});
document.getElementById("statusText").innerHTML = "Found " + resultsArray.length + " results";
}
</script>
</body>
</html>
addsupermarket.html (which contains the table)
<table class="table">
<thead>
<tr>
<th scope="col">Add?</th>
<th scope="col">Name</th>
<th scope="col">ID</th>
<th scope="col">Status</th>
</tr>
</thead>
<tbody id="searchResults">
</tbody>
</table>
Im really new with coding. Hopefully you can help me. Really appreciate it.
So I have a modal that is supposed to pass the value to a JS table. The modal has a drop down bar and a text field. the drop down got its values from a passed json via document.getElemetById. So I want to pass the chosen value from the dropdown and the value of the text field to the JS table.
so I've also tried this and does not work.
function trigData() {
var table = document.getElementById('container-2');
var i;
for (var i = 0; i < 2; i++){
var tr = document.createElement('tr');
var td1 = document.createElement('td');
var td2 = document.createElement('td');
td1.setAttribute("id", "equipment");
td2.setAttribute("id", "quantity");
}
var text1 = document.getElementById("equipment").innerHTML = td1.value;
var text1 = document.getElementById("equipment").innerHTML = td1.value;
// ALSO TRIED THIS
//var text1 = document.createTextNode(td1);
//var text2 = document.createTextNode(td2);
td1.appendChild(text1);
td2.appendChild(text2);
tr.appendChild(td1);
tr.appendChild(td2);
table.appendChild(tr);
}
/////////////// BELOW IS THE WHOLE CODE ////////////////
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js">
</script>
<style>
.container-2 {
position: absolute;
top: 10%;
left: 5%;
width: 45%;
height: 30%;
margin-top: 15px;
border: 3px solid #d9d9d9;
background-color: #f2f2f2;
overflow-x: scroll;
overflow-y: scroll;
}
.container-2 table, th, td {
width: 32.5%;
height: 10px;
border: 1px solid #d9d9d9;
border-collapse: collapse;
font-size: 15px;
}
th, td {
padding: 0;
}
</style>
</head>
<body>
<div class="borrow-list-area">
<table class="container-2" id="container-2">
<thead>
<tr>
<style>th,td{text-align:center;}
</style>
<th>Equipment</th>
<th>Quantity</th>
</tr>
</thead>
<script>
// THIS IS CODE I'M HAVING TROUBLE WITH
function trigData() {
var table = document.getElementById('container-
2');
var i;
for (var i = 0; i < 2; i++){
var tr = document.createElement('tr');
var td1 = document.createElement('td');
var td2 = document.createElement('td');
td1.setAttribute("id", "equipment");
td2.setAttribute("id", "quantity");
}
var text1 = document.getElementById("equipment").innerHTML = td1;
var text2 = document.getElementById("quantity").innerHTML = td1;
td1.appendChild(text1);
td2.appendChild(text2);
tr.appendChild(td1);
tr.appendChild(td2);
table.appendChild(tr);
}
</script>
<tbody></tbody>
</table>
</div>
<div class="container" >
<!-- Trigger the modal with a button -->
<button type="button" class="button-1 btn-lg" data-toggle="modal" data-target="#myModal" style="width: 26%; margin:0; height: 40px; font-size: 100%;">Choose Equipment</button>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<p>Choose An Equipment Below</p>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<p>Available Equipments</p>
<div class="form-inline">
<select name="dpdwn" class="drop-down">
<option selected="" disabled="">Select Equipment</option>
<option id="a" value="dpdwn-1"></option>
<option id="b" value="dpdwn-2"></option>
<option id="c" value="dpdwn-3"></option>
</select>
<br><br>
<input type="text" id="qnty-1" class="form-control" placeholder="Quantity" name="quantity" style="width:24%;"><br/>
<script>
var myObj, myJSON, text, obj;
/////////////////////////////// DISPLAY ///////////////////////////////////
// Storing data:
myObj = {
"cars" : [ "HONDA", "FIAT", "BMW" ]
};
myJSON = JSON.stringify(myObj);
localStorage.setItem("drop-down", myJSON);
// Retrieving data:
text = localStorage.getItem("drop-down");
obj = JSON.parse(text);
document.getElementById("a").innerHTML = obj.cars[0];
//document.getElementById("a").value = obj.id;
document.getElementById("b").innerHTML = obj.cars[1];
document.getElementById("c").innerHTML = obj.cars[2];
/////////////////////////////////// PASSING VALUES //////////////////////////////////////
function passValue1(a) {
text = localStorage.getItem("drop-down");
obj = JSON.parse(text);
var q = "dpdwn-1";
var b = "dpdwn-2";
var c = "dpdwn-3";
var e = document.getElementById(a);
alert(a.value);
if(a.value == q){
document.getElementById("equipment").innerHTML = obj.cars[0];
} else if(a.value == b){
document.getElementById("equipment").innerHTML = obj.cars[1];
} else {
document.getElementById("equipment").innerHTML = obj.cars[2];
}
}
function passValue2(b) {
document.getElementById("quantity").innerHTML = document.getElementById("qnty-1").value;
}
</script>
<br/><br/>
</div>
</div>
<div class="modal-footer">
<input class="submit-3" type = "submit" value = "Submit" name= "submit-2" onclick="trigData(); passValue1(dpdwn); passValue2(document.getElementById('qnty-1').value)"data-dismiss="modal" />
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
So I really need the output to be displayed on the JS table and would increment if ever same item is chosen. so far it wont show up anything or it will show up on the cell "[object HTMLTableCellElement]".
$(document).ready(function() {
var hero_image = new Array();
hero_image[0] = new Image();
hero_image[0].src = 'assets/images/link.png';
hero_image[0].id = 'image';
hero_image[1] = new Image();
hero_image[1].src = 'assets/images/bongo.png';
hero_image[1].id = 'image';
hero_image[2] = new Image();
hero_image[2].src = 'assets/images/gandondorf.jpg';
hero_image[2].id = 'image';
hero_image[3] = new Image();
hero_image[3].src = 'assets/images/queen.png';
hero_image[3].id = 'image';
var young_hero = ["Link", "Bongo Bongo", "Gandondorf", "Queen Gohma"];
var health = [100, 70, 120, 50];
var attack_power = [];
var counter_power = [];
console.log(hero_image[0]);
function it_is_over_9000(){
for (var i = 0; i < young_hero.length; i++) {
var x = Math.floor(Math.random(attack_power)*20) + 3;
var y = Math.floor(Math.random(attack_power)*10) + 3;
attack_power.push(x);
counter_power.push(y);
}
}
function ready_board(){
it_is_over_9000();
for (var i = 0; i < young_hero.length; i++) {
var hero_btns = $("<button>");
hero_btns.addClass("hero hero_button");
hero_btns.attr({
"data-name": young_hero[i],
"data-health": health[i],
"data-image": hero_image[i],
"data-attack": attack_power[i],
"data-counter": counter_power[i],
"data-index": i
});
hero_btns.text(young_hero[i]);
hero_btns.append(hero_image[i]);
hero_btns.append(health[i]);
$("#buttons").append(hero_btns);
}
}
function char(){
$(".hero_button").on("click", function() {
var hero = $(this);
var hero_select = hero.data('index');
for (var i = 0; i < young_hero.length; i++) {
//var attack = ;
if (i != hero_select){
var enemies = $("<button>");
enemies.addClass("hero enemy");
enemies.attr({
"data-power" : it_is_over_9000(),
"data-name": young_hero[i],
"data-health": health[i],
"data-image": hero_image[i],
"data-attack": attack_power[i],
"data-counter": counter_power[i],
"data-index": i
});
enemies.text(young_hero[i]);
enemies.append(hero_image[i]);
enemies.append(health[i]);
$("#battle").append(enemies);
}
}
$("#buttons").html($(this).data('name','health','image'));
defender();
});
}
function defender(){
$(".enemy").on("click", function() {
var enemy = $(this);
var enemy_select = enemy.data("index");
console.log(enemy_select);
for (var i = 0; i < young_hero.length; i++) {
if (i == enemy_select) {
var defender = $("<button>");
defender.addClass("hero defender");
defender.attr({
"data-name": young_hero[i],
"data-health": health[i],
"data-image": hero_image[i],
"data-attack": attack_power[i],
"data-counter": counter_power[i],
"data-index": i
});
defender.text(young_hero[i]);
defender.append(hero_image[i]);
defender.append(health[i]);
$("#defend").append(defender);
$(this).remove();
}
}
});
}
$(".defend_button").on("click" , function(){
if($(".defender").data("health") == 0){
$(".defender").remove();
}
$(".defender").attr({
"data-health": $(".defender").data("health") - $(".hero_button").data("attack")
});
});
ready_board();
char();
});
I am trying to make a RPG game and I have the characters being generated the way I want them too but on the $(".defend_button").on("click" , function() at the end it doesn't update the data-health as it should. It only updates once but upon many clicks on the defend-button it doesn't update past the first time.
<!DOCTYPE html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Zelda</title>
<script type='text/javascript' src='https://code.jquery.com/jquery-2.2.0.min.js'></script>
<script type = "text/javascript" src = "assets/javascript/game.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="assets/css/style.css">
</head>
<style type="text/css">
.hero { width: 125px; height:150px; border-style: solid; padding: 2px; float: left; margin: 2px; float: left; }
.letter-button-color { color: darkcyan; }
.fridge-color { color: orange; }
#display { margin-top:78px; height:500px; width:220px; margin-left:60px; }
#buttons { padding-top:60px; }
#clear { margin-left: 20px; font-size: 25px; color: black; border-style: solid; width: 100px; }
#image{width: 100px; height: 100px; margin-left: 10px; }
</style>
<body>
<div class="row">
<div class="col-md-8">Select Your Character</div>
</div>
<div class="row">
<div id="buttons" class="col-md-8"></div>
</div>
<div class="row">
<div id="battle" class="col-md-8">
</div>
</div>
<div class="row">
<div class="col-md-8">
<button class="btn btn-primary defend_button">Defend</button>
</div>
</div>
<div class="row">
<div id="defend">
</div>
</div>
</body>
</html>
You have to use .data() to update the health value.
var battleResult = $(".defender").data("health") - $(".hero_button").data("attack");
console.log("battleResult should be: "+battleResult );
$(".defender").data({
"health": battleResult
});
I played a little with your game.
I found how to update the health display below the image too...
Since only updating the data wasn't changing anything on the screen.
So, I left the above code there, for you to see it is effectively working.
But since you have to re-create the button to update health on scrreen... It is kind of useless.
I also fixed the death condition
from if($(".defender").data("health") == 0){
to if($(".defender").data("health") <= 0){
I have to stop here before changing to much things.
See it in CodePen
Check your loop in it_is_over_9000(), because I think it is running uselessly too often.
And a dead defender has to be "buried" (lol).
Because when it is killed, a click on the defend button is kind of ressurrecting it.
;)
Try setting the attribute like this. Also, I recommend putting $(".defender") in a variable so you aren't requerying it each time.
var defender = $(".defender");
var loweredHealth = defender.data("health") - $(".hero_button").data("attack");
defender.attr('data-health`, loweredHealth);
Update:
It looks like the $('.defender') call will return multiple items. You either need to select a specific defender or iterate through them individually like so:
$('.defender').each(function(i, nextDefender) {
var loweredHealth = nextDefender.data("health") - $(".hero_button").data("attack");
nextDefender.attr('data-health`, loweredHealth);
});`
I wanted to have a feature wherein the user can just copy the contents of a particular by just clicking a single button and press CTRL+C.
The following works if I don't put style="display: none" to my divToCopy. However, when I place the style, CTRL+C will no longer work.
var Clipboard = function() {
var clipboard = {};
clipboard.cssStyle = "";
clipboard.cssClass = "";
clipboard.targetId = "";
clipboard.highlight = function(targetId) {
// backup the styling of the target div
clipboard.cssStyle = $("#" + targetId).attr('style');
clipboard.cssClass = $("#" + targetId).attr('class');
// create a ranged selection
window.getSelection().removeAllRanges();
if (window.getSelection) {
console.log("has selection");
var node = document.getElementById("divToCopy");
var range = document.createRange();
console.log(range);
range.selectNodeContents(node);
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
}
// highlight
$("#" + targetId).css("background-color", "yellow");
};
clipboard.copyWithStyle = function(targetId) {
var toCopy = $('#' + targetId).html();
$('#divToCopy').html(toCopy);
clipboard.targetId = targetId;
clipboard.highlight(targetId);
};
clipboard.copyNoStyle = function(targetId) {
var toCopy = $('#' + targetId).html();
$('#divToCopy').html(toCopy);
$('#divToCopy *').removeAttr('style');
$('#divToCopy *').removeAttr('class');
clipboard.targetId = targetId;
clipboard.highlight(targetId);
};
$("#divToCopy").bind('copy', function() {
$("#" + clipboard.targetId).attr('style', clipboard.cssStyle);
$("#" + clipboard.targetId).attr('class', clipboard.cssClass);
});
return clipboard;
};
$(document).ready(function() {
var c = Clipboard();
$("#copy-with-style").click(function(event) {
c.copyWithStyle("content");
});
$("#copy-no-style").click(function(event) {
c.copyNoStyle("content");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="my-body" align="center">
<br/>
<div id="content" style="text-align:left; margin:0 auto; border: 1px solid black; width: 300px; padding: 5px;">
<div style="color:red">RED by Taylor Swift</div>
<ul>
<li>One</li>
<li style="font-weight:bold;">Two</li>
<li>3</li>
<li>Four</li>
<li>~!##$%^&*()______+{}[]:";'
<>?,./"</li>
</ul>
<table style="border:1px solid green;">
<tr>
<td colspan=2>Merged</td>
<td style="color:blue;">Blue</td>
</tr>
<tr>
<td>Red</td>
<td>Green</td>
<td>Violet</td>
</tr>
</table>
</div>
<br/>
<input type="button" value="Copy With Style" id="copy-with-style" />
<input type="button" value="Copy Without Style" id="copy-no-style" />
<div id="divToCopy" style="display: none" contenteditable="true"></div>
</div>
Instead of display:none; Use visibility:hidden This might work for you.
don't use:
display: none;
visibility: hidden;
use:
width: 1px;
height: 1px;
overflow: hidden;
i want to take input from user(number) and display image as many times as number.If user inputs 5 then the image should be displayed 5 times next to each other with corresponding number below the images-Below 1st image '1' 2nd Image '2'.Basically putting this table in loop.
<HTML>
<BODY>
<TABLE>
<TR>
<TD>
<IMG SRC="C:/Users/User/Desktop/RE/G.JPG">
</TD>
</TR>
<TR><TD ALIGN="CENTER">1</TD>
</TABLE>"
</BODY>
</HTML>
You can use jQuery for this task and write a function that generates HTML with a dynamic value:
Complete Solution
<HTML>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
function generateTable(number) {
return "<table><tr><td>" +
"<img src='C:/Users/User/Desktop/RE/G.JPG'></td></tr><tr><td align='center'>" +
number +
"</td></table>";
}
$(function(){
var userInput = 3;
for (var i = 0; i < userInput; i++) {
$('#dynamic').append(generateTable(i + 1));
}
});
</script>
</head>
<body>
<div id='dynamic'></div>
</body>
</html>
You can add an input and a button to trigger the function.
You could also check if the inserted value is actually a number or not.
$(document).on('click', '#add', function() {
var that = $(this);
var times = parseInt($('#times').val());
for (i=1;i<=times;i++) {
$('#table-wrp').append('<table class="table-times"><tbody><tr><td><img src="http://code52.org/aspnet-internationalization/icon.png" /></td></tr><tr><td>' + i + '</td></tr></tbody></table>');
}
});
$(document).on('input', '#times', function() {
var that = $(this);
var value = that.val();
if ((value != '' || value != false) && !isNaN(value)) {
$('#add').prop('disabled', false);
} else {
$('#add').prop('disabled', true);
}
});
#table-wrp {
height: 80px;
}
.table-times {
width: 100px;
height: 80px;
float: left;
border-collapse: collapse;
}
.table-times td {
border: 1px solid #d8d8d8;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input type="textbox" id="times" />
<button id="add" disabled>Add</button>
<div id="table-wrp"></div>
Or for a pure javascript version of Pugazh's answer
var tab = "<div></div>";
var num = prompt("Enter a number");
for(i = 0; i < num; i++){
document.getElementById('tab').innerHTML += "<div><div><img src='http://placehold.it/150x150'></div><div></div></div>";
}
img{
float: left;
box-shadow: 5px 5px 10px rgba(0,0,0,0.4);
height: 100px;
width: 100px;
margin: 10px;
}
<div id="tab"></div>
This will work just as well, but doesn't require jQuery as well.
<HTML>
<BODY>
<div id="tbl"></div>
</BODY>
</HTML>
<script>
var num = prompt("Enter a number");
var div=document.getElementById("tbl");
var l1='',l2="";
for(i=0;i<num;i++)
{
l1 += '<td><img src="C:/Users/User/Desktop/RE/G.JPG"></td>';
l2 += '<td>'+i+'</td>';
}
div.innerHTML = "<table><tr>"+l1+"</tr><tr>" + l2 + "</tr></table>";
</script>
Try this
$(function() {
var tab = "<div></div>";
var num = prompt("Enter a number");
for (i = 0; i < num; i++) {
$("#tab").append("<div class='left'><div><img src='http://placehold.it/150x150'></div><div>" + (i + 1) + "</div></div>");
}
});
div.left {
display: inline-block;
margin-right: 5px;
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<div id="tab">
</div>
</body>
</html>