Unable to create array of object to save MongoDB from AngularJS - javascript

I have created html dynamically and want to save in MongoDB using Mongoose from AngularJS. But the problem is that, I'm unable to create that require object which I have created Mongoose schema.
model code
var SegmentSchema = new Schema({
name: String,
uiName:String,
type:String,
lower:Number,
upper:Number,
options:[{key:String,value:String}]
});
export default mongoose.model('Segment', SegmentSchema);
view code
<form class="form-horizontal" ng-submit="addSegment()">
<div class="form-group">
<label class="col-sm-2 control-label">Name</label>
<div class="col-sm-6">
<p class="form-control-static"><input class="form-control" type="text" required ng-model="segment.name" name="name" value=""></p>
</div>
</div>
<div class="form-group">
<label for="inputPassword" class="col-sm-2 control-label">UI Name</label>
<div class="col-sm-6">
<input class="form-control" type="text" ng-model="segment.uiName" name="uiName" value="">
</div>
</div>
<div class="form-group">
<label for="inputPassword" class="col-sm-2 control-label">Type</label>
<div class="col-sm-6">
<select ng-model="segment.type" ng-change="changeType()" class="form-control" name="type">
<option value="">---select type---</option>
<option value="text">Text</option>
<option value="range">Range</option>
<option value="select">Select</option>
<option value="binary">Binary</option>
</select>
</div>
</div>
<div ng-show="rangeShow" class="form-group">
<label for="lower_range" class="col-sm-2 control-label">Lower Range</label>
<div class="col-sm-6">
<input class="form-control" ng-model="segment.lower" type="number" name="lower" value="">
</div>
</div>
<div ng-show="rangeShow" class="form-group">
<label for="lower_range" class="col-sm-2 control-label">Lower Range</label>
<div class="col-sm-6">
<input class="form-control" ng-model="segment.upper" type="number" name="upper" value="">
</div>
</div>
<div ng-show="numOptionShow" class="form-group">
<label for="inputPassword" class="col-sm-6 control-label"></label>
<div class="col-sm-2">
<input placeholder="Options count" class="form-control col-sm-3" ng-keydown="keyupOptionNumber()" ng-keyup="keyupOptionNumber()" ng-model="numOption" type="text" value="">
</div>
</div>
<div ng-show="selectOptionShow" class="" id="segment-select-option">
</div>
<div class="form-group">
<button type="submit" ng-show="addSegmentBtn" class="btn btn-success">Add</button>
</div>
</form>
angularjs(controller) code:
angular.module('nrichApp')
.controller('SegmentCtrl', function ($scope,$http,segment) {
$scope.loading = true;
$scope.addSegmentDiv=false;
segment.get().success(function(data) {
$scope.segments=data;
});
$scope.loading = false;
})
.controller('AddSegmentCtrl', function ($scope,segment,$location,$compile) {
$scope.loading = true;
$scope.addSegmentBtn=false;
$scope.changeType=function(){
$scope.addSegmentBtn=true;
$scope.rangeShow=false;
$scope.selectOptionShow=false;
$scope.numOptionShow=false;
switch ($scope.segment.type) {
case 'range':
$scope.rangeShow=true;
break;
case 'select':
$scope.numOptionShow=true;
break;
case 'binary':
break;
default:
}
};
$scope.keyupOptionNumber=function(){
console.log($scope.numOption);
$scope.selectOptionShow=true;
var input ='';
for (var i = 0; i < $scope.numOption; i++) {
input+='<div class="form-group">';
input+='<label for="option_key" class="col-sm-2 control-label">Key</label>';
input+='<div class="col-sm-2"><input ng-model="segment.options[' + i + '].key" class="form-control" type="text" name="key" value=""></div>';
input+='<label for="option_value" class="col-sm-1 control-label">Value</label>';
input+='<div class="col-sm-3"><input ng-model="segment.options[' + i + '].value" class="form-control" type="text" name="value" value=""></div>';
input+='</div>';
}
var eleDiv=angular.element(document.querySelector('#segment-select-option'));
eleDiv.html(input);
$compile(eleDiv)($scope);
};
$scope.addSegment=function(){
$scope.loading = true;
var param = {'segment' : $scope.segment};
console.log(JSON.stringify(param));//it is output which show at below
segment.create(param)
.success(function(data) {
$scope.loading = false;
$location.path('/segment');
});
$scope.loading = false;
};
});
Output:
{
"segment":{
"type":"select",
"name":"range2",
"uiName":"Select 3",
"options":{
"0": { "key":"k3","value":"v2"},
"1": { "key":"k4","value":"v4"}
}
}
}
Desired Output:
{
"segment": {
"type":"select",
"name":"range2",
"uiName":"Select 3",
"options": [
{"key":"k3","value":"v2"},
{"key":"k4","value":"v4"}
]
}
}

Finally, i got solution. I just declare array data type for options variable i.e,
$scope.options=[]
Inside angular controller:
$scope.keyupOptionNumber=function(){
$scope.options=[];//Here, this line is missing
console.log($scope.numOption);
$scope.selectOptionShow=true;
var input ='';
for (var i = 0; i < $scope.numOption; i++) {
input+='<div class="form-group">';
input+='<label for="option_key" class="col-sm-2 control-label">Key</label>';
input+='<div class="col-sm-2"><input ng-model="segment.options[' + i + '].key" class="form-control" type="text" name="key" value=""></div>';
input+='<label for="option_value" class="col-sm-1 control-label">Value</label>';
input+='<div class="col-sm-3"><input ng-model="segment.options[' + i + '].value" class="form-control" type="text" name="value" value=""></div>';
input+='</div>';
}
var eleDiv=angular.element(document.querySelector('#segment-select-option'));
eleDiv.html(input);
$compile(eleDiv)($scope);
};
Thanks #shaishab roy

