Storing HTML form input in a JS object - javascript

I know there is a very similar question asked over here but my object hierarchy is different than the one in that question.
Anyways, I want to store the HTML form input data in to my JavaScript object. Here is my HTML form code:
<form id="newAuction">
<input id="title" name="title" required type="text" value="" />
<input id="edate" name="edate" required type="datetime" value="" />
<input id="minbid" name="minbid" required type="number" value="" />
<button class="btn btn-primary">Submit</button>
</form>
What I want is to get the values of these 3 inputs and store it in my JS object.
I know the proper JSON format needed to post the data to my API. (I tried POSTing with POSTman and I get a status 200, so it works). The proper format is:
{
"auction": {
"Title": "Auction1",
"EDate": "01/01/1990",
"MinBid": 30
},
"productIds": [1,2,3]
}
This is what my JS object looks like:
<script>
$(document).ready(function() {
var vm = {
auction: {},
productIds: []
};
//validation and posting to api
var validator = $("#newAuction").validate({
//assigning values
vm.auction.Title = document.getElementById('title').value;
vm.auction.MinBid = document.getElementById('minbid').value;
vm.auction.EDate = document.getElementById('edate').value;
vm.productIds.push(1);
submitHandler: function () {
$.ajax({
url: "/api/newAuction",
method: "post",
data: vm
})
.done(function () {
toastr.success("Auction Added to the db");
//setting the vm to a new vm to get rid of the old values
var vm = { auction: {}, productIds: [] };
validator.resetForm();
})
.fail(function () {
toastr.error("something wrong");
});
return false;
}
});
});
</script>
As you can see, I am using document.getElementById('title').value; to get the values and assign them but I'm getting the syntax error Expected : Comma expected
Not sure if this matters, but this is inside a .NET MVC5 project.

Move your value assignment set of codes inside submitHandler. Check the syntax of validate() https://jqueryvalidation.org/validate/
//validation and posting to api
var validator = $("#newAuction").validate({
submitHandler: function () {
//assigning values
vm.auction.Title = document.getElementById('title').value;
vm.auction.MinBid = document.getElementById('minbid').value;
vm.auction.EDate = document.getElementById('edate').value;
vm.productIds.push(1);
$.ajax({
url: "/api/newAuction",
method: "post",
data: vm
})
.done(function () {
toastr.success("Auction Added to the db");
//setting the vm to a new vm to get rid of the old values
var vm = { auction: {}, productIds: [] };
validator.resetForm();
})
.fail(function () {
toastr.error("something wrong");
});
return false;
}
});

Related

Edit MEANJS list in the list page

I am using MEAN JS, i am trying to edit the list items on the list page, but it shows the error as below. i have initiated the data using ng-init="find()" for the list and ng-init="findOne()" for individual data.
Error: [$resource:badcfg] Error in resource configuration for action `get`. Expected response to contain an object but got an array
HTML
Below i the form inside the controller where it initiates the find() and findOne().
<div ng-controller="OrdersController" ng-init="find()">
<div>
<div class="order-filter">
<div ng-repeat="order in orders">
<form ng-init="findOne()" name="orderForm" class="form-horizontal" ng-submit="update(orderForm.$valid)" novalidate>
<input type="text" class="" ng-model="order.title">
<input type="text" class="" ng-model="order.content">
<div class="form-group">
<input type="submit" value="Update" class="btn btn-default">
</div>
</form>
</div>
</div>
</div>
</div>
Controller
$scope.update = function (isValid) {
$scope.error = null;
if (!isValid) {
$scope.$broadcast('show-errors-check-validity', 'orderForm');
return false;
}
var order = $scope.order;
order.$update(function () {
$location.path('orders/' + order._id);
}, function (errorResponse) {
$scope.error = errorResponse.data.message;
});
};
$scope.find = function () {
Orders.query(function loadedOrders(orders) {
orders.forEach(appendFood);
$scope.orders = orders;
});
};
$scope.findOne = function () {
$scope.order = Orders.get({
orderId: $stateParams.orderId
});
};
You need to check your Orders Service which probably is using $resource to provide your API requests (Orders.query)
It should look something like this:
function OrdersService($resource) {
return $resource('api/orders/:orderId', {
orderId: '#_id'
}, {
update: {
method: 'PUT'
}
});
}
The style may be different depending on which version of mean you're using. By default, the $resource query will expect an array of results, but if for some reason you've set "isArray" to false then it will expect an object.
https://docs.angularjs.org/api/ngResource/service/$resource

Meteor using namedContext to addInvalidKeys to an AutoForm form returning an error

