Using HTML5 code, I'm unable to delete from the database even though the onsuccess event is triggered.My delete code is as below:
btnDelete.addEventListener("click", function(){
//alert("At Delete function");
var AadharNumber = document.getElementById("AadharNumber").value;
var transaction = db.transaction("CustDetails",IDBTransaction.READ_WRITE);
var objectStore = transaction.objectStore("CustDetails");
var request = objectStore.delete(AadharNumber);
request.onsuccess = function(event){
alert( "Aadhar Number: "+ AadharNumber + " deleted from the database");
};
},false);
Then when i click the print button after the delete, i still get to see the same records.Below is my print function.
btnPrint.addEventListener("click", function () {
var output = document.getElementById("printOutput");
output.textContent = "";
var transaction = db.transaction("CustDetails", IDBTransaction.READ_WRITE);
var objectStore = transaction.objectStore("CustDetails");
var request = objectStore.openCursor();
request.onsuccess = function(event) {
var cursor = event.target.result;
if (cursor) {
output.textContent += "<li>""Aadhar Number: " + cursor.key + " is " + cursor.value.name + "</li>";
cursor.continue();
}
else {
console.log("No more entries!");
}
};
}, false);
My html code is as below:
<body><center>
<div id="container">
<label for="txtName">
Name:
</label>
<input type="text" id="txtName" name="txtName" />
<br />
<label for="txtEmail">
Email:
</label>
<input type="text" id="txtEmail" name="txtEmail" />
<br />
<input type="button" id="btnAdd" value="Add Record" />
<br />
<label for="AadharNumber">
ID:
</label>
<input type="text" id="AadharNumber" name="txtAadharNumber" />
<input type="button" id="btnDelete" value="Delete Record" />
<br />
<input type="button" id="btnPrint" value="Print Records" />
<br />
<output id="printOutput" > </output>
</div>
</center>
</body>
What is wrong with my delete? Thanks.
The code seems fine however you could check if converting the string key to integer value helps deleting the object from the object store.
var AadharNumber = parseInt(document.getElementById("AadharNumber").value);
Related
I would like to create two forms and store the inputs in the browser using IndexedDB. The inputs of the two forms should be required. The forms (here a short version) work so far and also for each page I can save the data separately, but unfortunately it doesn't work that I save the data in a common database.
I always receive the following error:
indexedDB.js:44 Uncaught TypeError: Cannot read properties of null (reading 'value') at HTMLFormElement.<anonymous>
Can someone help me how to solve this problem? I would really appreciate any help!
(Note: I do not want to create a common form on a HTML page.)
This is my first form:
<body>
<form action="form2.html" method="GET">
<label for="age">Age:</label>
<input id="age" value="age" name="age" type="number" required />
<br />
<label for="gender">Gender:</label>
<input id="gender" type="radio" name="gender" value="male" required />
<label for="male">male</label>
<input id="gender" type="radio" name="gender" value="female" required />
<label for="female">female</label>
<br />
<button type="submit"> next </button>
</form>
<script src="indexedDB.js"></script>
</body>
This is my second form:
<body>
<form action="end.html" method="GET">
<label for="car">Do you have a car?:</label>
<input id="car" type="radio" name="car" value="yes" required />
<label for="yes">yes</label>
<input id="car" type="radio" name="car" value="no" required />
<label for="no">no</label>
<br />
<button type="submit">next</button>
</form>
<script src="indexedDB.js"></script>
</body>
And this is my JavaScript:
// Create the database
var request = window.indexedDB.open("formData", 1);
request.onerror = function(event) {
console.error("Error opening database: ", event.target.errorCode);
};
request.onsuccess = function(event) {
var db = event.target.result;
// Get the form data from the first form
var form1 = document.querySelector("form");
form1.addEventListener("submit", function(event) {
event.preventDefault();
// Get the values of the inputs in the form
var age = form1.querySelector("input[name='age']").value;
var gender = form1.querySelector("input[name='gender']:checked").value;
// Store the values in the database
var transaction = db.transaction(["formData"], "readwrite");
var store = transaction.objectStore("formData");
store.put({
id: 42,
age: age,
gender: gender
});
transaction.oncomplete = function() {
console.log("Form 1 data saved successfully");
};
transaction.onerror = function(event) {
console.error("Error saving form 1 data: ", event.target.errorCode);
};
});
// Get the form data from the second form
var form2 = document.querySelector("form");
form2.addEventListener("submit", function(event) {
event.preventDefault();
// Get the value of the input in the form
var car = form2.querySelector("input[name='car']:checked").value;
// Store the value in the database
var transaction = db.transaction(["formData"], "readwrite");
var store = transaction.objectStore("formData");
store.put({
id: 42,
car: car
});
transaction.oncomplete = function() {
console.log("Form 2 data saved successfully");
};
transaction.onerror = function(event) {
console.error("Error saving form 2 data: ", event.target.errorCode);
};
});
};
request.onupgradeneeded = function(event) {
var db = event.target.result;
// Create the object store for the form data
db.createObjectStore("formData", { keyPath: "id" });
};
View 1:
<div ng-controller="ctrl1">
<button ng-click="goToExtendedForm({'name':'aaa'})">
</button>
</div>
ctrl1:
$scope.selectedList = {
name: ""
};
$scope.goToForm = function(e) {
$scope.selectedList.name = e.name;
$state.go('view2');
console.log(e); // prints updated value
};
View 2:
<div ng-controller="ctrl1">
<input
id="name"
name="name"
type="text"
ng-model="selectedList.name"
ng-readonly="true"
/>
</div>
But the input box is always empty, even though to get to the view the goToForm() is called. Why doesn't it update the HTML value?
Views are changed with ui.router's $state.
From your description, your code is supposed to work. Check if you are passing the right parameter into the function. Here is a working demo:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.selectedList = {
name: ""
};
$scope.goToForm = function(e) {
$scope.selectedList.name = e.name;
console.log(e); // prints updated value
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<button ng-click="goToForm({'name':'aaa'})">Change</button>
<br>
<input type="text" ng-model="selectedList.name" ng-readonly="true" />
</div>
Try adding $scope.$apply() at the end of your $scope.goToForm function
Try this ;
HTML Code
<div ng-app>
<div ng-controller="ClickToEditCtrl">
<input
id="name"
name="name"
type="text"
ng-model="selectedList.name"
ng-readonly="true"
/>
<button ng-click="goToForm(testUserDetails)" >Go To</button>
</button>
</div>
</div>
Define controller like this;
function ClickToEditCtrl($scope) {
$scope.selectedList = {
name: ""
};
$scope.testUserDetails ={
name: "nimal"
}
$scope.goToForm = function(e) {
$scope.selectedList.name = e.name;
console.log(e); // prints updated value
};
}
This question already has answers here:
File Upload using AngularJS
(29 answers)
Closed 5 years ago.
I have an angular controller that is supposed to update person data. With text and date fields, that works just fine, I have
<ul>
<li ng-repeat="person in $ctrl.persons | filter:$ctrl.query">
...
<div ng-show="person.edit">
<label>Full Name*:</label><input class="edit-person" ng-model="person.fullname" /><br />
<label>Birthdate:</label><input class="edit-person" type="date" ng-model="person.birthdate" /><br />
<label>Deathdate:</label><input class="edit-person" type="date" ng-model="person.deathdate" /><br />
<label>Description: </label><input class="edit-person" type="text" ng-model="person.description" /><br />
<img ng-src="{{person.picture}}" width="100px" height="100px" /><br />
<label>Picture: </label>
<input class="edit-person" type="file" accept="image/*"
ng-file-select="handleEditPersonFiles(this.files);" /><br />
<button ng-click="$ctrl.submitEdit(person); person.edit = false;">submit</button>
<button ng-click="$ctrl.cancelEdit(); person.edit = false;">cancel</button>
</div>
</li>
</ul>
and the component code:
var self = this;
this.submitEdit = function(person){
$http.post('/edit_person', {
id: person.id,
fullname: person.fullname,
birthdate: person.birthdate,
deathdate: person.deathdate,
description: person.description,
picture: person.picture
}).then(loadPersons);
};
and
handleEditPersonFiles = function(files){
var reader = new FileReader();
var that = this;
reader.onload = function(){
? = reader.result;
};
reader.readAsDataURL(files[0]);
};
I have no problem reading and uploading the pictures in the new-person function, since there I have a single variable, and can just self.new_person_picture = reader.result, but with the edit function, I don't know where to assign the reader result since I don't have access to the person.picture variable through angular. The onchange event correctly submits the file list. But ng-change seems to require a model, and doesn't fire when a file is selected. I also tried ng-file-select, but no event seems to be firing when I select a file to upload. Any help would be greatly appreciated.
It's easier than you think, you just have to pass the person model to the handleEditPersonFiles model too.
html:
<li ng-repeat="person in $ctrl.persons ...
...
<label>Picture: </label><input class="edit-person" type="file" accept="image/*" ng-file-select="handleEditPersonFiles(person, this.files);" />
js:
handleEditPersonFiles = function(person, files){
var reader = new FileReader();
reader.onload = function(){
person.picture = reader.result;
};
reader.readAsDataURL(files[0]);
};
I have a text box that show when I click on checkbox and I need to make an event on it that can make me bind it to object from DB
HTML:
<div ng-repeat="feture in featureEnumArray">
<input id="txtchkFet" type="checkbox" ng-model="feture.IsChecked" />
{{feture.DisplayText}}
<div ng-show="feture.IsChecked" >
<input class="form-control" type="text" ng-model="feture.Value" ng-change="getFeatureID(feture)" id="txtValue" placeholder="Type Feature Value" />
</div>
<div class="label label-danger" ng-show="feture.IsChecked && !feture.Value">
Type Value
</div>
</div>
And in Angular controller I did Like this :
$scope.getFeatureID = function (feture) {
if (feture.IsChecked) {
$scope.Planfeature = angular.copy(feture);
$scope.PlanFeatureTemp.FeatureID = $scope.Planfeature.ID;
$scope.PlanFeatureTemp.Value = $scope.Planfeature.Value;
$scope.Planfeature = [];
}
else {
var index = $scope.JAdminPlan.PlanFeatureValues.indexOf(feture);
$scope.JAdminPlan.PlanFeatureValues.splice(index, 1);
}
if (!$scope.$$phase) $scope.$apply();
};
I'm trying to create a 'recipe' object that contains an array of 'ingredients' and their properties when a form is submitted. I created inputs with ng-models: recipe.name, recipe.servings, recipe.ingredients[0].name, recipe.ingredients[0].amount, recipe.ingredients[1].name, recipe.ingredients[1].amount, etc. But when the form is submitted, only recipe.ingredients[0]'s properties are recorded. In my controller, I have the following:
angular.module('recipeMavenApp')
.controller('AddRecipeCtrl', function () {
var vm = this;
vm.ingredientCount = 1;
vm.recipe = {
name: '',
servings: 0,
ingredients: [],
};
vm.appendIngredient = function() {
var newIngredientInput = angular.element('<input type="text"' +
'ng-model="recipe.ingredients[' + vm.ingredientCount + '].name" placeholder="Ingredient name" />' +
'<input type="number" min="0.25" max="1000" step="0.25" ng-model="recipe.ingredients[' +
vm.ingredientCount + '].amount" placeholder="Amount"/>');
angular.element(document.querySelector('#ingredients')).append(newIngredientInput);
vm.ingredientCount++;
};
vm.addRecipe = function(recipe) {
vm.recipe = recipe;
console.log(vm.recipe); //Testing to see what is received.
};
The form:
<form novalidate >
<div class="form-group">
<label for="recipeName">Name of Recipe</label>
<input type="text" ng-model="recipe.name" id="recipeName" required/>
</div>
<div class="form-group">
<label for="recipeServings">Number of Servings</label>
<input type="number" min="1" max="50" ng-model="recipe.servings" id="recipeServings"/>
</div>
<div class="form-group" id="ingredients">
<label for="recipeIngredients">Ingredients</label>
<button class="btn btn-primary btn-xs" ng-click="add.appendIngredient()">Add Ingredient</button>
<br />
<input type="text" ng-model="recipe.ingredients[0].name" id="recipeIngredients" placeholder="Ingredient name" />
<input type="number" min="0.25" max="1000" step="0.25" ng-model="recipe.ingredients[0].amount" placeholder="Amount"/>
<br/>
</div>
<button ng-click="add.addRecipe(recipe)" class="btn btn-primary"><span class="glyphicon glyphicon-share"></span> Add Recipe</button>
</form>
How do I capture all ingredients in the recipe.ingredients array on form submit?
I tried to rewrite your code there : JSFiddle
I used ng-repeat to generate the list of ingredients (where I uses the $index for the models) to avoid any DOM manipulation in the controller :
<div ng-repeat="ingredient in recipe.ingredients">
<input type="text" ng-model="recipe.ingredients[$index].name" placeholder="Ingredient name" />
<input type="number" min="0.25" max="1000" step="0.25" ng-model="recipe.ingredients[$index].amount" placeholder="0"/>
</div>
Based on the model :
$scope.recipe = {
name: '',
servings: 0,
ingredients: [{
name: '',
amount: null
}]
};
In the $scope.recipe.ingredients you can add how many {name:'', amount:null} as you need to show by default (you can also add a prefilled name or amount, for instance : {name:'Ingredient 1', amount:5}).
Then when I need a new ingredient I just push a new object in the $scope.ingredients array :
$scope.appendIngredient = function() {
$scope.recipe.ingredients.push({
name: '',
amount: null
});
};
Feel free to let me know if it fulfills your requirements or if you have any question.
Thanks