Related

Why my equations are not running in this function?

Im having travel with te following function so when the value of tipoCompra == 'Nacional' the costUSD is going to be just the value of costUSD and disable the other fields, but if the value of tipoCompra == 'Exterior' the value of costUSD shall be auto completed with simple equations within other input fields.
function CalcularNacionalizacion(){
var tipoCompra = document.getElementById('tipoCompra').value;
var fob = document.getElementById('fob');
var nacFactor = document.getElementById('nacFactor');
var Nacionalizacion = document.getElementById('costNacionalizacion');
if (tipoCompra == 'Nacional'){
fob.disabled = true;
nacFactor.disabled = true;
Nacionalizacion.disabled = true;
var totalUSD = document.getElemenById('costUSD').value;
} else {
fob.disabled = '';
nacFactor.disabled = '';
Nacionalizacion.disabled = '';
var fob = document.getElementById('fob').value;
var nacFactor = document.getElementById('nacFactor').value;
var Nacionalizacion = parseFloat(fob) * parseFloat(nacFactor);
document.getElementById('costNacionalizacion').value = Nacionalizacion;
var totalUSD = parseFloat(fob) + parseFloat(Nacionalizacion);
document.getElementById('costUSD').value = totalUSD;
}
}
<div class="form-group col-md-2">
<label for="">Tipo de Compra</label>
<select name="" id="tipoCompra" onchange="CalcularNacionalizacion();" class="form-control" required>
<option value="">Tipo de compra </option>
<option value="Nacional">Nacional</option>
<option value="Exterior">Exterior</option>
</select>
</div>
<div class="form-group col-md-2">
<label for="fob">Costo Fob</label>
<input type="number" step="00.01" id="fob" name="fob" class="form-control" disabled="true" onchange="CalcularNacionalizacion();" onkeyup="CalcularNacionalizacion();" required>
</div>
<div class="form-group col-md-2">
<label for="nacFactor">Factor de Nacionalizacion</label>
<input type="number" step="00.01" id="nacFactor" name="nacFactor" class="form-control" onchange="CalcularNacionalizacion();" onkeyup="CalcularNacionalizacion();" required>
</div>
<div class="form-group col-md-2">
<label for="costNacionalizacion">Costo Nacionalizacion</label>
<input type="number" step="00.01" id="costNacionalizacion" name="costNacionalizacion" onchange="CalcularNacionalizacion();" onkeyup="CalcularNacionalizacion();" class="form-control" required>
</div>
<div class="form-group col-md-2">
<label for="costUSD">Costo total en USD-O</label>
<input type="number" step="00.01" name="costUSD" class="form-control" id="costUSD" onchange="ToCalcularNacionalizaciondas();" onkeyup="CalcularNacionalizacion();" required>
</div>
If you choose the option 'Exterior' you can see that my equations are not running.
I do some refactoring in your code so that it would work
const tipoCompra = document.querySelector('#tipoCompra');
const fob = document.querySelector('#fob');
const nacFactor = document.querySelector('#nacFactor');
const Nacionalizacion = document.querySelector('#costNacionalizacion');
const costUSD = document.querySelector('#costUSD');
const elements = [tipoCompra, fob, nacFactor, Nacionalizacion, costUSD];
elements.forEach((i) => {
i.addEventListener('change', CalcularNacionalizacion);
});
function CalcularNacionalizacion(e) {
if (tipoCompra.value === 'Nacional') {
fob.disabled = true;
nacFactor.disabled = true;
Nacionalizacion.disabled = true;
costUSD.value = costUSD.value;
} else {
fob.disabled = false;
nacFactor.disabled = false;
Nacionalizacion.disabled = false;
const fobValue = Number(fob.value);
const nacFacotrValue = Number(nacFactor.value);
const NacionalizacionValue = fobValue * nacFacotrValue;
Nacionalizacion.value = NacionalizacionValue;
const totalUSDValue = fobValue + NacionalizacionValue;
costUSD.value = totalUSDValue;
}
}
<div class="form-group col-md-2">
<label for="">Tipo de Compra</label>
<select name="" id="tipoCompra" class="form-control" required>
<option value="">Tipo de compra </option>
<option value="Nacional">Nacional</option>
<option value="Exterior">Exterior</option>
</select>
</div>
<div class="form-group col-md-2">
<label for="fob">Costo Fob</label>
<input type="number" step="00.01" id="fob" name="fob" class="form-control" disabled="true" required />
</div>
<div class="form-group col-md-2">
<label for="nacFactor">Factor de Nacionalizacion</label>
<input type="number" step="00.01" id="nacFactor" name="nacFactor" class="form-control" required />
</div>
<div class="form-group col-md-2">
<label for="costNacionalizacion">Costo Nacionalizacion</label>
<input type="number" step="00.01" id="costNacionalizacion" name="costNacionalizacion" class="form-control" required />
</div>
<div class="form-group col-md-2">
<label for="costUSD">Costo total en USD-O</label>
<input type="number" step="00.01" name="costUSD" class="form-control" id="costUSD" required />
</div>

Form Values Returning Null in localStorage When Editing Selects Using Javascript?

