Unable to store permanently the id of dragged item - javascript

I am working on a project in which i had to store the the 3ID's of drop item in 3 textbox. but when i dragg and drop either one it stores it's id but when i drop the second item it stores it's ID but remove the ID of first from the textbox.
code
function dropItems(idOfDraggedItem, targetId, x, y) {
var targetObj = document.getElementById(targetId);
var subDivs = targetObj.getElementsByTagName('DIV');
if(subDivs.length>0 && targetId!='body')return;
var sourceObj = document.getElementById(idOfDraggedItem);
var numericIdTarget = targetId.replace(/[^0-9]/gi,'')/1;
var numericIdSource = idOfDraggedItem.replace(/[^0-9]/gi,'')/1;
if (numericIdTarget == '101') {
document.getElementById('txt1').value = numericIdSource;
} else {
document.getElementById('txt1').value = "";
}
if (numericIdTarget == '102') {
document.getElementById('txt2').value = numericIdSource;
} else {
document.getElementById('txt2').value = "";
}
if (numericIdTarget == '103') {
document.getElementById('txt3').value = numericIdSource;
} else {
document.getElementById('txt3').value = "";
}
var fn = "Feeling1:-" + document.getElementById('txt1').value + ", Feeling2:-" + document.getElementById('txt2').value + ", Feeling3:-" + document.getElementById('txt3').value + "";
document.getElementById('txt4').value = fn;
if (numericIdTarget - numericIdSource == 100) {
sourceObj.style.backgroundColor = '';
} else {
sourceObj.style.backgroundColor = '';
}
if (targetId == 'body') {
targetObj = targetObj.getElementsByTagName('DIV')[0];
}
targetObj.appendChild(sourceObj);
}
Initialization (from comments)
$(document).ready(function(e) {
var inp1=$("#txt1");
var inp2=$("#txt2");
var inp3=$("#txt3");
$("#bttn").click(function(){
if(inp1.val()=="" && (inp2.val()!="" || inp3.val()!="")) {
alert("Provide answer in consecutive manner");
} else if((inp1.val()=="" || inp2.val()=="") && inp3.val()!="" ) {
alert("Provide answer in consecutive manner");
} else {
alert("Submit");
}
});
})

I like to use jquery's built in draggable/droppable to acquire id's maybe this will help you with your current situation.
<!DOCTYPE HTML>
<html>
<head>
<title>Test Page</title>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {
$( ".draggable" ).draggable();
$( ".droppable" ).droppable({
drop: function( event, ui ) {
var id = $( this ).attr("id");
var container = ui.draggable.attr("id");
alert(id + " " + container);
}
});
});
</script>
<style>
.draggable{
width: 100px;
height: 50px;
border: 1px black solid;
margin: 0.5em;
}
.droppable{
width: 100px;
height: 50px;
border: 1px black solid;
margin: 0.5em;
}
</style>
</head>
<body>
<div id="draggable1" class="draggable">
<p>Drag me to my target</p>
</div>
<div id="draggable2" class="draggable">
<p>Drag me to my target</p>
</div>
<div id="draggable3" class="draggable">
<p>Drag me to my target</p>
</div>
<div style="height: 25px;"></div>
<div id="droppable1" class="droppable">
<p>Drop here</p>
</div>
<div id="droppable2" class="droppable">
<p>Drop here</p>
</div>
</body>
</html>

Related

How to show/hide a border using javascript

