How to add data locally and add value by its id? - javascript

<!DOCTYPE HTML>
<html>
<head>
<title>HTML5 localStorage (name/value item pairs) demo</title>
<style >
td, th {
font-family: monospace;
padding: 4px;
background-color: #ccc;
}
#hoge {
border: 1px dotted blue;
padding: 6px;
background-color: #ccc;
margin-right: 50%;
}
#items_table {
border: 1px dotted blue;
padding: 6px;
margin-top: 12px;
margin-right: 50%;
}
#items_table h2 {
font-size: 18px;
margin-top: 0px;
font-family: sans-serif;
}
label {
vertical-align: top;
}
</style>
</head>
<body onload="doShowAll()">
<h1>HTML5 localStorage (name/value item pairs) demo</h1>
<form name=editor>
<div id="hoge">
<p>
<label>Value: <textarea name=data cols=41 rows=10></textarea></label>
</p>
<p>
<label>Name: <input name=name></label>
<input type=button value="getItem()" onclick="doGetItem()">
<input type=button value="setItem()" onclick="doSetItem()">
<input type=button value="removeItem()" onclick="doRemoveItem()">
</p>
</div>
<div id="items_table">
<h2>Items</h2>
<table id=pairs></table>
<p>
<label><input type=button value="clear()" onclick="doClear()"> <i>* clear() removes all items</i></label>
</p>
</div>
<script>
function doSetItem() {
var name = document.forms.editor.name.value;
var data = document.forms.editor.data.value;
var origData = localStorage.getItem(name) || 0;
localStorage.setItem(name, parseInt(origData) + parseInt(data));
doShowAll();
}
function doGetItem() {
var name = document.forms.editor.name.value;
document.forms.editor.data.value = localStorage.getItem(name);
doShowAll();
}
function doRemoveItem() {
var name = document.forms.editor.name.value;
document.forms.editor.data.value = localStorage.removeItem(name);
doShowAll();
}
function doClear() {
localStorage.clear();
doShowAll();
}
function doShowAll() {
var key = "";
var pairs = "<tr><th>Name</th><th>Value</th></tr>\n";
var i=0;
for (i=0; i<=localStorage.length-1; i++) {
key = localStorage.key(i);
pairs += "<tr><td>"+key+"</td>\n<td>"+localStorage.getItem(key)+"</td></tr>\n";
}
if (pairs == "<tr><th>Name</th><th>Value</th></tr>\n") {
pairs += "<tr><td><i>empty</i></td>\n<td><i>empty</i></td></tr>\n";
}
document.getElementById('pairs').innerHTML = pairs;
}
</script>
</form>
</body>
</html>
Hi friends,
I wants to locally save the data,now I am able to save the data locally by the code.even if I give the same name the value is getting added and saved locally.but the name should be shown in order of high value to low(example: Ram 20,Renu 18,green 2 like wise...).so how to do this?

function doSetItem() {
var name = document.forms.editor.name.value;
var data = document.forms.editor.data.value;
var origData = localStorage.getItem(name) || 0;
localStorage.setItem(name, parseInt(origData) + parseInt(data));
doShowAll();
}
To display them in descending order:
function doShowAll() {
var key = "";
var pairs = "<tr><th>Name</th><th>Value</th></tr>\n";
var userArray = [];
for (var i = 0; i <= localStorage.length - 1; i++) {
key = localStorage.key(i);
userArray.push({name:key, value:parseInt(localStorage.getItem(key))});
}
userArray.sort(function(a, b){
return b.value - a.value;
});
userArray.forEach(function(user){
pairs += "<tr><td>" + user.name + "</td>\n<td>" + user.value + "</td></tr>\n";
});
if (pairs === "<tr><th>Name</th><th>Value</th></tr>\n") {
pairs += "<tr><td><i>empty</i></td>\n<td><i>empty</i></td></tr>\n";
}
document.getElementById('pairs').innerHTML = pairs;
}

