jQuery saving data and loading every refresh page - javascript

Hey im really newbie of walking around in js, saw a nice code about to-do list and would like to save it in every refresh page (in local storage). Have tried savy.js plugin but it doesn't really work. Was thinking about making some json file but don't really know how it would work in jQuery. here is my code:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="list">
<input type="text" class="txtb" placeholder="Add a task">
<div class="notcomp">
<h3>Not Completed</h3>
</div>
<div class="comp">
<h3>Completed</h3>
</div>
</div>
<script type="text/javascript">
$(".txtb").on("keyup", function(e) {
if (e.keyCode == 13 && $(".txtb").val() != "") {
var task = $("<div class='task'></div>").text($(".txtb").val());
var del = $("<i class='fas fa-trash-alt'></i>").click(function() {
var p = $(this).parent();
p.fadeOut(function() {
p.remove();
})
});
var check = $("<i class='fas fa-check'></i>").click(function() {
var p = $(this).parent();
p.fadeOut(function() {
$(".comp").append(p);
p.fadeIn();
});
$(this).remove();
});
task.append(del, check);
$(".notcomp").append(task);
$(".txtb").val("");
}
});
</script>
Aprieciate for any help.

try this code or check the example at Task List
HTML
<div class="list">
<input type="text" class="txtb" placeholder="Add a task">
<div class="notcomp">
<h3>Not Completed</h3>
</div>
<div class="comp">
<h3>Completed</h3>
</div>
</div>
jQuery
$(document).ready(function() {
var data = localStorage.getItem("todo");
if (data != "" && data != null) {
data = JSON.parse(data);
for (const [key, value] of Object.entries(data)) {
insertTask(value);
}
} else {
data = [];
}
function insertTask(data) {
var task = $("<div class='task'></div>").text(data.value);
var del = $("<i class='fa fa-trash' ></i>").click(function() {
removeData(data.id);
$(this)
.parent(".task")
.fadeOut("slow", function() {
$(this).remove();
});
});
task.append(del);
$(".notcomp").append(task);
}
function removeData(id) {
console.log(id);
for (const [key, value] of Object.entries(data)) {
if (value.id === id) {
data.splice(key, 1);
localStorage.setItem("todo", JSON.stringify(data));
return false;
}
}
}
$(".txtb").on("keyup", function(e) {
if (e.keyCode == 13 && $(".txtb").val() != "") {
let val = $(".txtb").val();
var unix = Math.round(+new Date() / 1000);
var taskData = {
value: val,
id: unix
};
data.push(taskData);
insertTask(taskData);
localStorage.setItem("todo", JSON.stringify(data));
$(".txtb").val("");
}
});
});

Related

How to persist selection checkbox state when paging or changing tab on the kendo grid