I have 10 square boxes with different colors. I'm trying to show a border for the square that the user clicks on, and hide the border of the previous square. So far I have this, but I somehow get Cannot read property 'style' of null. My idea is to hide the current box border, then show a border for the new box that the user clicks.
Here is the jsFiddle of what I want. However, it doesn't seem to work. I can only use Javascript and can't use JQuery
https://jsfiddle.net/5op0d7zs/7/
var currentBoxNum = 1;
function changeColor(background, boxNum) {
document.getElementById("box" + currentBoxNum).style.borderStyle = "none";
currentBoxNum = boxNum;
document.getElementById("box" + currentBoxNum).style.borderStyle = "solid";
}
box1.onclick = function() { changeColor("#e6e2cf",1); }
box2.onclick = function() { changeColor("#dbcaac",2); }
box3.onclick = function() { changeColor("#c9cbb3",3); }
box4.onclick = function() { changeColor("#bbc9ca",4); }
box5.onclick = function() { changeColor("#a6a5b5",5); }
box6.onclick = function() { changeColor("#b5a6ab",6); }
box7.onclick = function() { changeColor("#eccfcf",7); }
box8.onclick = function() { changeColor("#eceeeb",8); }
box9.onclick = function() { changeColor("#bab9b5",9); }
<div class="colors">
<div id="box1">1</div>
<div id="box2">2</div>
<div id="box3">3</div>
<div id="box4">4</div>
<div id="box5">5</div>
<div id="box6">6</div>
<div id="box7">7</div>
<div id="box8">8</div>
<div id="box9">9</div>
</div>
You don't need to call the changeColor twice. Second thing You can do what you want in less code.
See this working example here.
You can check the updated fiddle here
var currentBoxNum = 1;
function changeColor(background, boxNum) {
document.getElementById("box" + currentBoxNum).style.borderStyle = "none";
currentBoxNum = boxNum;
document.getElementById("box" + currentBoxNum).style.borderStyle = "solid";
document.getElementById("box" + currentBoxNum).style.borderColor = "black";
}
document.getElementById("box1").addEventListener("click", function(){ changeColor("#e6e2cf", 1); });
document.getElementById("box2").addEventListener("click", function(){ changeColor("#dbcaac", 2); });
document.getElementById("box3").addEventListener("click", function(){ changeColor("#c9cbb3", 3); });
document.getElementById("box4").addEventListener("click", function(){ changeColor("#bbc9ca", 4); });
document.getElementById("box5").addEventListener("click", function(){ changeColor("#a6a5b5", 5); });
document.getElementById("box6").addEventListener("click", function(){ changeColor("#b5a6ab", 6); });
document.getElementById("box7").addEventListener("click", function(){ changeColor("#eccfcf", 7); });
document.getElementById("box8").addEventListener("click", function(){ changeColor("#eceeeb", 8); });
document.getElementById("box9").addEventListener("click", function(){ changeColor("#bab9b5", 9); });
#box1 {
background-color: #e6e2cf;
border: 2px solid black;
}
#box2 {
background-color: #dbcaac;
}
#box3 {
background-color: #c9cbb3;
}
#box4 {
background-color: #bbc9ca;
}
#box5 {
background-color: #a6a5b5;
}
#box6 {
background-color: #b5a6ab;
}
#box7 {
background-color: #eccfcf;
}
#box8 {
background-color: #eceeeb;
}
#box9 {
background-color: #bab9b5;
}
.pad {
margin: 10px;
}
.colors {
display: flex;
flex-wrap: wrap;
}
.colors>div {
width: 50px;
margin: 10px;
height: 50px;
}
<!-- This is a static file -->
<!-- served from your routes in server.js -->
<!DOCTYPE html>
<html>
<head>
<title>Show me!</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="./reset.css">
<link rel="stylesheet" href="./style.css">
<link href="https://fonts.googleapis.com/css?family=Dancing+Script|Homemade+Apple|Indie+Flower|Long+Cang&display=swap" rel="stylesheet">
</head>
<body>
<main>
<div class="pad">
<h2 class="choose_pad">Choose your color</h2>
<div class="colors">
<div id="box1">1</div>
<div id="box2">2</div>
<div id="box3">3</div>
<div id="box4">4</div>
<div id="box5">5</div>
<div id="box6">6</div>
<div id="box7">7</div>
<div id="box8">8</div>
<div id="box9">9</div>
</div>
</div>
</main>
<footer>
<p class="msg">
Made on Glitch!
</p>
<!-- adds the glitch button at the bottom -->
<div class="glitchButton"></div>
<script src="https://button.glitch.me/button.js"></script>
<script src="./script.js"></script>
</footer>
</body>
</html>
You're calling
document.getElementById("cb").style.backgroundColor = background;
There is no element with an id of "cb".
Update your code to properly reference the id of the element you wish to change the background color for.
Missing line: document.getElementById("box" + currentBoxNum).style. borderColor = background;
var currentBoxNum = 1;
function changeColor(background, boxNum) {
document.getElementById("box" + currentBoxNum).style.borderStyle = "none";
currentBoxNum = boxNum;
document.getElementById("box" + currentBoxNum).style.borderStyle = "solid";
document.getElementById("box" + currentBoxNum).style. borderColor = background;
}
box1.onclick = function() { changeColor("#e6e2cf",1); }
box2.onclick = function() { changeColor("#dbcaac",2); }
box3.onclick = function() { changeColor("#c9cbb3",3); }
box4.onclick = function() { changeColor("#bbc9ca",4); }
box5.onclick = function() { changeColor("#a6a5b5",5); }
box6.onclick = function() { changeColor("#b5a6ab",6); }
box7.onclick = function() { changeColor("#eccfcf",7); }
box8.onclick = function() { changeColor("#eceeeb",8); }
box9.onclick = function() { changeColor("#bab9b5",9); }
<div class="colors">
<div id="box1">1</div>
<div id="box2">2</div>
<div id="box3">3</div>
<div id="box4">4</div>
<div id="box5">5</div>
<div id="box6">6</div>
<div id="box7">7</div>
<div id="box8">8</div>
<div id="box9">9</div>
</div>
You can change you changeColor method as below
function changeColor(background, boxNum) {
$('.colors div').css('border', 'none'); // This will remove borders from all boxes
document.getElementById("box" + boxNum).style.borderStyle = "solid";
document.getElementById("box" + boxNum).style.borderColor = background;
}
Since this method is using jQuery, please include the jQuery in your html as below,
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
Also, this is just adding the border color not background color. If you want to add the background color as well you can add the following statement in changeColor function
document.getElementById("box" + boxNum).style.backgroundColor = background;