I have the following SimpleSchema where I am trying to add custom validation to validate against entering duplicate customer name, yet whenever I try to save a new customer I get error:
Exception in delivering result of invoking
'adminCheckNewCustomerName': TypeError: Cannot read property
'namedContext' of null
can someone please tell me what I am doing wrong / missing here to validate the customer name against duplicate records? Thanks
schema.js:
AdminSection.schemas.customer = new SimpleSchema({
CustomerName: {
type: String,
label: "Customer Name",
unique: true,
custom: function() {
if (Meteor.isClient && this.isSet) {
Meteor.call("adminCheckNewCustomerName", this.value, function(error, result) {
if (result) {
Customer.simpleSchema().namedContext("newCustomerForm").addInvalidKeys([{
name: "CustomerName",
type: "notUnique"
}]);
}
});
}
}
}
});
UI.registerHelper('AdminSchemas', function() {
return AdminSection.schemas;
});
form.html:
{{#autoForm id="newCustomerForm" schema=AdminSchemas.customer validation="submit" type="method" meteormethod="adminNewCustomer"}}
{{>afQuickField name="CustomerName"}}
<button type="submit" class="btn btn-primary">Save Customer</button>
{{/autoForm}}
collections.js:
this.Customer = new Mongo.Collection("customers");
Check collection2 code for fetching the schema attached to a collection:
_.each([Mongo.Collection, LocalCollection], function (obj) {
obj.prototype.simpleSchema = function () {
var self = this;
return self._c2 ? self._c2._simpleSchema : null;
};
});
This cryptic homonym _c2 (one of two hard things in programming...) comes from attachSchema:
self._c2 = self._c2 || {};
//After having merged the schema with the previous one if necessary
self._c2._simpleSchema = ss;
Which means that you have forgotten to attachSchema or fiddled with the property of your collection.
To solve:
Customer.attachSchema(AdminSchemas.customer);
//Also unless this collection stores only one customer its variable name should be plural

passing a JSON object to server using angularjs/javascript

How can I pass the information from an input field in the front end(using angularjs) as a JSON object to a server(javascript)?
Basically what I intend to do is take input from a user, and pass it as a query to search a database and return the values.
My controller code:
`app.controller('SearchController',['$scope','$http',function($scope,$http){
$scope.click=function(){
var data=$scope.query1;
$http.post('/credjson',data);
/*$scope.addRowAsyncAsJSON = function(){
$scope.cred.push({ 'query':$scope.query1 });
var dataObj = {
query : $scope.query1,
};
var res = $http.post('/credjson', dataObj);
res.success(function(data, status, headers, config) {
$scope.message = data;
});
res.error(function(data, status, headers, config) {
alert( "failure message: " + JSON.stringify({data: data}));
});
$scope.query1='';*/`
Note: The code in between /* */ was a different attempt at trying this out.
My view code:
`<div style="padding-top:20px" ng-controller="SearchController">
<form name="form1" ng-submit="click()">
<input id="creditq" ng-model='query1' type="text" />
<button id="Search" ng-value='Search'>Search</button><br/><br/>
</form>
</div>`
Just construct your JSON payload and pass it to $http as the second param
data: { query1: $scope.query1 }
and then
$http.post('/credjson',data);

Don't have access to attribute in my controller Angular.js 1.3

I'm building a simple form.
This form get a birthday field.
I can select a date and persist it.
But when I reload the page, I have an error
Error: [ngModel:datefmt] Expected `2015-03-06T23:00:00.000Z` to be a date
I know how to resolve it. I need to convert my user.date_birthday to a Date.
So I tried this.
'use strict';
angular.module('TheNameApp')
.controller('SettingsCtrl', function ($scope, User, Auth) {
$scope.user = User.get();
$scope.errors = {};
console.log($scope.user); // display the resource
console.log($scope.user.date_birthday); //undefined
$scope.changeInformations = function(form) {
$scope.infos_submitted = true;
if(form.$valid) {
Auth.changeInformations({
gender: $scope.user.gender,
city: $scope.user.city,
country: $scope.user.country,
talent: $scope.user.talent,
date_birthday: $scope.user.date_birthday,
user_name: $scope.user.user_name,
email: $scope.user.email })
.then( function() {
$scope.infos_message = 'Done.'
})
.catch( function(err) {
err = err.data;
$scope.errors = {};
// Update validity of form fields that match the mongoose errors
angular.forEach(err.errors, function(error, field) {
form[field].$setValidity('mongoose', false);
$scope.errors[field] = error.message;
});
});
}
};
the .html
<div class="form-group">
<label>Birthday</label>
<input type="date" name="date_birthday" class="form-control" ng-model="user.date_birthday"/>
</div>
The user.date_birthday is not defined but I can see it in $scope.user
I need this for my next step
$scope.user.date_birthday = new Date($scope.user.date_birthday);
Why I can't see my attribute? How Can I resolve this?
Assuming your User is a resource, .get() is an async call. Use a callback:
User.get(function(user) {
user.date_birthday = new Date(user.date_birthday);
$scope.user = user;
});

AngularJS: Taking old values instead of new during put

When updating, I want to insert new values coming from the ui instead of old values present in the local collection. The below code inserts old values in local collection(I don't want this to happen).
dataService.getSupplierById($routeParams.id)
.then(function (supplier) {
$scope.supplier = supplier; //now this contains local collection
$scope.save = function () {
$scope.updatedSupplier = $scope.supplier; //I want the scope to be updated and take values from the ui
dataService.updateSupplier($routeParams.id, $scope.updatedSupplier)
.then(function () {
//success
},
function () {
//error
});
};
},
function () {
//error
});
This is my Html.
<div>
<label for="City">City</label>
<input name="City" type="text" data-ng-model="updateSupplier.city" value="{{supplier.city}}" />
</div>
How can I do this? How can I update the scope to take new values? I'm new to angular.
If you are binding to updateSupplier as the ng-model then you shouldn't overwrite the values when you save:
$scope.save = function () {
// remove the line that overwrites, was here
dataService.updateSupplier($routeParams.id, $scope.updatedSupplier)
.then(function () {
//success
},
function () {
//error
});
};
}
Angular will take care of two-way binding the value inside the ng-model so by the time you save it will have the correct value that was input in the textbox.
You can also clean up the code by not have 2 different scope properties:
dataService.getSupplierById($routeParams.id)
.then(function (supplier) {
$scope.supplier = supplier; //now this contains local collection
$scope.save = function () {
dataService.updateSupplier($routeParams.id, $scope.supplier )
.then(function () {
//success
},
function () {
//error
});
};
},
function () {
//error
});
And then in the html:
<div>
<label for="City">City</label>
<input name="City" type="text" data-ng-model="supplier.city" />
</div>
The initial value should bind into the value attribute automatically.

Categories

Resources