I want to persist selection of checkbox while paging or moving on other tab in kendo grid .I have referred "How to keep current checkbox state when paging on the grid" here and but i didn't get value of checked and checkbox and also confused with the steps.Please guide in detail.I have attached code below.I have attached script code kendo ui code and html code below.Also thought to use Session to store values of selected checkbox but i don't know is it right way or not.
Please guide me as soon as possible.
<div class="dashboardCharts" id="grid-display">
<div class="count-detail-top right">
<div class="count-detail-bg right">
<ul id="ulOptions">
<li id="Employee" data-type="employee">Employee</li>
<li id="Visitor" data-type="visitor">Visitor</li>
</ul>
</div>
</div>
#(Html.Kendo().Grid<xyz.Models.abcModel>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(c => c.Employee_id).Title("Alert On").Width(200)
.ClientTemplate("<input type=\"checkbox\" class=\"checkbox\" data-id=\"#= Employee_id#\"/>").Sortable(false);
columns.Bound(c => c.Employee_name).Title("Employee Name");
})
.NoRecords("No Records Found")
.Events(e => e.DataBound("onDataBound"))
.DataSource(dataSource => dataSource
.Transport(transport =>
transport
.Read(read => read.Url(DataUrl))
.ParameterMap("parameterMap")
))
)
</div>
//code in script :
<script>
function onDataBound(e) {
$(".checkbox").bind("click", function (e) {
e.stopPropagation();
$(e.target).closest("tr").toggleClass("k-state-selected");
var tr = $(e.target).closest("tr");
var chk = $(tr).find(".checkbox");
var selected = $(chk).attr("data-id");
var a = selectedIDs.includes(selected);
if (a != true) {
if ($(chk).prop("checked")) {
selectedIDs.push(selected);
}
else {
selectedIDs.pop(selected);
}
}
});
var gridDataView = $("#grid").data().kendoGrid.dataSource.view();
for (var i = 0; i < gridDataView.length; i++) {
var panelApplicationId = gridDataView[i].Checkbox;
if (ShouldBeChecked(panelApplicationId)) {
$('#grid tr td input').eq(i).prop("checked", true);
}
}
}
$(document).on('click', 'input.checkbox', function (e) {
var checked = $(this).prop("checked");
var gridDataView = $("#grid").data().kendoGrid.dataSource.view();
console.log(gridDataView);
var idx = $(this).closest("tr").find("td:nth-child(1)").text();
var gridData = $("#grid").data().kendoGrid.dataSource.data();
for (var i = 0; i < gridData.length; i++) {
if (gridData[i].ID == idx) {
gridData[i].Checkbox = checked;
break;
}
}
});
function ShouldBeChecked(panelApplicationId) {
var shouldBeChecked = false;
var gridData = $("#grid").data().kendoGrid.dataSource.data();
for (var i = 0; i < gridData.length; i++) {
if (gridData[i].Checkbox == panelApplicationId) {
if (gridData[i].Checkbox) {
shouldBeChecked = true;
}
break;
}
}
return shouldBeChecked;
}
</script>
code for selected checkbox and and not selected checkbox.
<input type="checkbox" class="checkbox" data-id="34" checked="checked">
<input type="checkbox" class="checkbox" data-id="30">
As mentioned by OP in question-comment as of the 2017 R2 release, there is a grid-option persistselection
Kendo-versions before that, can add their own code, storing the selection in the change-event, and restoring it in the databoundevent as shown by Kendo in persist-row-selection:
change: function (e, args) {
var grid = e.sender;
var items = grid.items();
items.each(function (idx, row) {
var idValue = grid.dataItem(row).get(idField);
if (row.className.indexOf("k-state-selected") >= 0) {
selectedOrders[idValue] = true;
} else if (selectedOrders[idValue]) {
delete selectedOrders[idValue];
}
});
},
dataBound: function (e) {
var grid = e.sender;
var items = grid.items();
var itemsToSelect = [];
items.each(function (idx, row) {
var dataItem = grid.dataItem(row);
if (selectedOrders[dataItem[idField]]) {
itemsToSelect.push(row);
}
});
e.sender.select(itemsToSelect);
}
(See also this SO-question.)

Why isn't the addEventListener calling my addItem function?

