Renaming/removing uploaded files - Vue.js - javascript

The requirement is to rename the files before uploading it to the system. So I tired using v-model but failed. So I came up with the following which is working great just that I cannot retain my input text value. The preventdefault isn't working.
Here I uploaded 3 images and rename them as First, Second and Third.
<div>
<input type="file" #change="addFile" multiple>Choose file
</div>
<div v-if="selectedFiles && selectedFiles.length>0">
<div v-for="(item, index) in selectedFiles">
<span>{{ item.name }}</span>
<input type="text" v-model="" placeholder="Rename File" #change="renameFile(item,event)"/>
<button #click="removeFile(event,item,index)"></button>
</div>
</div>
<button #click="uploadDrawings">Upload Files</button>
data: {
selectedFiles: [],
renameFiles: [],
finalFiles: [],
},
methods: {
addFile(event) {
_.each(Array.from(event.target.files), function (file) {
var existed = _.find(app.selectedFiles, function (item) {
return item.name == file.name;
});
if (!existed) {
app.selectedFiles.push(file);
}
});
},
renameFile(item, event) {
if (app.renameFiles.filter(x => x.oldName == item.name).length > 0) {
var objIndex = app.renameFiles.findIndex(x => x.oldName == item.name);
app.renameFiles[objIndex].newName = event.target.value;
}
else {
app.renameFiles.push({
oldName: item.name,
newName: event.target.value
})
}
},
removeFile(e,item, index) {
e.preventDefault(); // while removing an item, the text value changes.
app.selectedFiles.splice(index, 1);
var objIndex = app.renameFiles.findIndex(x => x.oldName == item.name);
app.renameFiles.splice(objIndex, 1);
},
uploadDrawings() {
app.isLoading = true;
if (app.selectedFiles.length == 0) {
return;
}
_.each(app.selectedFiles, function (item) {
var blob = item.slice(0, item.size, 'image/jpg');
var name = app.renameFiles.filter(x => x.oldName == item.name);
app.finalFiles.push(new File([blob], name[0].newName + '.jpeg', { type: 'image/jpg' }));
});
}
So, On removing item from top to bottom the text box does not retain its value. First was assigned for 091646.
However, the finalFiles has the correct naming files. Its just the textbox which has a problem.
Please help me to retain the textbox values.
Thanks in advance.

Missing keys
The items in the v-for are not explicitly keyed in your markup, so Vue automatically keys them by their index. As a rendering optimization, Vue reuses existing elements identified by their keys. This can cause an issue when an item is added to or removed from the middle of the list, where surrounding items take on new keys equal to their new indices.
Solution
Apply the key attribute to each v-for item using a unique ID (not equal to index). In this case, the index combined with the filename would suffice:
<div v-for="(item, index) in selectedFiles" :key="index + item.name">
Missing v-models
When the template is re-rendered (occurs when removing an item from the middle of the list), the textboxes lose their values. This is because they have no model bound to them.
Solution
Update renameFiles[] to store only strings (instead of objects), where each string corresponds to a file in selectedFiles[] by the same index. That would obviate the file lookup code throughout your methods, so the code would be simplified to this:
export default {
⋮
methods: {
addFile(event) {
this.selectedFiles = Array.from(event.target.files)
},
removeFile(e, item, index) {
this.selectedFiles.splice(index, 1)
this.renameFiles.splice(index, 1)
},
⋮
},
}
That change also enables using renameFiles[] as v-model on the <input>s for the rename strings:
<input type="text" v-model="renameFiles[index]" placeholder="Rename File" />
demo

Related

Cannot read the array property. Objects are not valid as a React child

I am following a tutorial exercise and I got the following error
Objects are not valid as a React child
I know this error is related to the object as I am trying to access the object but it needs an individual item of an object but not sure.
Why cannot the map loop over each item in the array?
Following is my code
var template = <h1>Indecision App</h1>;
var app = {
title: 'Indecision App',
subtitle: 'yo',
options: []
}
let count = 0;
function checkSubtitles (subtitle){
if(subtitle){
return <p>{subtitle}</p>
}else{
return undefined
}
}
function reset(){
count = 0;
reRenderApp();
}
function increaseCount(){
count++;
reRenderApp();
}
function onSubmitHandle(e){
e.preventDefault();
const options = e.target.elements.options;
app.options.push(options);
reRenderApp();
e.target.elements.options.value = ''
}
function removeAll(){
app.options = [];
reRenderApp();
}
function reRenderApp(){
var templateTwo = (
<div>
<h1>{app.title}</h1>
{checkSubtitles(app.subtitle)}
<p>Count: {count}</p>
<p>Array Length: {app.options.length > 0 ? app.options.length : '0 Items'}</p>
<ol>
{app.options.map((item)=>{
return <li key={item}>{item}</li>
})}
</ol>
<hr></hr>
<form onSubmit={onSubmitHandle}>
<input type="text" name="options" />
<input type="submit" value="Push to the Array" />
<input type="reset" value="Empty my list" onClick={removeAll} />
</form>
<button onClick={()=>{
increaseCount();
}}>Increase Count</button>
<button onClick={()=>{
reset();
}}>Reset Count</button>
</div>
)
ReactDOM.render(templateTwo, appRoot)
}
var appRoot = document.getElementById('app');
reRenderApp();
<body>
<div id="app"></div>
<script src="https://unpkg.com/react#16.0.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom#16.0.0/umd/react-dom.development.js"></script>
<script src="./app.js"></script>
</body>
</html>
The main problem is, as you mentioned: Objects are not valid as a React child
But, what is happening?
If we go into:
function onSubmitHandle(e){
e.preventDefault();
// Line 1
const options = e.target.elements.options;
app.options.push(options);
reRenderApp();
// Line 2
e.target.elements.options.value = ''
}
So in Line 1, you're pushing options into the options array.
But, then in Line 2, we can notice options has an attribute (so, it's an object)
So, if you change Line 1, from:
const options = e.target.elements.options;
To this:
const options = e.target.elements.options.value;
It'd work.
Also, to check what I'm saying you have 2 options:
option 1: console.log
function onSubmitHandle(e){
e.preventDefault();
const options = e.target.elements.options;
console.log({ options })
app.options.push(options);
reRenderApp();
e.target.elements.options.value = ''
}
option 2: make that option a valid child of react with JSON.stringify()
<ol>
{app.options.map((item, index)=>{
return <li key={index}>{JSON.stringify(item)}</li>
})}
</ol>
You can do
{app.options.length && app.options.map((item)=>{
return <li key={item}>{item}</li>
})}
But you must be sure that "item" here is not an object as you can't render an object
The reason for this is that your options array is going to be filled with elements as you're pushing the input element with the name of "option" into your array - this elements are objects in JS which you can't render out as list items.
Use React State to store anything that's going to change in the UI - in this case your list of options> So rather than doing
var app = {
title: 'Indecision App',
subtitle: 'yo',
options: []
}
let count = 0;
Do:
const [options, setOptions] = React.useState([]);
const [count, setCount] = React.useState(0);
Title and subtitle are probably not going to change, so just put them in h1 & h2 elements - if they are, then use the state pattern again.
Get rid of the two inputs with types of "submit" & "reset" just use normal button elements instead.
You'll also need an onchange event on your input where the text will go in and each time the onchange event is fired (i.e, when a user types) you'll need to save the input text
const [inputText, setInputText] = React.useState('');
const handleChange = (e) => {
const {value} = e.target;
setInputText(value)
}
<input type="text" value={inputText} onChange={handleChange}/>
Then in your onHandleSubmit function, just have
const onHandleSubmit = () => {
setOptions([...options, inputText]);
setInputText('')
}
This should work

How to perform calculation with values of dynamic input fields?

I have a little problem with my html form code...
In my code, there are few input fields which are generated dynamically. In every input field generated dynamically, there is some numerical value. i need to do some Mathematical calculation with them.
="PE+ROCE+(2-SG)-(4-DY/2)"
This is a pattern of my calculation. In this, PE, ROCE etc are the IDs of Dynamic Input fields generated.
Using values of dynamic input fields generated, I need to perform above calculation.
This calculation has to be executed when the user would click on "Calculate" Input Button.
Then, the final calculated value from the above will be shown in the Output Tag present in bottom of my form code.
I tried to solve this problem on my own. But unfortunately, failed in this task.
somebody can now please help me to solve this problem.
I will be very grateful...
here is my full code of form..
// define the headings here, so we can access it globally
// in the app
let headings = []
// appending the created HTML string to the DOM
function initInputs(headingList) {
jQuery(".fields").append(createInputsHTML(headingList))
}
// the HTMLT template that is going to be appended
// to the DOM
function createInputsHTML(headingList) {
let html = ''
headingList.forEach(heading => {
if (heading !== 'Company') {
html += `<label for="${heading}">${heading}: </label>`
html += `<input id="${heading}">`
html += '<br>'
}
})
return html
}
// receiving data
// this data arrives later in the app's lifecycle,
// so it's the best to return a Promise object
// that gets resolved (check JS Promise for more information)
function getJSON() {
return new Promise(resolve => {
jQuery.get("https://cors-anywhere.herokuapp.com/www.coasilat.com/wp-content/uploads/2019/06/data-1.txt", function(data) {
resolve(JSON.parse(data))
});
})
}
// processing raw JSON data
function processRawData(data) {
return new Promise(resolve => {
const companyData = []
// creating data array
// handling multiple sheets
Object.values(data).forEach((sheet, index) => {
sheet.forEach((company, i) => {
companyData.push({ ...company
})
// create headings only once
if (index === 0 && i === 0) {
Object.keys(company).forEach(item => {
headings.push(item.trim())
})
}
})
})
resolve(companyData)
})
}
$(async function() {
let lists = [];
function initAutocomplete(list) {
const thisKey = 'Company'
$("#company").autocomplete('option', 'source', function(request, response) {
response(
list.filter(item => {
if (item[thisKey].toLowerCase().includes(request.term.toLowerCase())) {
item.label = item[thisKey]
return item
}
})
)
})
}
$("#company").autocomplete({
minLength: 3,
source: lists,
focus: function(event, ui) {
// the "species" is constant - it shouldn't be modified
$("#company").val(ui.item.Company);
return false;
},
select: function(event, ui) {
// handling n number of fields / columns
headings.forEach(heading => {
$('#' + heading).val(ui.item[heading])
})
return false;
}
});
// starting data download, processing and usage
getJSON()
.then(json => {
return processRawData(json)
})
.then(data => {
// just so we see what data we are using
console.log(data)
// make the processed data accessible globally
lists = data
initAutocomplete(lists)
initInputs(headings)
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" />
<div class="ui-widget">
<form id="frm1">
<label for="company">Company: </label>
<input id="company"><br />
<div class="fields"></div>
<input type="submit" id="calculate" value="Calculate">
<p>Final Amount <output name="amount" for="calculation">0</output></p>
</form>
</div>
Try each loop of inputs
$("#Calculate").click(function(){
var peVal,roceVal,sgVal,dyVal;
jQuery(".fields input").each(function (){
var idHeading=$(this).attr("id");
if(idHeading=="Your ID for PE input"){
peVal=parseInt($(this).val());
}
if(idHeading=="Your ID for ROCE input "){
roceVal=parseInt($(this).val());
}
if(idHeading=="Your ID for SG input"){
sgVal=parseInt($(this).val());
}
if(idHeading=="Your ID for DY input"){
dyVal=parseInt($(this).val());
}
});
var output=peVal+roceVal+(2-sgVal)-(4-dyVal/2);
});

Angular 2 How to remove file from files of input type file multiple?

How to remove specific file from files selected with input type with multiple attribute?
<input type="file" (change)="onFileChange($event)" #fileInput multiple>
I want to delete one of the selected file.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file
https://jsfiddle.net/Sagokharche/eL3eg6k4/
Do you need it to be impossible to choose? Then use HTML Input file accept property. accept="image/png" for instance.
Or you want it to filter from the input after the user selected it?
Then you should use a custom directive or check for the file types in the ts code upon upload.
EDIT
in that case, in your code:
onFileChange(event) {
const fileList = event.target.files;
console.log("User selected fileList:", fileList)
Array.from(fileList).filter(
item => {
console.log("file mime type:", item['type'])
})
const filesToUpload = Array.from(fileList).filter(
item => { return item['type'] != "application/zip" })
console.log("reduced list:", filesToUpload)
}
Working stackblitz example here.
You can access the inputs FileList-object in .ts side like this:
onFileChange(event) {
console.log(event.srcElement.files);
}
Edit:
If you are looking for a solution how to make dynamic form (add and delete inputs), then have a look at this answer and demo:
Angular 4 Form FormArray Add a Button to add or delete a form input row
In your hmtl code
<div class="row">
<div class="col-md-2 productAddfromImages" *ngFor='let url of imageurls; let i = index'>
<img class="img-fluid" [src]="url.base64String">
<a (click)="removeImage(i)" class="btn btn-xs btn-danger">Remove</a>
</div>
</div>
Remove function
removeImage(i) {
this.imageurls.splice(i, 1);
}
Add Function
onSelectFile(event) {
if (event.target.files && event.target.files[0]) {
var filesAmount = event.target.files.length;
for (let i = 0; i < filesAmount; i++) {
var reader = new FileReader();
reader.onload = (event: any) => {
this.imageurls.push({ base64String: event.target.result, });
}
reader.readAsDataURL(event.target.files[i]);
}
}
}
}
For more details:https://findandsolve.com/articles/how-to-upload-and-remove-multiple-image-using-anular-code-example

Check and uncheck checkbox with Angular

In my form I have a table with checkbox in all of these columns. I have 3 <tr> and each <tr> has its ng-repeate calling the webservice to display the clones (Json data).
When I click on a checkbox I generate a js array which records id using this code :
checkoptions (array, model) {
angular.forEach(array, (value, key) => {
if (array[key].checked) {
model.push(array[key].id)
}
})
And in HTML :
<tr ng-repeat="developer in $ctrl.developers">
<td>{{developer.label}}</td>
<td>
<input type="checkbox" id="{{developer.id}}"
ng-change="$ctrl.checkoptions($ctrl.developers,$ctrl.employees.developers)"
ng-model="developer.checked">
<label for="{{developer.id}}"></label>
</td>
It works, but the problem is that when I uncheck a checkbox it is not removed from the js array
I included an else part to remove from the array:
http://jsfiddle.net/x9m1nqvp/1/
$scope.checkoptions = function (array, model) {
angular.forEach(array, (value, key) => {
if (array[key].checked) {
var index = model.indexOf(array[key].id);
if(index == -1)
model.push(array[key].id)
}
else {
var index = model.indexOf(array[key].id);
if(index >=0)
model.splice(index, 1);
}
})
While Everton's answer gets the job done, it is a bit redundant checking every item in the array, every time a single checkbox changes state. You don't really have to update for every single item in the array.
Here is an example, where only the checkbox that's actually toggled, is added or removed from the employees.developers array (Note: no need for the redundant angular.forEach):
$scope.checkoption = function (developer){
if (developer.checked) {
var index = $scope.employees.developers.indexOf(developer.id);
if(index == -1)
$scope.employees.developers.push(developer.id)
} else {
var index = $scope.employees.developers.indexOf(developer.id);
if(index >=0)
$scope.employees.developers.splice(index, 1);
}
}
and how this is used in the html:
<tr ng-repeat="developer in developers">
<td>{{developer.label}}</td>
<td>
<input type="checkbox" id="{{developer.id}}"
ng-change="checkoption(developer)"
ng-model="developer.checked">
<label for="{{developer.id}}"></label>
</td>
</tr>

Angular 1: Last checkbox doesn't stay checked after page refresh

I am saving all data into localStorage. When a checkbox is checked function is called to change items state. It works fine. However after page refresh, last checked item gets unchecked (or if it was unchecked, it gets checked) while others are working just fine. Why does that 1 last action gets ignored after page is refreshed?
Here is codepen: http://codepen.io/kunokdev/pen/vGeEoY?editors=1010
(add few items and click on "click me" for all of them and then refresh page, last action will be ignored)
The view:
<div ng-app="TaskApp" ng-controller="ToDoCtrl">
<form>
<input type="text" ng-model="toDoItem">
<input type="submit" ng-click="addToDoItem()">
</form>
<div>
<ul>
<div
ng-repeat="item in toDoItems |
orderBy: 'createdAt'
track by item.createdAt">
<b>Content:</b> {{item.content}} <br>
<b>Completed?</b> {{item.completed}}
<md-checkbox ng-model="item.completed" ng-click="toggleToDoItem(item.completed)" aria-label="todo-checkbox">
CLICK ME
</md-checkbox>
</div>
</ul>
</div>
</div>
And JS:
var ls = {};
ls.get = function(key) {
return JSON.parse(localStorage.getItem(key));
};
// sets or updates a value for a key
ls.set = function(key, val) {
localStorage.setItem(key, JSON.stringify(val));
};
// returns true if value is set, else false
ls.isSet = function(key) {
var val = ls.get(key);
return ( null === val || 'undefined' === typeof val) ? false : true;
};
// removes a set item
ls.remove = function(key) {
localStorage.removeItem(key)
};
var TaskApp = angular.module('TaskApp', [
'ngMaterial',
'taskAppControllers'
]);
var taskAppControllers = angular.module('taskAppControllers',[]);
taskAppControllers.controller('ToDoCtrl', ['$scope',
function($scope){
//
loadToDoItems = function(){
var data = ls.get("toDoData");
if (data == null) data = [];
return data;
};
//
$scope.toDoItems = loadToDoItems();
//
$scope.addToDoItem = function(){
var toDoItems = $scope.toDoItems;
var newToDoItem = {
"content" : $scope.toDoItem,
"createdAt" : Date.now(),
"completed" : false
}
toDoItems.push(newToDoItem);
ls.set("toDoData", toDoItems);
$scope.toDoItem = "";
};
//
$scope.toggleToDoItem = function(item){
console.log('test');
var toDoItems = $scope.toDoItems;
for (var i = 0; i < toDoItems.length; i++)
if (toDoItems[i].createdAt === item){
if (toDoItems[i].completed == true)
toDoItems[i].completed = false;
else
toDoItems[i].completed = true;
}
ls.set('toDoData', toDoItems);
};
//
}]);
md-checkbox is designed to toggle whatever you put in ng-model so with your code, md-checkbox was toggling the completed property and then you were changing it back again in your $scope.toggleToDoItem function. Why this worked for all the items except the last clicked I am unsure.
So I changed the ng-click to only save the items to local storage and still got the same problem which leads to me believe the problem is caused by using ng-click on an md-checkbox.
<md-checkbox ng-model="item.completed" ng-click="saveToLocalStorage()" aria-label="todo-checkbox">
CLICK ME
</md-checkbox>
$scope.saveToLocalStorage = function() {
ls.set('toDoData', $scope.toDoItems);
};
So I removed the ng-click and set up a watch on $scope.toDoItems.
<md-checkbox ng-model="item.completed" aria-label="todo-checkbox">
$scope.$watch("toDoItems", function() {
ls.set("toDoData", $scope.toDoItems);
}, true);
Codepen
-- EDIT --
Just read the documentation and feel like an idiot, you should use ng-change instead of ng-click. From the docs regarding ng-change:
Angular expression to be executed when input changes due to user interaction with the input element.
That being said, the above about not needing to toggle the completed property yourself still stands.
You are passing item.completed (in the HTML) to your toggleToDoItem(item) method. In your array loop, you then compare the item.Created field to the item.completed parameter. This is comparing a Date type to a Bool. How is that supposed to work?

Categories