I have a form which sends data to localStorage, which I am able to view, delete and edit. My form has a mixture of input types, text select and textarea, when I submit the form, these values store correctly, however when I use my edit function, the values show correctly on the edit form, but if I don't change the values (even to the same value), they update/store as null.
For example:
I have a form with Name(type text), Address(type address) and Dog Breed(type select), when I edit, the values of all three will be there from the form before, but if I hit submit without changing any, the dog breed would return null. They update correctly if I change the values, but as this is an appointment scheduler, not every value will be changed (for eg they may only need to change the time or breed).
Here is my snippet - I know it can't be run fully because of sandboxing but just so you can see:
const BREEDS_URL = 'https://dog.ceo/api/breeds/list/all';
const select = document.getElementById('breed');
fetch(BREEDS_URL)
.then(res => {
return res.json();
})
.then(data => {
const breedsObject = data.message;
const breedsArray = Object.keys(breedsObject);
for (let i = 0; i < breedsArray.length; i++) {
const option = document.createElement('option');
option.value = breedsArray[i];
option.innerText = breedsArray[i];
select.appendChild(option);
}
console.log(breedsArray);
});
// ~~~ add bookings to localStorage
var bookings = JSON.parse(localStorage.getItem("bookings")) || [];
window.onload = showBooking();
window.onload = showTimes();
$("#submit").click(function() {
var newBookings = {
id: new Date().getTime(),
fname: $('#fname').val(),
lname: $('#lname').val(),
email: $('#email').val(),
number: $('#number').val(),
sdate: $('#sdate').val(),
stime: $('#stime').val(),
duration: $('#duration').val(),
address: $('#address').val(),
postcode: $('#postcode').val(),
dogname: $('#dogName').val(),
breed: $('#breed').val(),
info: $('#info').val()
}
bookings.push(newBookings);
var json = JSON.stringify(bookings);
window.localStorage.setItem("bookings", json);
alert('Form submitted!');
showBooking();
});
$(document).on('click', '#edit', function(e) {
e.preventDefault();
var parent_form = $(this.form);
var fname = parent_form.find('.fname').val();
var lname = parent_form.find('.lname').val();
var email = parent_form.find('.email').val();
var number = parent_form.find('.number').val();
var sdate = parent_form.find('.datepicker').val();
var stime = parent_form.find('.select').val();
var duration = parent_form.find('.duration').val();
var address = parent_form.find('.address').val();
var postcode = parent_form.find('.postcode').val();
var dogname = parent_form.find('.dogname').val();
var breed = parent_form.find('.breed').val();
var info = parent_form.find('.info').val();
let i = bookings.findIndex(booking => booking.id == $(this).data("id"));
bookings[i].fname = fname;
bookings[i].lname = lname;
bookings[i].email = email;
bookings[i].number = number;
bookings[i].sdate = sdate;
bookings[i].stime = stime;
bookings[i].duration = duration;
bookings[i].address = address;
bookings[i].postcode = postcode;
bookings[i].dogname = dogname;
bookings[i].breed = breed;
bookings[i].info = info;
var json = JSON.stringify(bookings);
window.localStorage.setItem("bookings", json);
window.location.reload();
alert('Form updated!');
showBooking();
});
// ~~~ display bookings in browser
function showBooking() {
var bookingResult = document.getElementById("result");
var ul = document.createElement("ul");
bookingResult.innerHTML = `<h3 class="text-center">Your Bookings</h3>`;
for (let i = 0; i < bookings.length; i++) {
bookingResult.innerHTML += `
<div class="card card-body bg-light m-4">
<div class="row">
<p>${bookings[i].fname + " " + bookings[i].lname}</p>
</div>
<div class="row">
<div class="d-grid gap-2 d-md-block">
<button onclick="editBooking(${i})" class="col-md-4 btn btn-outline-danger ">Edit</button>
<button onclick="deleteBooking(${i})" class="col-md-4 btn btn-danger text-light ">Delete</button>
</div>
</div>
</div>`;
}
}
// ~~~ edit bookings in browser
function editBooking(i) {
$('#result').hide();
var currentItem = document.getElementById("currentItem");
var editBooking = document.getElementById("editAppt");
currentItem.innerHTML += `
<h3 class="text-center">Currently Amending</h3>
<div class="card card-body bg-light m-4">
<p data-id="${bookings[i].id}">${bookings[i].fname + " " + bookings[i].lname}</p>
</div>`;
editBooking.innerHTML = `
<h3 class="text-center">Amend Your Booking</h3>
<div class="row">
<div class="col-md-6">
<input type="text" class="fname form-control required" data-id="${bookings[i].id}" placeholder="First Name" name="${bookings[i].fname}" value="${bookings[i].fname}">
</div>
<div class="col-md-6">
<input type="text" class="lname form-control required" data-id="${bookings[i].id}" placeholder="Last Name" name="${bookings[i].lname}" value="${bookings[i].lname}">
</div>
</div>
<div class="row">
<div class="col-md-6">
<input type="email" class="email form-control required" data-id="${bookings[i].id}" placeholder="Email Address" name="${bookings[i].email}" value="${bookings[i].email}">
</div>
<div class="col-md-6">
<input type="number" class="number form-control required" data-id="${bookings[i].id}" onchange="validateContact()" placeholder="Contact Number" name="${bookings[i].number}" value="${bookings[i].number}">
</div>
</div>
<div class="row">
<div class="col-md-6">
<input type="date" id="sdate" class="datepicker form-control required" name="${bookings[i].sdate}" onchange="checkStartDate()" value="${bookings[i].sdate}">
</div>
<div class="col-md-6">
<select id="stime" name="${bookings[i].stime}" onfocus="showTimes()" class="time select form-control required" value="${bookings[i].stime}">${bookings[i].stime}
<option value="${bookings[i].stime}" selected disabled hidden>${bookings[i].stime}</option>
</select>
</div>
</div>
<div class="row">
<div class="col-md-6">
<select name="${bookings[i].duration}" class="duration form-control required" data-id="${bookings[i].id}" value="${bookings[i].duration}">${bookings[i].duration}
<option value="${bookings[i].duration}" selected disabled hidden>${bookings[i].duration}</option>
<option value="30 mins">30 mins</option>
<option value="1 hour">1 hour</option>
<option value="1.5 hours">1.5 hours</option>
<option value="2 hours">2 hours</option>
</select>
</div>
</div>
<div class="row">
<div class="col-md-6">
<input type="text" data-id="${bookings[i].id}" class="address form-control required" placeholder="Address" name="${bookings[i].address}" value="${bookings[i].address}">
</div>
<div class="col-md-6">
<input type="text" data-id="${bookings[i].id}" class="postcode form-control " placeholder="Post Code" name="${bookings[i].postcode}" value="${bookings[i].postcode}">
</div>
</div>
<div class="row">
<div class="col-md-6">
<input type="text" id="dogName" class="dogname form-control required" placeholder="Dogs Name" name="${bookings[i].dogname}" value="${bookings[i].dogname}">
</div>
<div class="col-md-6">
<select id="breed" class="breed form-control required" name="${bookings[i].breed}" value="${bookings[i].breed}">
<option value="${bookings[i].breed}" selected disabled hidden>${bookings[i].breed}</option>
</select>
</div>
</div>
<div class="row">
<div class="col-md-12">
<textarea id="info" name="info" class="info form-control required" placeholder="Any additional info - favourite toys or places?" name="${bookings[i].info}">${bookings[i].info}</textarea>
</div>
</div>
<div class="d-grid gap-2 d-md-block">
<input data-id="${bookings[i].id}" id="edit" class="btn btn-danger toggle-disabled" type="submit" value="Edit" disabled>
Cancel
</div>
`;
}
function showTimes() {
let startTime = document.getElementById('stime');
let times = ['9:00', '9:30', '10:00', '10:30', '11:00', '11:30', '12:00', '12:30', '13:00', '13:30', '14:00', '14:30', '15:00'];
let options = times.map(time => `<option value="${time}">${time}</option>`).join('');
startTime.innerHTML += options;
}
// ~~~ delete bookings from localStorage
function deleteBooking(i) {
alert('Are you sure you want to delete this booking?');
bookings.splice(i, 1);
localStorage.setItem("bookings", JSON.stringify(bookings));
showBooking();
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<link rel="stylesheet" href="css/style.css">
<section class="form row">
<form id="regForm" name="regForm" action="" class="col-md-6">
<div id="editAppt">
<div class="row text-center">
<h3>Book your dog walk now</h3>
<p>Tell us about yourself first..</p>
</div>
<div class="row">
<div class="col-md-6">
<input type="text" class="input form-control required" id="fname" placeholder="First Name" name="fname" required>
</div>
<div class="col-md-6">
<input type="text" class="input form-control required" id="lname" placeholder="Last Name" name="lname" required>
</div>
</div>
<div class="row text-center">
<p>When should we pick your dog up?</p>
</div>
<div class="row">
<div class="col-md-6">
<input type="date" id="sdate" class="datepicker form-control required" name="sdate" onchange="checkStartDate()" required>
</div>
<div class="col-md-6">
<select name="duration" class="duration form-control required" id="duration" required>
<option value="" selected disabled hidden>Duration</option>
<option value="30 mins">30 mins</option>
<option value="1 hour">1 hour</option>
<option value="1.5 hours">1.5 hours</option>
<option value="2 hours">2 hours</option>
</select>
</div>
</div>
<div class="row">
<div class="col-md-6">
<input type="text" id="dogName" class="dogname form-control required" placeholder="Dogs Name" name="dogname">
</div>
<div class="col-md-6">
<select id="breed" class="breed form-control required">
<option value="" selected disabled hidden>Select Breed</option>
</select>
</div>
</div>
<div class="col-md-6">
<input id="submit" class="btn btn-danger toggle-disabled" type="submit" value="Submit">
</div>
</div>
</form>
<div class="col-md-6">
<div id="result" class="row"></div>
<div id="currentItem" class="row"></div>
</div>
There are a few issues in the code you'll need to take care of:
First thing is, I'd wrap everything in a "document.ready" event handler from jQuery:
$(function() {
...
});
The above is shorthand and just ensures your code runs once all of the HTML code has been parsed.
Now, the caveat with that is now all of your functions are no longer in the global scope, so you can't reference them in HTML attributes like onclick. So, you'll need to attach them to your elements using jQuery or plain old DOM methods.
You had two lines which set the window.onload property. In the code below I've changed it to use jQuery-style event handler attachment.
You were setting the name attribute of the form elements to the value of edited appointment, but the name attribute really shouldn't need to change that often.
$(function() {
const BREEDS_URL = 'https://dog.ceo/api/breeds/list/all';
function loadBreeds() {
const select = document.getElementById('breed');
fetch(BREEDS_URL)
.then(res => {
return res.json();
})
.then(data => {
const breedsObject = data.message;
const breedsArray = Object.keys(breedsObject);
for (let i = 0; i < breedsArray.length; i++) {
const option = document.createElement('option');
option.value = breedsArray[i];
option.innerText = breedsArray[i];
select.appendChild(option);
}
console.log(breedsArray);
});
}
// ~~~ add bookings to localStorage
var bookings = JSON.parse(localStorage.getItem("bookings")) || [];
$(window).on('load', function() {
showBooking();
showTimes();
loadBreeds();
});
$("#submit").click(function() {
var newBookings = {
id: new Date().getTime(),
fname: $('#fname').val(),
lname: $('#lname').val(),
email: $('#email').val(),
number: $('#number').val(),
sdate: $('#sdate').val(),
stime: $('#stime').val(),
duration: $('#duration').val(),
address: $('#address').val(),
postcode: $('#postcode').val(),
dogname: $('#dogName').val(),
breed: $('#breed').val(),
info: $('#info').val()
}
bookings.push(newBookings);
var json = JSON.stringify(bookings);
window.localStorage.setItem("bookings", json);
alert('Form submitted!');
showBooking();
});
$(document).on('click', '#edit', function(e) {
e.preventDefault();
var parent_form = $(this.form);
var fname = parent_form.find('.fname').val();
var lname = parent_form.find('.lname').val();
var email = parent_form.find('.email').val();
var number = parent_form.find('.number').val();
var sdate = parent_form.find('.datepicker').val();
var stime = parent_form.find('.select').val();
var duration = parent_form.find('.duration').val();
var address = parent_form.find('.address').val();
var postcode = parent_form.find('.postcode').val();
var dogname = parent_form.find('.dogname').val();
var breed = parent_form.find('.breed').val();
var info = parent_form.find('.info').val();
let i = bookings.findIndex(booking => booking.id == $(this).data("id"));
bookings[i].fname = fname;
bookings[i].lname = lname;
bookings[i].email = email;
bookings[i].number = number;
bookings[i].sdate = sdate;
bookings[i].stime = stime;
bookings[i].duration = duration;
bookings[i].address = address;
bookings[i].postcode = postcode;
bookings[i].dogname = dogname;
bookings[i].breed = breed;
bookings[i].info = info;
var json = JSON.stringify(bookings);
window.localStorage.setItem("bookings", json);
window.location.reload();
alert('Form updated!');
showBooking();
});
$(document).on('change', '.datepicker', checkStartDate);
$(document).on('change', '.number', validateContact);
$(document).on('focusin', '.time', showTimes);
$(document).on('click', '.edit-booking', function(e) {
var index = +$(this).data('index');
editBooking(index);
});
$(document).on('click', '.delete-booking', function(e) {
var index = +$(this).data('index');
deleteBooking(index);
});
// ~~~ display bookings in browser
function showBooking() {
var bookingResult = document.getElementById("result");
var ul = document.createElement("ul");
bookingResult.innerHTML = `<h3 class="text-center">Your Bookings</h3>`;
for (let i = 0; i < bookings.length; i++) {
bookingResult.innerHTML += `
<div class="card card-body bg-light m-4">
<div class="row">
<p>${bookings[i].fname + " " + bookings[i].lname}</p>
</div>
<div class="row">
<div class="d-grid gap-2 d-md-block">
<button data-index="${i}" class="edit-booking col-md-4 btn btn-outline-danger ">Edit</button>
<button data-index="${i}" class="delete-booking col-md-4 btn btn-danger text-light ">Delete</button>
</div>
</div>
</div>`;
}
}
// ~~~ edit bookings in browser
function editBooking(i) {
$('#result').hide();
var currentItem = document.getElementById("currentItem");
var editBooking = document.getElementById("editAppt");
currentItem.innerHTML += `
<h3 class="text-center">Currently Amending</h3>
<div class="card card-body bg-light m-4">
<p data-id="${bookings[i].id}">${bookings[i].fname + " " + bookings[i].lname}</p>
</div>`;
editBooking.innerHTML = `
<h3 class="text-center">Amend Your Booking</h3>
<div class="row">
<div class="col-md-6">
<input type="text" class="fname form-control required" data-id="${bookings[i].id}" placeholder="First Name" name="fname" value="${bookings[i].fname}">
</div>
<div class="col-md-6">
<input type="text" class="lname form-control required" data-id="${bookings[i].id}" placeholder="Last Name" name="lname" value="${bookings[i].lname}">
</div>
</div>
<div class="row">
<div class="col-md-6">
<input type="email" class="email form-control required" data-id="${bookings[i].id}" placeholder="Email Address" name="email" value="${bookings[i].email}">
</div>
<div class="col-md-6">
<input type="number" class="number form-control required" data-id="${bookings[i].id}" placeholder="Contact Number" name="number" value="${bookings[i].number}">
</div>
</div>
<div class="row">
<div class="col-md-6">
<input type="date" id="sdate" class="datepicker form-control required" name="sdate" value="${bookings[i].sdate}">
</div>
<div class="col-md-6">
<select id="stime" name="stime" class="time select form-control required" value="${bookings[i].stime}">
<option value="${bookings[i].stime}">${bookings[i].stime}</option>
</select>
</div>
</div>
<div class="row">
<div class="col-md-6">
<select name="duration" class="duration form-control required" data-id="${bookings[i].id}" value="${bookings[i].duration}">
<option value="${bookings[i].duration}">${bookings[i].duration}</option>
<option value="30 mins">30 mins</option>
<option value="1 hour">1 hour</option>
<option value="1.5 hours">1.5 hours</option>
<option value="2 hours">2 hours</option>
</select>
</div>
</div>
<div class="row">
<div class="col-md-6">
<input type="text" data-id="${bookings[i].id}" class="address form-control required" placeholder="Address" name="address" value="${bookings[i].address}">
</div>
<div class="col-md-6">
<input type="text" data-id="${bookings[i].id}" class="postcode form-control " placeholder="Post Code" name="postcode" value="${bookings[i].postcode}">
</div>
</div>
<div class="row">
<div class="col-md-6">
<input type="text" id="dogName" class="dogname form-control required" placeholder="Dogs Name" name="dogname" value="${bookings[i].dogname}">
</div>
<div class="col-md-6">
<select id="breed" class="breed form-control required" name="breed" value="${bookings[i].breed}">
<option value="${bookings[i].breed}">${bookings[i].breed}</option>
</select>
</div>
</div>
<div class="row">
<div class="col-md-12">
<textarea id="info" name="info" class="info form-control required" placeholder="Any additional info - favourite toys or places?" name="info">${bookings[i].info}</textarea>
</div>
</div>
<div class="d-grid gap-2 d-md-block">
<input data-id="${bookings[i].id}" id="edit" class="btn btn-danger toggle-disabled" type="submit" value="Edit" disabled>
Cancel
</div>
`;
loadBreeds();
}
function showTimes() {
let startTime = document.getElementById('stime');
let times = ['9:00', '9:30', '10:00', '10:30', '11:00', '11:30', '12:00', '12:30', '13:00', '13:30', '14:00', '14:30', '15:00'];
let options = times.map(time => `<option value="${time}">${time}</option>`).join('');
startTime.innerHTML += options;
}
// ~~~ delete bookings from localStorage
function deleteBooking(i) {
alert('Are you sure you want to delete this booking?');
bookings.splice(i, 1);
localStorage.setItem("bookings", JSON.stringify(bookings));
showBooking();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<link rel="stylesheet" href="css/style.css">
<section class="form row">
<form id="regForm" name="regForm" action="" class="col-md-6">
<div id="editAppt">
<div class="row text-center">
<h3>Book your dog walk now</h3>
<p>Tell us about yourself first..</p>
</div>
<div class="row">
<div class="col-md-6">
<input type="text" class="input form-control required" id="fname" placeholder="First Name" name="fname" required>
</div>
<div class="col-md-6">
<input type="text" class="input form-control required" id="lname" placeholder="Last Name" name="lname" required>
</div>
</div>
<div class="row text-center">
<p>When should we pick your dog up?</p>
</div>
<div class="row">
<div class="col-md-6">
<input type="date" id="sdate" class="datepicker form-control required" name="sdate" required>
</div>
<div class="col-md-6">
<select name="duration" class="duration form-control required" id="duration" required>
<option value="" selected disabled hidden>Duration</option>
<option value="30 mins">30 mins</option>
<option value="1 hour">1 hour</option>
<option value="1.5 hours">1.5 hours</option>
<option value="2 hours">2 hours</option>
</select>
</div>
</div>
<div class="row">
<div class="col-md-6">
<input type="text" id="dogName" class="dogname form-control required" placeholder="Dogs Name" name="dogname">
</div>
<div class="col-md-6">
<select id="breed" class="breed form-control required">
<option value="" selected disabled hidden>Select Breed</option>
</select>
</div>
</div>
<div class="col-md-6">
<input id="submit" class="btn btn-danger toggle-disabled" type="submit" value="Submit">
</div>
</div>
</form>
<div class="col-md-6">
<div id="result" class="row"></div>
<div id="currentItem" class="row"></div>
</div>

Calling a method in itself as a method

So , basically i am trying to create a input field and when i enter a number it gives me the desired child of the same html.
now i want child to produce more children with unique name with javascript.
i am attaching the code for a better understanding.
<div class="row" id="child_nr">
<div class="col-xs-12">
<div class="form-group col-xs-6">
<div class="form-group col-xs-4">
<label for="name" class="control-label">Parameter Name: <font color="red">*</font></label>
</div>
<div class="form-group col-xs-8">
<input type="text" class="form-control required" id="param_name" name="param_name" placeholder="name" onblur="param()"/>
</div>
</div>
<div class="form-group col-xs-6">
<div class="form-group col-xs-3">
<input type="text" class="form-control required" id="parent_nr" name="parent_nr" value="0" onblur="param()"/>
</div>
<div class="form-group col-xs-5">
<label for="name" name="service_code" id="service_code" class="control-label">
Service Code </label>
</div>
<div class="form-group col-xs-4">
<input type="text" class="form-control required" name="service_code" id="service_code"/>
</div>
</div>
</div>
</div>
<script language="javascript">
function param(){
var value=parent_nr.value;
const name=document.getElementById("param_name").value;
for(var i=1;i<=value;i++)
{
const html='<div class="col-xs-12"><div class="form-group col-xs-6"><div class="form-group col-xs-7"><label for="name" class="control-label">Parameter Name'+i+': <font color="red">*</font></label></div><div class="form-group col-xs-5"><input type="text" class="form-control required" id="name" name="name" placeholder="name"/></div></div><div class="form-group col-xs-6"><div class="form-group col-xs-3"><input type="number" class="form-control required" id="parent_nr" name="parent_nr" value="0" onblur="param()"/></div><div class="form-group col-xs-5"><label for="name" name="service_code" id="service_code" class="control-label">Service Code </label></div><div class="form-group col-xs-4"><input type="text" class="form-control required" name="service_code" id="service_code"/></div></div></div>';
document.querySelector('#child_nr').insertAdjacentHTML('beforeend',html);
}
}
function sendData() {
var question = 'abc';
var c = 'cde';
$.ajax({
url: 'http://localhost/gtiemr/addnewparameter_laboratory',
type: 'POST',
data: { question: question, c: c },
success: function () {
alert('suc');
},
error: function (error) {
alert('error');
}
});
}
</script>
Also, i want to know how i can send the value to my controller using ajax so that i can send it to model.

How to create a key:value object from several HTML inputs

I got the following HTML:
<div class="slot_subclass">
<div class="form-group">
<input type="text" class="form-control slot" name="slot_name">
</div>
<div class="form-group">
<input type="text" class="form-control slot" name="slot_type">
</div>
</div>
<div class="slot_subclass">
<div class="form-group">
<input type="text" class="form-control slot" name="slot_name">
</div>
<div class="form-group">
<input type="text" class="form-control slot" name="slot_type">
</div>
</div>
<div class="slot_subclass">
<div class="form-group">
<input type="text" class="form-control slot" name="slot_name">
</div>
<div class="form-group">
<input type="text" class="form-control slot" name="slot_type">
</div>
</div>
The amount of slot_subclass may be unlimited.
I need to parse all these inputs and make an object where the key is the value of first input of slot_subclass (slot_name) and value is the value of the second (slot_type).
I tried the following:
$(".slot").map(function(){
return $(this).val();
}).get();
but I just get a plain array of values. I may use jQuery for this task. Thank you.
UPD_1 In order to handle for the same keys I chose the following code (if someone interested):
jsonObj = [];
$(".slot_subclass").each(function() {
var slot_name = $(this).find("input[name=slot_name]").val();
var slot_type = $(this).find("input[name=slot_type]").val();
item = {};
item[slot_name] = slot_type;
jsonObj.push(item);
});
console.log(jsonObj);
Thank you everyone for help.
Like this code:
100% working and tested
jsonObj = [];
$(".slot_subclass").each(function() {
var slot_name = $(this).("input[name=slot_name]").val();
var slot_type = $(this).("input[name=slot_type]").val();
item = {};
item["slot_name"] = slot_name;
item["slot_type"] = slot_type;
jsonObj.push(item);
});
console.log(jsonObj);
Example:
jsonObj = [];
$(".slot_subclass").each(function() {
var slot_name = $(this).find("input[name=slot_name]").val();
var slot_type = $(this).find("input[name=slot_type]").val();
item = {};
item["slot_name"] = slot_name;
item["slot_type"] = slot_type;
jsonObj.push(item);
});
console.log(jsonObj);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="slot_subclass">
<div class="form-group">
<input type="text" class="form-control slot" name="slot_name" value="1">
</div>
<div class="form-group">
<input type="text" class="form-control slot" name="slot_type" value="11">
</div>
</div>
<div class="slot_subclass">
<div class="form-group">
<input type="text" class="form-control slot" name="slot_name" value="2">
</div>
<div class="form-group">
<input type="text" class="form-control slot" name="slot_type" value="22">
</div>
</div>
<div class="slot_subclass">
<div class="form-group">
<input type="text" class="form-control slot" name="slot_name" value="3">
</div>
<div class="form-group">
<input type="text" class="form-control slot" name="slot_type" value="33">
</div>
</div>
Firstly note that there's no such thing as a 'JSON object'. JSON is a notation for serialising data to a string. It's never an object.
With regard to your code, map() returns an array. In your example this array will contain values only. Instead you need to change that to return an object that holds the values of the input elements within each .slot_subclass group.
Once you've done that to build the array, you can use JSON.stringify to build your JSON string, something like this:
var arr = $('.slot_subclass').map(function() {
var obj = {};
$(this).find('.slot').each(function() {
obj[this.name] = this.value;
});
return obj;
}).get();
console.log(arr);
var json = JSON.stringify(arr);
console.log(json);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="slot_subclass">
<div class="form-group">
<input type="text" class="form-control slot" name="slot_name">
</div>
<div class="form-group">
<input type="text" class="form-control slot" name="slot_type">
</div>
</div>
<div class="slot_subclass">
<div class="form-group">
<input type="text" class="form-control slot" name="slot_name">
</div>
<div class="form-group">
<input type="text" class="form-control slot" name="slot_type">
</div>
</div>
<div class="slot_subclass">
<div class="form-group">
<input type="text" class="form-control slot" name="slot_name">
</div>
<div class="form-group">
<input type="text" class="form-control slot" name="slot_type">
</div>
</div>
You should use each(), not map()
$('.test').on('click', function() {
var obj = {}
$(".slot_subclass").each(function() {
var $slots = $(this).find('.slot');
obj[$slots.eq(0).val()] = $slots.eq(1).val()
})
console.log(obj)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="slot_subclass">
<div class="form-group">
<input type="text" class="form-control slot" name="slot_name">
</div>
<div class="form-group">
<input type="text" class="form-control slot" name="slot_type">
</div>
</div>
<div class="slot_subclass">
<div class="form-group">
<input type="text" class="form-control slot" name="slot_name">
</div>
<div class="form-group">
<input type="text" class="form-control slot" name="slot_type">
</div>
</div>
<div class="slot_subclass">
<div class="form-group">
<input type="text" class="form-control slot" name="slot_name">
</div>
<div class="form-group">
<input type="text" class="form-control slot" name="slot_type">
</div>
</div>
<button class="test">Test</button>
Following is based on :
where key is the value of first input
// set values for demo
setDemoValues()
// get data based on above values
var res = {};
$('.slot_subclass').each(function() {
var $inputs = $(this).find('.slot');
res[$inputs[0].value] = $inputs[1].value;
})
console.log(res)
function setDemoValues() {
$('.slot_subclass').each(function(i) {
$(this).find('.slot').val(function() {
return this.name + (i + 1);
})
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="slot_subclass">
<div class="form-group">
<input type="text" class="form-control slot" name="slot_name">
</div>
<div class="form-group">
<input type="text" class="form-control slot" name="slot_type">
</div>
</div>
<div class="slot_subclass">
<div class="form-group">
<input type="text" class="form-control slot" name="slot_name">
</div>
<div class="form-group">
<input type="text" class="form-control slot" name="slot_type">
</div>
</div>
<div class="slot_subclass">
<div class="form-group">
<input type="text" class="form-control slot" name="slot_name">
</div>
<div class="form-group">
<input type="text" class="form-control slot" name="slot_type">
</div>
</div>
You're on a right way but you need to change you algorithm.
Let's see $(".slot_subclass") is array of div elements - iterate that array, and got both 'key' and 'value' values :). For each element of $(".slot_subclass") you can get access to first and second nested inputs by something like $(el).find('.slot') and first element of that array is a first input, second is a second input.
So, what you can do is query all of the inputs, set their name as the key and their value as their input.
The problem you can run into, if you just do it as you have it now, is that your values will be overridden since you have multiple inputs with the same name.
You can get around that by adding a unique ID or class to their parent container.
var inputs = document.querySelectorAll("input");
var data = {};
for (var i = 0; i < inputs.length; i++) {
data[inputs[i].name] = inputs[i].value;
}
console.log(data);
For getting a specific set of inputs, using the unique identifier I mentioned above, all you have to do is change the query selector.
var inputs = document.querySelectorAll("#container input");
EDIT
Having an unknown amount of subclasses you can put them into an array. Following the same JS above, it's just one extra step.
var subclasses = document.querySelectorAll(".slot_subclass");
var data = [];
for (var i = 0; i < subclasses.length; i++) {
if (!data[i]) data[i] = {};
var inputs = subclasses[i].querySelectorAll("input");
for (var o = 0; o < inputs.length; o++) {
data[i][inputs[o].name] = inputs[o].value;
}
}
console.log(data);
// outputs like:
[
0: {slot_name: "", slot_type: ""}
1: {slot_name: "", slot_type: ""}
2: {slot_name: "", slot_type: ""}
]

Angularjs with rest api using SQLALCHEMEY joined tables

I am trying to create a webapp that uses angularjs and a backend api build in flask and sqlalchemy. The problem is that some keys in the json contain a dot and angularjs can't handle this. The problem is with the location.name field.
This is the json from the api
{
"brand": "Unknown",
"id": 6,
"location.name": "USB",
"name": "Usb verlengkabel 0.5m",
"uri": "http://localhost:5000/items/6"
}
And this is my angular controller:
angular
.module('inventory')
.controller('Item.ItemEditController', Controller);
function Controller($stateParams,$http) {
var ctrl = this;
$http.get(config.API_URL+'/items'+'/'+$stateParams.itemId ).success(function(data) {
ctrl.item = data;
}).error(function(data){ctrl.errormsg = data});
ctrl.updateItem = function () {
$http({
method: 'PUT',
url: config.API_URL +'/items/' + $stateParams.itemId,
data : this.item
})
.then(function successCallback(response) {
ctrl.result = { class:'alert alert-success', message:'Opgeslagen!'};
console.log(ctrl.result);
}, function errorCallback(response) {
console.log("error")
ctrl.result = { class:'alert alert-danger', message:'Er is iets fout gegaan bij het opslaan'};
});
}
}
And the html page
<div ng-if="ctrl.result.class" ng-class="ctrl.result.class">
{{ctrl.result.message}}
</div>
<form class="form-horizontal" role="form" ng-submit="ctrl.updateItem()">
<div class="form-group">
<label for="name" class="col-sm-2 control-label">Name</label>
<div class="col-sm-10">
<input type="text" ng-model="ctrl.item.name" class="form-control" id="name" placeholder="name"/>
</div>
</div>
<div class="form-group">
<label for="brand" class="col-sm-2 control-label">Brand</label>
<div class="col-sm-10">
<input type="text" ng-model="ctrl.item.brand" class="form-control" id="brand" placeholder="brand" />
</div>
</div>
<div class="form-group">
<label for="location" class="col-sm-2 control-label">Location</label>
<div class="col-sm-10">
<input type="text" ng-model="ctrl.location.name" class="form-control" id="location" placeholder="location" />
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="submit" class="btn btn-primary" value="Save"/>
</div>
</div>
</form>
use ctrl.item['location.name'] instead of ctrl.location.name
<input type="text"
class="form-control"
id="location"
placeholder="location"
ng-model="ctrl.item['location.name']" />
plunker: http://plnkr.co/edit/V2LsFL7SNMV8n5nkLQWa?p=preview

Categories