It was working fine a while ago, but now it isn't. The console isn't giving any errors either. I added a console.log string
console.log("You can't reach me!!");
to track the flow of execution but the string stopped being displayed when placed in the addItem function and the + button is clicked which makes me suspect that the addItem function isn't being called.
eventListener:
document.querySelector(".button").addEventListener('click', addItem);
the addItem function:
let controller = (function(budgetCtrl, uiCtrl){
let input,newItem;
let addItem = function(){
// 1. Get the field input data
console.log("You can't reach me!!");
input = uiCtrl.getInput();
if(input.description !="" && !isNaN(input.value) && input.value > 0){
// 2. Add the item to the budget budgetController
newItem = budgetCtrl.addItem(input.type, input.description, input.value);
// 3. Add the item to the UI
uiCtrl.addListItem(newItem, input.type);
// 4. Clear the fieldsArray
uiCtrl.clearFields();
// 5.Calculate and update the budget
updateBudget();
}
}
I added the entire code below in case it was needed.
the html file
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Budget App</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="top">
<div class="total">money</div>
<div class="green">
<span class="left">INCOME $ </span><span class="right, income-budget">+ 4,300.00</span>
</div>
<div class="red">
<span class="left">EXPENSES $ </span><span class="right, expense-budget">- 1954.46</span>
</div>
</div>
<div class="middle">
<select class="operation">
<option value="exp">-</option>
<option selected value="inc">+</option>
</select>
<input class="description" type="text" placeholder="Add description">
<input class="value" type="number" placeholder="value" min ="0">
<button class="button">+</button>
</div>
<div class="bottom">
<div class="bottom-left">
<h3>INCOME</h3>
<div class="income-list">
<!--
<div id="income-0" class="inline">
<div class="item-description">Salary</div>
<div class="item-value">+2,100.00</div>
<button type="button">X</button>
</div>
<!-->
</div>
</div>
<div class="bottom-right">
<h3>EXPENSES</h3>
<div class="expense-list">
<!--
<div id="expense-0" class="inline">
<div class="item-description">Bought car</div>
<div class="item-value">-2,100.00</div>
<button type="button">X</button>
</div>
<!-->
</div>
</div>
</div>
<script src="app.js" charset="utf-8"></script>
</body>
</html>
In case you need the entire javascript file
let budgetController = (function(){
let Expense = function(id, description, value){
this.id = id;
this.description = description;
this.value = value;
};
let Income = function(id, description, value){
this.id = id;
this.description = description;
this.value = value;
};
let calculateTotal = function(type){
let sum = 0;
data.allItems[type].forEach(function(current){
sum += current.value;
});
data.totals[type] = sum;
};
let data = {
allItems: {
exp:[],
inc:[]
},
totals: {
exp: 0,
inc:0
},
budget: 0
}
// Public method that allows other modules to add a new item to the data struc
return{
addItem: function(type, description, value){
let newItem, ID;
// Create a new ID
if (data.allItems[type].length > 0){
// I don't understand the .id in the following line of code
ID = data.allItems[type][data.allItems[type].length - 1].id + 1;
} else{
ID = 0;
}
// Create new item based on 'inc' or 'exp'
if(type === 'exp'){
newItem = new Expense(ID, description, value);
}
else if( type === 'inc'){
newItem = new Income(ID, description, value);
}
// Add item to the data structure
data.allItems[type].push(newItem);
// Return the new element
return newItem;
},
calculateBudget: function(){
// calculate total income and expenses
calculateTotal('exp');
calculateTotal('inc');
// Calculate the budget: income - EXPENSES
data.budget = data.totals.inc - data.totals.exp;
},
getBudget: function(){
return{
budget: data.budget,
totalInc: data.totals.inc,
totalExp: data.totals.exp
}
},
testing: function(){
console.log(data);
}
};
})();
let uiController = (function(){
return{
getInput: function(){
return{
type: document.querySelector('.operation').value,
description: document.querySelector('.description').value,
value: parseFloat(document.querySelector('.value').value)
};
},
addListItem: function(obj, type){
let HTML, listType;
// Create htML string with placeholder text
if(type === 'inc'){
element = '.income-list';
listType = 'income';
}else{
element = '.expense-list';
listType = 'expense';
}
HTML = '<div id="%listType%-%id%" class="inline">' +
'<div class="item-description">%description%</div>' +
'<div class="item-value">%value%</div>' +
'<button type="button">X</button>' +
'</div>'
// Replace the placeholder text with the actual data
HTML = HTML.replace('%listType%', listType)
HTML = HTML.replace('%id%', obj.id);
HTML = HTML.replace('%description%', obj.description);
HTML = HTML.replace('%value%', obj.value);
// Insert the htML into the DOM
document.querySelector(element).insertAdjacentHTML('beforeend', HTML);
},
clearFields: function(){
let fields, fieldsArray;
// querySelectorAll returns a list not an array
fields = document.querySelectorAll('.description, .value');
fieldsArray = Array.prototype.slice.call(fields);
fieldsArray.forEach(function(current, index, array){
current.value ="";
});
// Sets focus to the descriptions field
fieldsArray[0].focus();
},
displayBudget: function(object){
document.querySelector('.total').innerHTML = object.budget;
document.querySelector('.income-budget').innerHTML = object.totalInc;
document.querySelector('.expense-budget').innerHTML = object.totalExp;
}
}
})();
let controller = (function(budgetCtrl, uiCtrl){
let input,newItem;
let addItem = function(){
// 1. Get the field input data
console.log("You can't reach me!!");
input = uiCtrl.getInput();
if(input.description !="" && !isNaN(input.value) && input.value > 0){
// 2. Add the item to the budget budgetController
newItem = budgetCtrl.addItem(input.type, input.description, input.value);
// 3. Add the item to the UI
uiCtrl.addListItem(newItem, input.type);
// 4. Clear the fieldsArray
uiCtrl.clearFields();
// 5.Calculate and update the budget
updateBudget();
}
}
let updateBudget = function(){
// 1. Calculate the budgetCtrl
budgetCtrl.calculateBudget();
// 2. Return the budget
let budget = budgetCtrl.getBudget();
// 3. Display the budget on the UI
uiCtrl.displayBudget(budget);
}
//let ctrlDeleteItem = function(event){
// console.log(event.target);
//}
let enterKey = function(event){
if(event.keyCode === 13 || event.which === 13){// older browers use which
addItem();
}
}
return {
init: function(){
const budget = {budget: 0, totalInc:0, totalExp:0};
uiCtrl.displayBudget(budget);
}
};
document.querySelector(".button").addEventListener('click', addItem);
document.addEventListener('keypress', enterKey);
document.querySelector('.bottom').addEventListener('click', ctrlDeleteItem);
})(budgetController, uiController);
controller.init();
Your code never reaches addEventListener because you have a return right before. It's pretty much unreachable code.
return {
init: function(){
const budget = {budget: 0, totalInc:0, totalExp:0};
uiCtrl.displayBudget(budget);
}
};
//unreachable..
document.querySelector(".button").addEventListener('click', addItem);
document.addEventListener('keypress', enterKey);
document.querySelector('.bottom').addEventListener('click', ctrlDeleteItem);
Solution
Switch around the unreachable code with your return.
document.querySelector(".button").addEventListener('click', addItem);
document.addEventListener('keypress', enterKey);
document.querySelector('.bottom').addEventListener('click', ctrlDeleteItem);
return {
init: function(){
const budget = {budget: 0, totalInc:0, totalExp:0};
uiCtrl.displayBudget(budget);
}
};

Store text from dynamically created textareas in localStorage

Problem - I have 2 buttons addNew and submitText. I have created a javascript function for each of these two buttons. The addNewcreates textareas with unique ids (note0, note1...). The submitText is supposed to submit the text from all the dynamically created textareas in localStorage in the (key, value) format (notesList0, data), (notesList1, data) and so on. The code is as follows -
$(document).ready(function(){
var note_id = 0;
$("#addNew").click(function () {
note_id++;
var inputField = $('<p align="center"><br><textarea id="note' + note_id + '" placeholder="Enter note, max limit 200 words" class="form-control" rows="5" style="width:80%;overflow:auto;"></textarea></p>');
$('#textFields').append(inputField);
});
document.getElementById("submitText").addEventListener("click", function(){
var id=0, counter;
var flag=true;
for(counter=0; counter<=note_id; counter++) {
var textData = document.getElementById("note"+counter).value;
alert(textData);
while(flag==true)
{
if(localStorage.getItem("notesList"+id)!=null) {
id++;
}
else {
localStorage.setItem("notesList"+id, textData);
flag=false;
alert("Text saved");
}
}
}
} , false);
});
The addNew works but submitText only saves value of the first textarea. Where am I going wrong?
I guess it's because of flag staying "false" after the first loop:
$(document).ready(function(){
var note_id = 0;
$("#addNew").click(function () {
note_id++;
var inputField = $('<p align="center"><br><textarea id="note' + note_id + '" placeholder="Enter note, max limit 200 words" class="form-control" rows="5" style="width:80%;overflow:auto;"></textarea></p>');
$('#textFields').append(inputField);
});
document.getElementById("submitText").addEventListener("click", function(){
var id=0, counter;
var flag=true;
for(counter=0; counter<=note_id; counter++) {
var textData = document.getElementById("note"+counter).value;
alert(textData);
while(flag==true)
{
if(localStorage.getItem("notesList"+id)!=null) {
id++;
}
else {
localStorage.setItem("notesList"+id, textData);
flag=false;
alert("Text saved");
}
}
flag = true;
}
} , false);
});
Use the following for the submit function to make it work for dynamically created elements:
$(document).on("click", "#submitText", function(){
// Do stuff
})
Make sure the ID is only used once on the page. Otherwise switch to class definition.
$(document).ready(function(){
var note_id = 0;
$("#addNew").click(function () {
note_id++;
var inputField = $('<p align="center"><br><textarea id="note' + note_id + '" placeholder="Enter note, max limit 200 words" class="form-control" rows="5" style="width:80%;overflow:auto;"></textarea></p>');
$('#textFields').append(inputField);
});
document.getElementById("submitText").addEventListener("click", function(){
var id=0, counter;
for(counter=0; counter<=note_id; counter++) {
var flag=true;
var textData = $("#note"+counter).val();
if(textData != undefined && textData != '') {
while(flag==true)
{
if(localStorage.getItem("notesList"+id)!=null) {
id++;
}
else {
localStorage.setItem("notesList"+id, textData);
flag=false;
alert("Text saved");
}
}
}
}
} , false);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="addNew">Add new</span>
<span id="submitText">Submit</span>
<div id="textFields"></div>
In case you get error when executing the code, check this link:
Failed to read the 'localStorage' property from 'Window'

Angularjs devade tags when user put comma

I have a case in which I need to divide tags when the user put a comma separation, for the moment the user can only add tags one by one, what I want to do is allows user to enter more than one tag in the input separated by a comma:
This is what I have now :
this is what I want to do :
what I have so far :
<div class="form-group">
<label>Mes centres d'intérêt</label>
<div class="input-group" style="margin-bottom: 8px;">
<input id="tagInsert" type="text" name="newTag" ng-model="newTag" ng-model-options="{debounce: 100}" typeahead="tag for tag in getTags($viewValue)" class="form-control" typeahead-loading="loadingTags" ng-keydown="addInterestOnEvent($event)" ng-disabled="interestLimit" autocomplete="off">
<span class="input-group-btn"><span class="btn btn-primary" ng-click="addInterest()" analytics-on="click" ng-disabled="interestLimit" analytics-event="Ajout Interet" analytics-category="Profil">Ajouter</span></span>
</div>
<p class="form__field__error" ng-show="interestLimit">Vous avez atteint la limite de 10 centres d'intérêt.</p>
<ul class="tags">
<li class="tag" ng-repeat="name in user.interests track by $index">{{ name }} <i class="icon-close" ng-click="removeInterest($index)" analytics-on analytics-event="Supprimer Interet" analytics-category="Profil"></i></li>
</ul>
</div>
My controller :
$scope.getTags = function (name) {
return $http.get('/api/tags/' + name.replace('/', '')).then(function (result) {
var tags = result.data;
for (var i = tags.length; i--; ) {
var tagName = tags[i].name;
if ($scope.user.interests.indexOf(tagName) !== -1) tags.splice(i, 1);
else tags[i] = tagName;
}
return tags;
});
};
$scope.removeInterest = function (id) {
$scope.interestLimit = false;
$scope.user.interests.splice(id, 1);
}
$scope.addInterest = function () {
if ($scope.interestLimit) return;
var element = $document[0].getElementById('tagInsert'),
value = element.value;
if (value.length) {
element.value = '';
if ($scope.user.interests.indexOf(value) === -1) {
$scope.user.interests.push(value);
$scope.interestLimit = $scope.user.interests.length === 10;
}
}
};
$scope.addInterestOnEvent = function (event) {
if (event.which !== 13) return;
event.preventDefault();
$scope.addInterest();
};
$scope.remove = function () {
$scope.confirmModal = Modal.confirm.delete(function () {
User.remove(function () {
submit = true;
Auth.logout();
$location.path('/');
});
})('votre compte');
};
You should split value with comma and do for loop.
Change "addInterest" function like this:
$scope.addInterest = function () {
if ($scope.interestLimit) return;
var element = $document[0].getElementById('tagInsert'),
value = element.value.split(',');
if (value.length) {
element.value = '';
for (var i = 0; i < value.length; i++) {
if ($scope.interestLimit) break;
if ($scope.user.interests.indexOf(value[i]) === -1) {
$scope.user.interests.push(value[i]);
$scope.interestLimit = $scope.user.interests.length === 10;
}
}
}
};
As far as I understand , you want to split text into string array by comma
Try this code please
<input id='tags' type="text" />
<input type="button" value="Click" onclick="seperateText()" />
<script>
function seperateText(){
var text= document.getElementById("tags").value;
var tags = text.split(',');
console.log(text);
console.log(tags);
}
</script>

Cannot get file type input to clear

So i've looked at the other questions and I am too far along in my page to try something else. I have an input type of file and I am trying to clear it when the user decides that they do not want to use it. I have some other functionality that is set to show the file name, size, etc... based on the FILE API but for some reason I cannot get the input to clear. I am trying a few different ways to clear it but still nothing. Anyone see what I am doing wrong. I have a jQuery check to check the value of the input and it never clears. The only thing I can think of is that I am using the standard hide the input and using a link so I can actually style the file input button.
Here is the FIDDLE:
JS FIDDLE
Here is the HTML:
<div>
<label id="huf1-label">fileGroup 1</label>
<input type="file" id="fileElem" accept="image/*" style="display:none"
onchange="handleFiles(this.files)" name="file">
<a href="#" id="fileSelect" class="c1-button right gray" tabindex="0">Select
File to
Upload<span class="icon-checkmark"></span> </a>
</div>
<div>
<label id="huf1Btn-label">
<div class="fileInfoContainer">
<ul>
<li>
<div id="fileList" class="fileInfoContainer">
</div>
</li>
</ul>
</div>
</label>
<button id="removeFile1" class="c1-button red left-icon"
aria-controls="huf1">
<span class="icon-remove"></span><b> Cancel</b>
<span class="hidden">fileGroup 1</span>
</button>
<div class="filename"></div>
Here is the script:
window.URL = window.URL || window.webkitURL;
//BEGIN - fileSelect1 and handleFile
var fileSelect = document.getElementById("fileSelect"),
fileElem = document.getElementById("fileElem"),
fileList = document.getElementById("fileList");
fileSelect.addEventListener("click", function (e) {
if (fileElem) {
fileElem.click();
}
e.preventDefault(); // prevent navigation to "#"
}, false);
function handleFiles(files) {
if (!files.length) {
fileList.innerHTML = "<p></p>";
} else {
$('#fileList').empty().append();
var list = document.createElement("ul");
for (var i = 0; i < files.length; i++) {
var li = document.createElement("li");
list.appendChild(li);
var info = document.createElement("span");
info.innerHTML = files[i].name + ": " + files[i].size + " bytes";
li.appendChild(info);
}
fileList.appendChild(list);
$("#removeFile1").click(function (event) {
event.preventDefault();
$("#fileList").empty();
$("#removeFile1").find('b').html('Cancel');
$('#fileElem').each(function() {
$(this).val();
});
document.getElementById("fileElem").value = "";
document.getElementById("fileSelect").value = "";
console.log('#fileList' + 'was deleted');
console.log('#fileElem' + 'was deleted I hope');
// console.log($(this)+'#fileList'.val());
});
}
};
$("#fileElem").change(function(){
if (this.val == "" ) {
$("#removeFile1").find('b').html('Cancel');
} else {
$("#removeFile1").find('b').html('Remove this file');
}
});
$(function() {
$("input:file").change(function (){
var fileName = $(this).val();
$(".filename").html(fileName);
});
});
I Corrected It this is the answer Try this....
The problem you are facing is this error...
Uncaught ReferenceError: handleFiles is not defined
So I canged it like this...
HTML
<div>
<label id="huf1-label">fileGroup 1</label>
<input type="file" id="fileElem" accept="image/*" style="display:none"
name="file">
<a href="#" id="fileSelect" class="c1-button right gray" tabindex="0">Select
File to
Upload<span class="icon-checkmark"></span> </a>
</div>
<div>
<label id="huf1Btn-label">
<div class="fileInfoContainer">
<ul>
<li>
<div id="fileList" class="fileInfoContainer">
</div>
</li>
</ul>
</div>
</label>
<button id="removeFile1" class="c1-button red left-icon"
aria-controls="huf1">
<span class="icon-remove"></span><b> Cancel</b>
<span class="hidden">fileGroup 1</span>
</button>
<div class="filename"></div>
</div>
SCRIPT
window.URL = window.URL || window.webkitURL;
//BEGIN - fileSelect1 and handleFile
var fileSelect = document.getElementById("fileSelect"),
fileElem = document.getElementById("fileElem"),
fileList = document.getElementById("fileList");
fileSelect.addEventListener("click", function (e) {
if (fileElem) {
fileElem.click();
}
e.preventDefault(); // prevent navigation to "#"
}, false);
$("#fileElem").change(function() {
var files=this.files;
if (!files.length) {
fileList.innerHTML = "<p></p>";
} else {
$('#fileList').empty().append();
var list = document.createElement("ul");
for (var i = 0; i < files.length; i++) {
var li = document.createElement("li");
list.appendChild(li);
var info = document.createElement("span");
info.innerHTML = files[i].name + ": " + files[i].size + " bytes";
li.appendChild(info);
}
fileList.appendChild(list);
$("#removeFile1").click(function (event) {
event.preventDefault();
$("#fileList").empty();
$("#removeFile1").find('b').html('Cancel');
$('#fileElem').each(function() {
$(this).val();
});
document.getElementById("fileElem").value = "";
document.getElementById("fileSelect").value = "";
console.log('#fileList' + 'was deleted');
console.log('#fileElem' + 'was deleted I hope');
// console.log($(this)+'#fileList'.val());
});
}
});
$("#fileElem").change(function(){
if (this.val == "" ) {
$("#removeFile1").find('b').html('Cancel');
} else {
$("#removeFile1").find('b').html('Remove this file');
}
});
$(function() {
$("input:file").change(function (){
var fileName = $(this).val();
$(".filename").html(fileName);
});
});
JSFIDDLE LINK HERE
This is the Link for updated JSFIDDLE...

Categories

Resources