Create multiple divs with different content

The problem is when duplicate multiple div but with different data-type, it still running a same content, i want correct all div will have the different content following the different data-type.
Is there a way to do this?
$(function() {
// document
'use strict';
var cp = $('div.box');
// unique id
var idCp = 0;
for (var i = 0; i < cp.length; i++) {
idCp++;
cp[i].id = "cp_" + idCp;
}
// diffrent type
if (cp.data('type') == "c1") {
cp.addClass('red').css({
"background: 'red',
"padding": "20px",
"display": "table"
});
$('.box').append('<div class="cp-title">' + 'c1-title' + '</div>');
} else if (cp.data('type') == "c2") {
cp.addClass('green').css({
"background": 'green',
"padding": "20px",
"display": "table"
});
$('.box').append('<div class="cp-title">' + 'c2-title' + '</div>');
} else {
return false;
}
}); //end
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<! it should be like this>
<div class="box" data-type="c1" id="cp_1">
<div class="cp-title">c1 title</div>
</div>
<div class="box" data-type="c2" id="cp_2">
<div class="cp-title">c2 title</div>
</div>
<! currently wrong output>
<div class="box" data-type="c1" id="cp_1">
<div class="cp-title">c1 title</div>
</div>
<div class="box" data-type="c2" id="cp_2">
<div class="cp-title">c1 title</div>
</div>
The problem in your code is that you are not looping inside the div's. You have to use the .each() function while looping inside all the elements
$(function() {
var cp = $('div.box');
cp.each(function() {
var _cp = $(this);
var text = _cp.attr("data-type") + "-title"; //Generate the text dynamically
var cls = _cp.attr("data-class"); //Get the class dynamically
_cp.addClass(cls).append('<div class="cp-title">' + text + '</div>'); //Add the class and append the text to the parent div
});
}); //end
.box{
padding: 20px;
display: table;
}
.red{
background: red;
}
.green{
background: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box" data-type="c1" data-class="red"></div>
<div class="box" data-type="c2" data-class="green"></div>
Probably you're searching for something like this.
// document.ready
$(function() {
'use strict';
$('.box').each(function(i,elem){
var ref = +$(elem).attr("data-type").match(/\d/)[0], addClass = 'default';
switch(true) {
case ref === 1:
addClass = 'red';
break;
case ref === 2:
addClass = 'green';
break;
}
$(this)
.addClass(addClass)
.append('<div class="cp-title">c'+ref+' title</div>');
});
}); //end
.red{
background: red;
padding: 20px;
display: table;
}.green{
background: green;
padding: 20px;
display: table;
}.default {
background: #2d2d2d;
color: #f6f6f6;
padding: 20px;
display: table;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box" data-type="c1"></div><div class="box" data-type="c2"></div>

How can I update attributes with jQuery?

$(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);
});`

Page-Breaks in JQuery Mobile?

Is it possible to apply page-breaks to JQuery Mobile when printing?
The problem that is occurring is when attempting to print, dynamically generated paragraphs <p> split between the end and start of a new page and that section does not move over as one section in A4. I have also attempted to use page-break-after: always; and other css, however, this seems not to work.
The following JSFiddle converts text from a <textarea> into equal paragraphs <p>
Attached is a JSFiddle to better understand the problem.
Thank You!
<!DOCTYPE html>
<html>
<head>
<meta content="width=device-width, initial-scale=1" name="viewport">
<link href=
"https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" rel=
"stylesheet">
<script src="https://code.jquery.com/jquery-1.11.3.min.js">
</script>
<script src=
"https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js">
</script>
<title></title>
</head>
<body>
<div data-role="page" id="pageone">
<div data-role="header">
<h1>Page 1</h1>
</div>
<div class="ui-content" data-role="main">
<a data-transition="slide" href="#pagetwo">Go to Generated Paragraphs</a>
<div>
<h3>Paste text in the field below to divide text into
paragraphs..</h3>
<textarea id="textarea1" placeholder=
"Type text here, then press the button below." rows="5">
</textarea> <button id="go">Divide Text into Paragraphs</button>
</div>
</div>
<div data-role="footer">
<h1>Page 1 Footer</h1>
</div>
</div>
<div data-role="page" id="pagetwo">
<div data-role="header">
<h1>Page 2</h1>
</div>
<div class="ui-content" data-role="main">
<button onclick="myFunction()">Print this page</button>
<script>
function myFunction() {
window.print();
}
</script>
<h5>Click on the link to go back. <b>Note</b>: fade is
default.</h5>Go to Page One
<div id="content"></div>
</div>
<div data-role="footer">
<h1>Page 2 Footer</h1>
</div>
</div>
<script>
var btn = document.getElementById('go'),
textarea = document.getElementById('textarea1'),
content = document.getElementById('content'),
chunkSize = 100;
btn.addEventListener('click', initialDistribute);
content.addEventListener('keyup', handleKey);
content.addEventListener('paste', handlePaste);
function initialDistribute() {
var text = textarea.value;
while (content.hasChildNodes()) {
content.removeChild(content.lastChild);
}
rearrange(text);
}
function rearrange(text) {
var chunks = splitText(text, false);
chunks.forEach(function(str, idx) {
para = document.createElement('P');
para.setAttribute('contenteditable', true);
para.textContent = str;
content.appendChild(para);
});
}
function handleKey(e) {
var para = e.target, position,
key, fragment, overflow, remainingText;
key = e.which || e.keyCode || 0;
if (para.tagName != 'P') { return; }
if (key != 13 && key != 8) { redistributeAuto(para); return; }
position = window.getSelection().getRangeAt(0).startOffset;
if (key == 13) {
fragment = para.lastChild;
overflow = fragment.textContent;
fragment.parentNode.removeChild(fragment);
remainingText = overflow + removeSiblings(para, false);
rearrange(remainingText);
}
if (key == 8 && para.previousElementSibling && position == 0) {
fragment = para.previousElementSibling;
remainingText = removeSiblings(fragment, true);
rearrange(remainingText);
}
}
function handlePaste(e) {
if (e.target.tagName != 'P') { return; }
overflow = e.target.textContent + removeSiblings(fragment, true);
rearrange(remainingText);
}
function redistributeAuto(para) {
var text = para.textContent, fullText;
if (text.length > chunkSize) {
fullText = removeSiblings(para, true);
}
rearrange(fullText);
}
function removeSiblings(elem, includeCurrent) {
var text = '', next;
if (includeCurrent && !elem.previousElementSibling) {
parent = elem.parentNode;
text = parent.textContent;
while (parent.hasChildNodes()) {
parent.removeChild(parent.lastChild);
}
} else {
elem = includeCurrent ? elem.previousElementSibling : elem;
while (next = elem.nextSibling) {
text += next.textContent;
elem.parentNode.removeChild(next);
}
}
return text;
}
function splitText(text, useRegex) {
var chunks = [], i, textSize, boundary = 0;
if (useRegex) {
var regex = new RegExp('.{1,' + chunkSize + '}\\b', 'g');
chunks = text.match(regex) || [];
} else {
for (i = 0, textSize = text.length; i < textSize; i = boundary) {
boundary = i + chunkSize;
if (boundary <= textSize && text.charAt(boundary) == ' ') {
chunks.push(text.substring(i, boundary));
} else {
while (boundary <= textSize && text.charAt(boundary) != ' ') { boundary++; }
chunks.push(text.substring(i, boundary));
}
}
}
return chunks;
}
</script>
<style>
p { padding: 1.2em 0.5em; margin: 1.4em 0; border: 1px dashed #aaa; }
</style>
<style>
p {
page-break-before: always;
page-break-after: always;
}
p { page-break-inside: avoid;
}
</style>
</body>
</html>
JQM uses absolutely positioned pages, which page-break-after does not allow. To solve this, add something like:
#media print{
.ui-page {
position: relative !important;
}
}
I hope this helps someone!

How to dynamically create table in html with certain constraints?

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>

Categories

Resources