For what I can see in your code, you're just replacing the value, you need to get the existent value from the localStorage first, append to it the new one and then asign the result to the localStorage.

Related

How do I add multiple entries in a list in JavaScript

I have a program for a makeshift task list that I am working on that should allow a user to enter more than one task by separating the tasks with a comma. I am not sure how I would write a portion of code to allow this function. I am trying to also make the lists themselves separate so if a user needed to delete a task, all the tasks would not be deleted too.
"use strict";
var $ = function(id) { return document.getElementById(id); };
var tasks = [];
var displayTaskList = function() {
var list = "";
// if there are no tasks in tasks array, check storage
if (tasks.length === 0) {
// get tasks from storage or empty string if nothing in storage
var storage = localStorage.getItem("tasks") || "";
// if not empty, convert to array and store in global tasks variable
if (storage.length > 0) { tasks = storage.split("|"); }
}
// if there are tasks in array, sort and create tasks string
if (tasks.length > 0) {
tasks.sort();
list = tasks.join("\n");
}
// display tasks string and set focus on task text box
$("task_list").value = list;
$("task").focus();
};
var addToTaskList = function() {
var task = $("task");
if (task.value === "") {
alert("Please enter a task.");
} else {
// add task to array and local storage
tasks.push(task.value);
localStorage.tasks = tasks.join("|");
// clear task text box and re-display tasks
task.value = "";
displayTaskList();
}
};
var clearTaskList = function() {
tasks.length = 0;
localStorage.tasks = "";
$("task_list").value = "";
$("task").focus();
};
window.onload = function() {
$("add_task").onclick = addToTaskList;
$("clear_tasks").onclick = clearTaskList;
displayTaskList();
};
body {
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 100%;
background-color: white;
width: 700px;
margin: 0 auto;
border: 3px solid blue;
padding: 0 2em 1em;
}
h1 {
font-size: 150%;
color: blue;
margin-bottom: .5em;
}
label {
float: left;
width: 8em;
}
input {
width: 22em;
margin-right: 1em;
margin-bottom: 1em;
}
#tasks {
margin-top: 0;
float: right;
}
<!DOCTYPE html>
<html>
<head>
<title>Ch09 Task Manager</title>
<link type="text/css" rel="stylesheet" href="task_list.css">
<script type="text/javascript" src="task_list.js"></script>
</head>
<body>
<main>
<h1>Task Manager</h1>
<div id="tasks">
<span id="name"> </span>Tasks<br>
<textarea id="task_list" rows="8" cols="50"></textarea>
</div>
<label for="task">Task</label><br>
<input type="text" name="task" id="task"><br>
<input type="button" name="add_task" id="add_task" value="Add Task">
<input type="button" name="clear_tasks" id="clear_tasks" value="Clear Tasks"><br>
<input type="button" name="delete_task" id="delete_task" value="Delete Task">
<input type="button" name="toggle_sort" id="toggle_sort" value="Toggle Sort"><br>
<input type="button" name="set_name" id="set_name" value="Set Name">
<input type="button" name="filter_tasks" id="filter_tasks" value="Filter Tasks"><br>
</main>
</body>
</html>
I found a lot of other stuff that needed fixing, so I did (mostly having to do with how you use jQuery). Works for me locally. Snippet runner doesn't want to do some of this stuff - sorry! Don't know about that.
var tasks = [];
var displayTaskList = function() {
var list = "";
if (tasks.length === 0) { // if there are no tasks in tasks array, check storage
var storage = localStorage.getItem("tasks") || ""; // get tasks from storage or empty string if nothing in storage
if (storage.length > 0) {
tasks = storage.split("|");
} // if not empty, convert to array and store in global tasks variable
}
if (tasks.length > 0) { // if there are tasks in array, sort and create tasks string
tasks.sort();
list = tasks.join("\n");
}
$("#task_list").val(list); // display tasks string and set focus on task text box
$("#task").focus();
};
var addToTaskList = function() {
var task = $("#task").val();
console.log(`entering addtotask list with task value = ${task}`);
if (task === "") {
alert("Please enter a task.");
} else {
if (task.indexOf(',') === -1) {
tasks.push(task); // add task to array and local storage
} else {
const split = task.split(','); // 2 lines for readability
split.forEach(atask => {
tasks.push(atask);
});
}
localStorage.tasks = tasks.join("|");
$("#task").val(""); // clear task text box and re-display tasks
displayTaskList();
}
};
var clearTaskList = function() {
tasks.length = 0;
localStorage.tasks = "";
$("#task_list").val("");
$("#task").focus();
};
window.onload = function() {
$("#add_task").on('click', function() {
addToTaskList();
});
$("#clear_tasks").on('click', function() {
clearTaskList();
});
displayTaskList();
};
body {
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 100%;
background-color: white;
width: 800px;
margin: 0 auto;
border: 3px solid blue;
padding: 0 2em 1em;
}
h1 {
font-size: 150%;
color: blue;
margin-bottom: .5em;
}
label {
float: left;
width: 8em;
}
input {
width: 22em;
margin-right: 1em;
margin-bottom: 1em;
}
#tasks {
margin-top: 0;
float: right;
}
<body>
<main>
<h1>Task Manager</h1>
<div id="tasks">
<span id="name"> </span>Tasks<br>
<textarea id="task_list" rows="8" cols="50"></textarea>
</div>
<label for="task">Task</label><br>
<input type="text" name="task" id="task"><br>
<input type="button" name="add_task" id="add_task" value="Add Task">
<input type="button" name="clear_tasks" id="clear_tasks" value="Clear Tasks"><br>
<input type="button" name="delete_task" id="delete_task" value="Delete Task">
<input type="button" name="toggle_sort" id="toggle_sort" value="Toggle Sort"><br>
<input type="button" name="set_name" id="set_name" value="Set Name">
<input type="button" name="filter_tasks" id="filter_tasks" value="Filter Tasks"><br>
</main>
<script src="//code.jquery.com/jquery-3.4.1.min.js"></script>
</body>

JS splicing array value according to key value

I have this code below that consists of three different array Red Fruits, Green Fruits and Suggested Fruits I am able to splice and push a single array value from Suggested Fruits to Green Fruits by clicking of the value and vice versa. But now i'm trying to do something different which is using my new Multidimensional Array: fruits to splice and push the value of the suggestFruits array to my red and green fruits array depending on the type e.g. type:1 goes to red fruits table and type:2 goes to green fruits table is there any easy way to accomplish this? Any help would be greatly appreciated!
var red = {};
var green = {};
var random = {};
var fruits = [];
var fruits1 = {["fruit"]:"Apple", ["type"]:"1"}
var fruits2 = {["fruit"]:"Tomato", ["type"]:"1"}
var fruits3 = {["fruit"]:"Lime", ["type"]:"2"}
var fruits4 = {["fruit"]:"Guava", ["type"]:"2"}
fruits.push(fruits1,fruits2,fruits3,fruits4);
console.log(fruits);
var suggestFruits = fruits.filter(x => x.fruit).map(x => x.fruit);
console.log(suggestFruits);
var key = "Red Fruits";
red[key] = ['Apple', 'Cherry', 'Strawberry','Pomegranate','Rassberry'];
var key2 = "Green Fruits";
green[key2] = ['Watermelon', 'Durian', 'Avacado','Lime','Honeydew'];
var key3 = "Random Fruits";
random[key3] = suggestFruits;
function redraw() {
var redString = '';
$.each(red[key], function(index) {
redString += ('<div class="pilldiv redpill class">' + red[key][index] + '</div>');
});
$('.redclass').html(redString);
var greenString = '';
$.each(green[key2], function(index) {
greenString += ('<div class="pilldiv greenpill class">' + green[key2][index] + '</div>');
});
$('.greenclass').html(greenString);
var randomString = '';
$.each(random[key3], function(index) {
randomString += ('<div class="pilldiv randompill class">' + random[key3][index] + '</div>');
});
$('.randomclass').html(randomString);
}
function listener() {
$(document).ready(function() {
$(document).on("click", "#randomid div", function() {
data = this.innerHTML;
k1 = Object.keys(random).find(k => random[k].indexOf(data) >= 0)
index = random[k1].indexOf(data);
random[k1].splice(index, 1);
green[key2].push(data);
$(".total_count_Green_Fruits").html(key2 + ': ' + green[key2].length);
var element = $(this).detach();
$('#greenid').append('<div class="new-green-fruit pilldiv class ">' + element.html() + '</div>');
});
});
$('body').on('click', 'div.new-green-fruit', function() {
data2 = this.innerHTML;
console.log(data2);
k2 = Object.keys(green).find(k => green[k].indexOf(data2) >= 0)
index2 = green[k2].indexOf(data2);
green[k2].splice(index2, 1);
random[key3].push(data2);
$(this).detach();
var element2 = $(this).detach();
$('#randomid').append('<div class="pilldiv randompill class" >' + element2.html() + '</div>');
});
}
redraw();
listener();
.pilldiv {
padding: 8px 15px;
text-align: center;
font-size: 15px;
border-radius: 25px;
color: Black;
margin: 2px;
}
.redpill {
background-color: Pink;
cursor:default;
}
.greenpill {
background-color: SpringGreen;
cursor:default;
}
.randompill {
background-color: LightBlue;
cursor:pointer;
}
.class {
font-family: Open Sans;
}
.center {
display: flex;
justify-content: center;
}
.wrappingflexbox {
display: flex;
flex-wrap: wrap;
justify-content: center;
}
.top {
margin-bottom: 20px
}
h3{
font-weight: normal;
}
.panel {
display: table;
height: 100%;
width: 60%;
background-color:white;
border: 1px solid black;
margin-left: auto;
margin-right: auto;
}
.new-green-fruit{
background-color: LightBlue;
cursor:pointer;
}
.top{
margin-bottom:30px;
}
<!DOCTYPE html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<head>
<meta charset="utf-8" />
<link rel="shortcut icon" href="//#" />
</head>
<body>
<div class="panel">
<div style="float:left;width:calc(50% - 5px);">
<h3 class="class center">Red Fruits</h3>
<div id="redid" class="redclass wrappingflexbox top"></div>
</div>
<div style="float:right;width:calc(50% - 5px)">
<h3 class="class center">Green Fruits</h3>
<div id="greenid" class="greenclass wrappingflexbox top"></div>
</div>
<div style="clear:both">
<h3 class="center class">Suggested Fruits</h3>
<div id="randomid" class="randomclass wrappingflexbox top"></div>
</div>
</div>
</body>
</html>
There's a lot going on in this question, but from what I gathered, you are simply trying to push the names of the fruits that are type === "1" to the red fruits array, and type === "2" to the green fruits array.
Your main issue with splitting the suggestedFruits into the red and green categories is that when you create the suggestedFruits array, you are losing the type information. What you can do, though, is you can look back at the original fruits array to get the info.
Here's how you can accomplish that:
var fruits = [
{fruit:"Apple", type:"1"},
{fruit:"Tomato", type:"1"},
{fruit:"Lime", type:"2"},
{fruit:"Guava", type:"2"},
];
// map so we can know how to map fruit.type into the correct fruitTypes array
var fruitTypeMap = {"1": "Red Fruits", "2": "Green Fruits"}
// one container for all fruit types so we can access dynamically
var fruitTypes = {
"Red Fruits": ['Apple', 'Cherry', 'Strawberry','Pomegranate','Rassberry'],
"Green Fruits": ['Watermelon', 'Durian', 'Avacado','Lime','Honeydew'],
"Random Fruits": fruits.map(fruit => fruit.fruit)
};
// clone element for easily creating fruit-pills
var clonePill = $(".clone");
// initialize the red/green/random pills
Object.keys(fruitTypes).forEach(key => {
fruitTypes[key].forEach(fruit => {
var $newFruit = clonePill.clone();
// remove clone class so it is visible and doesn't get re-cloned
$newFruit.removeClass("clone");
// set the text
$newFruit.text(fruit);
// append to the correct list in DOM
$(`[data-fruits="${key}"]`).append($newFruit);
});
});
// handler for moving a fruits back and forth
function moveFruit (e) {
// get the category from the data-fruits property on the parent container
var fruitCategory = $(this).parent().data("fruits");
var fruitName = $(this).text();
// detach the fruit element from the DOM and keep it in a variable so we can re-insert later
var $fruit = $(this).detach();
if (fruitCategory === "Random Fruits") {
// get the type number from the original fruits array
var fruitType = fruits.find(fruit => fruit.fruit === fruitName).type;
// find the correct array to place the fruit into
var fruitArr = fruitTypes[fruitTypeMap[fruitType]];
// find the index of the array it is currently in
var fruitIndex = fruitTypes["Random Fruits"].indexOf(fruitName);
// splice out of current array and insert into destination array in 1 line
fruitArr.push(fruitTypes["Random Fruits"].splice(fruitIndex, 1)[0]);
// add movable class so we can toggle it back to Random Fruits on click
$fruit.addClass("movable");
// finally, add to the correct list in the DOM
$(`[data-fruits="${fruitTypeMap[fruitType]}"]`).append($fruit);
}
else {
// find the current array
var fruitArr = fruitTypes[fruitCategory];
// find the index of the fruit in the current array
var fruitIndex = fruitArr.indexOf(fruitName);
// splice out of current array and insert into destination array in 1 line
fruitTypes["Random Fruits"].push(fruitArr.splice(fruitIndex, 1)[0]);
// add back to Random Fruits list
$('[data-fruits="Random Fruits"]').append($fruit);
}
}
// handle click on all fruits that we label as .movable in the red/green lists
$(".red-fruits, .green-fruits").on("click", ".movable", moveFruit);
// handle click on all items in Random Fruits list
$(".random-fruits").on("click", ".fruit-pill", moveFruit);
.clone {
display: none;
}
.fruit-pill {
border-radius: 20px;
padding: 10px 15px;
display: inline-block;
}
.movable {
cursor: pointer;
}
.red-fruits > .fruit-pill {
background-color: rgba(255, 0, 0, 0.6);
}
.red-fruits > .movable {
background-color: rgb(255, 150, 150);
}
.green-fruits > .fruit-pill {
background-color: rgba(0, 255, 0, 0.7);
}
.green-fruits > .movable {
background-color: rgb(200, 255, 175);
}
.random-fruits > .fruit-pill {
background-color: rgba(0, 0, 0, 0.2);
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="fruits-container">
<div class="red-fruits" data-fruits="Red Fruits">
</div>
<div class="green-fruits" data-fruits="Green Fruits">
</div>
<div class="random-fruits" data-fruits="Random Fruits">
</div>
</div>
<div class="fruit-pill clone"></div>

How to auto format my textbox in license format?

I tried searching on the internet for answer but the closest I can find is in this jfiddle
What I wanted to do is when the page loads, the textbox is automatically filled with this words Furniture/Chair/Square. In addition, the user can input some text next to the words like this Furniture/Chair/Square/_ _ _/_ _ _. The user cannot erase the automatically filled words.
This is a work around with some reference from jwa's post and RegEx:
$(function() {
$('label.prefilled input[type="text"][placeholder]').on('input', function() {
var fmt = this.placeholder.split('');
var len = this.placeholder.match(/_/g).length;
var val = this.value.replace(/[^a-z]/gi, '').split('').slice(0, len);
var res = '',
v, f;
while ((v = val.shift()) && (f = fmt.shift())) {
if ('_' === f) {
res += v;
} else {
res += f + v;
fmt.shift();
}
}
res += fmt.join('');
this.value = res;
}).trigger('input');
});
label.prefilled input[type="text"] {
border: none;
outline: none;
}
label.prefilled {
border: 1px ridge gray;
}
div.card {
margin: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="card">
<label class='prefilled'>
Furniture/Chair/Square/<input type="text" placeholder="___/___"/>
</label>
</div>
<div class="card">
<label class='prefilled'>
Electronic/Handheld/<input type="text" placeholder="______/______"/>
</label>
</div>
How do I include numbers?
Use [^a-z0-9] in this line this.value.replace(/[^a-z]/gi, '')
$(function() {
$('label.prefilled input[type="text"][placeholder]').on('input', function() {
var fmt = this.placeholder.split('');
var len = this.placeholder.match(/_/g).length;
var val = this.value.replace(/[^a-z0-9]/gi, '').split('').slice(0, len);
var res = '',
v, f;
while ((v = val.shift()) && (f = fmt.shift())) {
if ('_' === f) {
res += v;
} else {
res += f + v;
fmt.shift();
}
}
res += fmt.join('');
this.value = res;
}).trigger('input');
});
label.prefilled input[type="text"] {
border: none;
outline: none;
}
label.prefilled {
border: 1px ridge gray;
}
div.card {
margin: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="card">
<label class='prefilled'>
Furniture/Chair/Square/<input type="text" placeholder="___/___"/>
</label>
</div>
<div class="card">
<label class='prefilled'>
Electronic/Handheld/<input type="text" placeholder="______/______"/>
</label>
</div>
You can do this by assigning a label to the input field you create. For example...
#text-input {
border: none;
outline: none;
}
label{
border:solid 1px black;
padding-right: 2px;
}
<label for="text-input">
furniture chair square
<input type="text" id="text-input" />
</label>
Use RegExp to solve your problem.
You may add some css or addition text to notice the user error input.
function checkStr(str){
//check pattern
result = str.match(/^Furniture\/Chair\/Square([a-zA-Z\/]+)?/)
if(result == null || result[0].length !== str.length){
//revert the input field to default
document.getElementById('userText').value = "Furniture/Chair/Square"
}
}
<input type="text" value="Furniture/Chair/Square" id="userText" oninput="checkStr(value)"></input>
<p id='asd'></p>

How to check duplicate of my input file upload?

I have this form which has a button for file upload. When you select a file it shows at upload_prev div.
My problem is that when I try to select the same file nothing happens. I would like a validation or kind of non duplication function to run.
I did that. I tried many things and methods like using child nodes and seeing if the inner text is the same. I tried to loop using jquery each and getting the value, but all of them failed. I want to display a message that this file is already in the Box of upload_prev when I select it again.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="https://code.jquery.com/jquery-1.10.1.js"></script>
<link rel="stylesheet" type="text/css" href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css">
<link rel="stylesheet" type="text/css" href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css">
<style type="text/css">
.fileUpload {
position: relative;
overflow: hidden;
margin: 10px;
}
.fileUpload input.upload {
position: absolute;
top: 0;
right: 0;
margin: 0;
padding: 0;
font-size: 20px;
cursor: pointer;
opacity: 0;
background-color: #fff;
filter: alpha(opacity=0);
}
.buttonwrap {
text-align: center;
padding-top: 20px;
float: left;
display: block;
}
.buttonsend:hover {
background-color: rgba(255, 255, 255, 0.2);
color: #225C51;
}
.buttonsend {
text-decoration: none;
color: #fff;
font-size: 18px;
padding-top: 5px;
padding-bottom: 5px;
padding-left: 10px;
padding-right: 10px;
background-color: rgba(72, 133, 130, .5);
}
span {
float: left;
display: flex;
width: 100%;
}
p.closed {
margin: 0 0 0 7px;
cursor: pointer;
}
</style>
<title></title>
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
// TO CLOSE THE SLECTED FILE
$(document).on('click', '.close', function() {
$(this).parents('span').remove();
})
//JUST TO PUT A VALUE IN THE BOX WHICH HAS
document.getElementById("uploadBtn").onchange = function() {
document.getElementById("uploadFile").value = this.value;
};
document.getElementById('uploadBtn').onchange = uploadOnChange;
//document.getElementById('uploadBtn').onchange = myFunction;
function uploadOnChange() {
var filename = this.value;
var lastIndex = filename.lastIndexOf("\\");
if (lastIndex >= 0) {
filename = filename.substring(lastIndex + 1);
}
// alert (filename);
var files = $('#uploadBtn')[0].files;
for (var i = 0; i < files.length; i++) {
$("#upload_prev").append('<span>' + '<div class="hesh">' + files[i].name +'</div>' + '<p class="close">X</p></span>');
}
document.getElementById('filename').value = filename;
document.getElementById("demo").innerHTML = files.length;
}
});//]]>
</script>
</head>
<body>
<FORM METHOD="post" ACTION="" ENCTYPE="multipart/form-data">
<!-- <input id="uploadFile" placeholder="Add files from My Computer" class="steptextboxq3" />-->
<div class="fileUpload btn btn-primary">
<span>Browse</span>
<input id="uploadBtn" type="file" class="upload" multiple="multiple" name="browsefile" />
</div>
<input id="filename" type="text" />
<div id="upload_prev"></div>
<div style="clear:both;"></div>
<div class="buttonwrap">
Send </div>
</FORM>
<p id="demo"></p>
</body>
</html>
This is my fiddle. How can I find a way to do this.
https://jsfiddle.net/Lc5gb7c9/
You can create an array to store files[i].name, use Array.prototype.indexOf() to check if file name has been added to array, if true call alert(), else add file name to array. You can reset array to [] at any point during process.
Note, <div> and <p> elements are not valid content of <span> element
// outside of `onchange`
var arr = [];
for (var i = 0; i < files.length; i++) {
if (arr.indexOf(files[i].name) === -1) {
arr.push(files[i].name)
$("#upload_prev").append('<div>'
+ '<div class="hesh">'
+ files[i].name + '</div>'
+ '<p class="close">X</p></div>');
} else {
alert(files[i].name + " already selected")
}
}
jsfiddle https://jsfiddle.net/Lc5gb7c9/2/
There is a low chance that a file with same name, size, type, modified time to repeat and have different content
const existingFiles = []
function findFile(file) {
return existingFiles.find(function(existingFile) {
return (
existingFile.name === file.name &&
existingFile.lastModified === file.lastModified &&
existingFile.size === file.size &&
existingFile.type === file.type
)
})
}
const input = document.querySelector('input')
input.addEventListener('change', function(e) {
const files = e.target.files
Array.from(files).forEach(function(file) {
const existingFile = findFile(file)
if (existingFile) {
console.error('Existing file: ', existingFile)
return
}
existingFiles.push(file)
console.warn('Added file: ', file)
})
})
<input type="file" />
I think you're running into issues with how your assigning your files to the dom. Remember FileLists are read only, meaning you can't select multiple files then keep going and append them to an existing element.
But you CAN append them to a JavaScript array:
files=[]; files.push(fileList);
So, I've edited your JSFiddle to include this functionality, as well as the check you were asking for:
https://jsfiddle.net/Lc5gb7c9/3/
I would recommend you look at:
http://blog.teamtreehouse.com/uploading-files-ajax for the way to upload via Ajax, as you'll need to create the formData object and then loop through your uploaded_files array and append them to the correct formData key. They are getting file from the html element, but you already have file in the uploaded_files array, so you would do it like:
for (var i = 0; i < uploaded_files.length; i++) {
formData.append('files[]', uploaded_files[i], uploaded_files[i].name);
}
Once that's done, you can make your ajax call.

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