ng-click or ng-change don't save array - javascript

I have a new auction form. The user has to insert all the requested field , then by clicking on a button "Invite People" can invite other saved users or can invite people by e mail. The email part works fine. But the users part give me some problem.
The html part:
<div ng-show="showBid" class="panel panel-default" ng-controller="NewAuctionController">
<div class="panel-heading">Invite Members</div>
<div class="panel-body">
<ul class="list-group" ng-repeat="user in users">
<li class="col-md-4" id="userlist" ng-hide="user.name == profile">
<img ng-src="{{user.img}}" class="userImage">
<div class="username"> {{user.name}}</div>
<div class="userrole"> {{user.role}} </div>
<div class="usercompany">{{user.company}}</div>
<input type="checkbox" ng-model="user.isChecked" ng-click="insertinvited(user)">
</li>
</ul>
The above part i tried also with ng-change, but it's the same.
The insertinvited() is:
$scope.invitations=[];
$scope.insertinvited= function (user) {
if(user.isChecked) {
$scope.invitations.push(user.name);
} else {
var toDel = $scope.invitations.indexOf(user.name);
$scope.invitations.splice(toDel,1);
}
console.log($scope.invitations);
};
In the console this works, cause when i check the box the array is pushed correctly
But when i try to use that array here:
<div ng-show="showBid" class="panel panel-default" >
<div class="panel-heading">Members Selected:</div>
<div class="panel-body">
<ul class="list-group">
<li class="list-group-item" ng-repeat="invitation in invitations">
<div class="listmail"> {{invitation}}</div>
</li>
</ul>
</div>
</div>
The array seems to be empty, infact when i pass the array to the controller and i try to do a console.log the array is empty.
Anyone could me help?
Edited
This is all my html code:
<form ng-controller="NewAuctionController"
name="myform">
<div>
<div ng-hide="showBid">
<div ng-show="uploading" class="progress">
</div>
<label class="btn" style="background-color: #858892">
Browse
<input type="file" ng-disabled="uploading" file-model="file.upload" name="myfile" style="display: none;" onchange="angular.element(this).scope().photoChanged(this.files)">
</label>
<br>
<br>
<br>
<img class="mythumbnail" ng-src="{{ thumbnail.dataUrl || default }}">
<br>
<br>
<div ng-show="message">
<div ng-class="alert">{{ message }}</div>
</div>
<div class="form-group" id="productname">
<label for="exampleInputName1">Product Name</label>
<input type="text" class="form-control" id="exampleInputName1" placeholder="Enter Product" ng-model="productTitle" >
</div>
<br>
<div class="form-group">
<label for="exampleInputdescription1"> Description:</label>
<input type="text" class="form-control" id="exampleInputdescription1" placeholder="Enter Description" ng-model="productDescription" >
</div>
<div class="form-group">
<label> Expiration Date:</label><br>
<input type="date" class="form-control" name="expiration date" ng-model="endtime" ><br>
</div>
<div class="quantity">
<label>Quantity:</label><br>
<input type="number" name="quantity" ng-model="quantity" placeholder="u" class="form-control" ><br>
</div>
<div class="Warranty">
<label>Warranty (days):</label><br>
<input type="number" name="warranty" class="form-control" ng-model="warranty" placeholder="days" ><br>
</div>
<div class="form-group">
<label>Minimum Price:</label><br>
<input type="number" name="minimum price" id="min" ng-model="minPrice" placeholder="€" class="form-control" ><br>
</div>
<div class="form-group">
<label>Buy-Now Price:</label><br>
<input type="number" name="minimum price" id="min" ng-model="productbuynow" placeholder="€" class="form-control" ><br>
</div>
<div class="form-group">
<label>Location of the goods:</label><br>
<input type="text" name="location" id="country" ng-model="Country" placeholder="Country" class="form-control" ><br>
<input type="text" name="Town" id="town" ng-model="Town" placeholder="Town" class="form-control" ><br>
<input type="text" name="address" id="address" ng-model="Address" placeholder="Address" class="form-control" ><br>
<input type="text" name="Postal code" id="postalCode" ng-model="PostalCode" placeholder="Postal Code" class="form-control" ><br>
</div>
<div class="form-group">
<label>Terms of payment: </label><br>
<select ng-model="payment">
<option value="Letter of credit">Letter of credit</option>
<option value="Cash in advance">Cash in advance</option>
<option value="Confirmed Irrevocable Credit">Confirmed irrevocable Credit</option>
</select><br>
</div>
<div class="form-group">
<label>Terms of Delivery: </label><br>
<select ng-model="delivery">
<option value="Carriage Paid To">Carriage Paid To</option>
<option value="Free Carrier">Free Carrier</option>
<option value="Confirmed Irrevocable Credit">Ex Works</option>
</select><br>
</div>
<input class="savebutton" type="submit" value="Invite People" ng-click="clickToOpen5()"><br>
<div ng-show="showBid" class="panel panel-default" ng-controller="NewAuctionController">
<div class="panel-heading">Invite Members</div>
<div class="panel-body">
<ul class="list-group" ng-repeat="user in users">
<li class="col-md-4" id="userlist" ng-hide="user.name == profile">
<img ng-src="{{user.img}}" class="userImage">
<div class="username"> {{user.name}}</div>
<div class="userrole"> {{user.role}} </div>
<div class="usercompany">{{user.company}}</div>
<input type="checkbox" ng-model="user.isChecked" ng-change="insertinvited(user)">
</li>
</ul>
</div>
<div class="panel-heading">Members Selected:</div>
<div class="panel-body">
<ul class="list-group">
<li class="list-group-item" ng-repeat="invitation in invitations">
<div class="listmail"> {{invitation}}</div>
</li>
</ul>
</div>
<div class= "insertmail" ng-show=" showBid ">
Or Insert E-mail:<br>
<input type="email" name="emailaddress" ng-model="emailaddress">
<div ng-show="showBid" class="panel panel-default" >
<div class="panel-heading">Mail Inserted:</div>
<div class="panel-body">
<ul class="list-group">
<li class="list-group-item" ng-repeat="mail in mails">
<div class="listmail"> {{mail}}</div>
</li>
</ul>
</div>
</div>
<button ng-show="showBid" class="savebutton" ng-click="saveauction(profile)">SAVE</button><br>
</div>
</form>
And this is all my controller:
angular.module('NewAuctionCtrl', ['ngDialog', 'fileModelDirective', 'uploadFileService']).controller('NewAuctionController', ['$scope','$http' ,'ngDialog','uploadFile', '$timeout' , function($scope, $http, ngDialog, uploadFile, $timeout){
$scope.file = {};
$scope.message = false;
$scope.alert = '';
$scope.photoChanged = function (files) {
if (files.length > 0 && files[0].name.match(/\.(png|jpeg|jpg|pdf)$/)) {
$scope.uploading = true;
var file = files[0];
var fileReader = new FileReader();
fileReader.readAsDataURL(file);
fileReader.onload = function(e) {
$timeout(function() {
$scope.thumbnail = {};
$scope.thumbnail.dataUrl = e.target.result;
$scope.uploading = false;
$scope.message = false;
});
};
} else {
$scope.thumbnail = {};
$scope.message = false;
}
};
$http.get('/api/users').then(function(Users) {
$scope.users = Users.data;
});
$scope.mails = [];
$scope.emailaddress = '';
$scope.insertmail = function () {
$scope.mails.push($scope.emailaddress);
$scope.emailaddress = '';
};
$scope.invitations = [] ;
$scope.insertinvited= function (user) {
if(user.isChecked) {
$scope.invitations.push(user.name);
} else {
var toDel = $scope.invitations.indexOf(user.name);
$scope.invitations.splice(toDel,1);
}
console.log($scope.invitations);
};
$scope.saveauction = function (user) {
console.log($scope.invitations);
var array = {
param1: $scope.productTitle,
param2: $scope.productDescription,
param3: $scope.endtime,
param4: $scope.minPrice,
param5: $scope.productbuynow,
param6: user,
param7: $scope.quantity,
param8: $scope.warranty,
param9: $scope.Country,
param10: $scope.Town,
param11: $scope.Address,
param12: $scope.PostalCode,
param13: $scope.payment,
param14: $scope.delivery,
param15:$scope.invitations
};
$scope.uploading = true;
uploadFile.upload($scope.file).then(function (data) {
if (data.data.success) {
$scope.uploading = false;
$scope.alert = 'alert alert-success';
$scope.message = data.data.message;
$scope.file = {};
$http.post('/api/newauction', array)
.then(
function () {
swal(
'Good job!',
'New Auction is created',
'success'
)
});
$scope.sendmail();
}
else {
$scope.uploading = false;
$scope.message = data.data.message;
swal(
'Oops...!',
$scope.message,
'error'
);
$scope.file = {};
}
});
};
$scope.clickToOpen5 = function () {
$scope.showBid = !$scope.showBid;
};
$scope.sendmail = function (){
var address = $scope.mails;
console.log(address);
if(address[0]) {
$http.post('/api/sendmail/', {address: address}).then(function (err) {
if (err)
console.log(err);
});
}
};
});

You should change ng-click to ng-change
<input type="checkbox" ng-model="user.isChecked" ng-change="insertinvited(user)">
And in del of you , i think it should
var todel =$scope.invitations.indexOf(user.name);
$scope.invitations.splice(toDel,1);

This can be the problem of scope inheritance in angular JS.
try to do following changes:
In controller save this to some parameter like:
var vm = this;
now use vm.invitations instead of $scope.invitations.
and in ng-repeat use:
ng-repeat="invitation in vm.invitations"

You are clearing the array with each click.
Remove this statement:
$scope.invitations = [];
and move it to controller's main body; then it should work(especially if you're using ng-change).

this is due to the prototypical inheritance in javascript.
using var vm= this inside controller and
renaming $scope.invitations to vm.invitations in controller and invitations in html to vm.invitations.
will resolve the issue

Related

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>

AngularJS dynamic forms with ng-repeat

i am working with AngularJS dynamic forms . According to my userid value i generated multiple form field with same model name using ng-repeat. i am not able to get this input model values due to this ng-repeat. in this example i am using static userid data.
<div ng-app="myApp">
<div ng-controller="myCtrl">
<form role="form" name='userForm' novalidate>
<div class="container">
<div class="row" ng-repeat="myid in userid">
<div class="form-group">
<div class="col-md-3">
<label>ID</label>
<input ng-model="myid" id="myid" name="myid" placeholder="Enter bugid" type="text" required readonly disabled>
</div>
<div class="col-md-3">
<label>Comments</label>
<textarea ng-model="manualComment" id="textarea1" rows="1" required></textarea>
</div>
<div class="col-md-3 ">
<label>Gender</label>
<select ng-model="gender" name="select2" required>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
</div>
</div>
</div>
</div>
<div class="buttonContainer text-center btn-container">
<br>
<button ng-disabled="userForm.$invalid" type="button" id="adduser" ng-click="adduser">Add user</button>
<button type="button" class="btn button--default btn--small pull-center">Close</button>
</div>
</form>
</div>
my js code
var myApp = angular.module('myApp', []);
myApp.controller('myCtrl', function($scope) {
$scope.userid = [1, 2, 3];
$sope.adduser = function() {
}
});
i need to send array of objects to my server.my userid also dynamic it has more than 100 data. how can i get each and every data field model value? and how to convert those model data into array of objects like my sampleserver data?
i am expecting my final output data like this
var sampleServerData = [{
"userid": 1,
"manualcomment": "mycmt1",
"gender": "male"
}, {
"userid": 2,
"manualcomment": "mycmt2",
"gender": "male"
}, {
"userid": 3,
"manualcomment": "mycmt3",
"gender": "female"
}]
You should change your textarea id to a class or create a textarea id in your user object(more on that below).
If the id's you have to work with are in an array, then create an array of objects based on you ids array.
var ids = [1, 2, 3];
var users = ids.map(function(id) {
return {id: id, comment: "", gender: ""};
})
I think I have a solution for you, I made you a jsbin. Make sure you hit the run with js button, for some reason it doesn't run onload.
HTML
<div ng-app="myApp">
<div ng-controller="myCtrl">
<form role="form" name='userForm' novalidate>
<div class="container">
<div class="row" ng-repeat="user in users">
<div class="form-group">
<div class="col-md-3">
<label>ID</label>
<input ng-model="user.id" id="user.id" name="user.id" placeholder="Enter bugid" type="text" required readonly disabled>
</div>
<div class="col-md-3">
<label>Comments</label>
<textarea ng-model="user.comment" id="textarea1" rows="1" required></textarea>
</div>
<div class="col-md-3 ">
<label>Gender</label>
<select ng-model="user.gender" name="select2" required>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
</div>
</div>
</div>
</div>
<div class="buttonContainer text-center btn-container">
<br>
<button ng-disabled="userForm.$invalid" type="button" id="adduser" ng-click="adduser()">Add user</button>
<button type="button" class="btn button--default btn--small pull-center">Close</button>
</div>
</form>
</div>
JS
var myApp = angular.module('myApp', []);
myApp.controller('myCtrl', function($scope) {
$scope.ids = [1, 2, 3];
$scope.users = $scope.ids.map(function(id) {
return {id: id, comment: "", gender: ""};
});
$scope.adduser = function() {
var data = $scope.users.map(function(user) {
return {
"userid": user.id,
"manualcomment": user.comment,
"gender": user.gender
}
});
console.log("data", data)
}
});
In your HTML file you can call ng-repeat like this;
<div ng-app="myApp">
<div ng-controller="myCtrl">
<form role="form" name='userForm' novalidate>
<div class="container">
<div class="row" ng-repeat="myid in userId">
<div class="form-group">
<div class="col-md-3">
<label>ID</label>
<input ng-model="userId[$index].id" id="myid"name="myid" placeholder="Enter bugid" type="text" required readonly disabled>
</div>
<div class="col-md-3">
<label>Comments</label>
<textarea ng-model="userId[$index].manualcomment" id="textarea1" rows="1" required></textarea>
</div>
<div class="col-md-3 ">
<label>Gender</label>
<select ng-model="userId[$index].gender" name="select2" required>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
</div>
</div>
</div>
</div>
<div class="buttonContainer text-center btn-container">
<br>
<button ng-disabled="userForm.$invalid" type="button" id="adduser" ng-click="addusers()">Add user</button>
<button type="button" class="btn button--default btn--small pull-center">Close</button>
</div>
</form>
</div>
And then in the controller.
var myApp = angular.module('myApp', []);
myApp.controller('myCtrl', function($scope) {
$scope.userId = [1,2,3,4,5] // or new Array(3);
$sope.adduser = function() {
var serverData = $scope.userId;
}
});
you can use track by $index in ng-repat and then use the index for models
<div class="row" ng-repeat="myid in userid track by $index">
<div class="form-group">
<div class="col-md-3">
<label>ID</label>
<input ng-model="userId[$index].id" id="myid"name="myid" placeholder="Enter bugid" type="text" required readonly disabled>
</div>
<div class="col-md-3">
<label>Comments</label>
<textarea ng-model="userId[$index].manualcomment" id="textarea1" rows="1" required></textarea>
</div>
<div class="col-md-3 ">
<label>Gender</label>
<select ng-model="userId[$index].gender" name="select2" required>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
</div>

My validating a captcha using JavaScript is not working

<script>
function validate2(id)
{
var regex = [a-z];
var ctrl = document.getElemetnById(id);
if (regex.test(ctrl.value)) {
return true;
}
else {
return false;
}
}
</script>
<script>
function TestCompanyName(txtCompanyName){
var obj = document.getElementById(txtCompanyName);
var RegEx = /THE DAMN REGULAR EXPRESSION/
if(RegEx.test(obj.value)==false)
{
alert("Invalid");
}
}
</script>
</script>
<script>
function checklname(input1)
{
var pattern=/^([a-zA-Z0-9_.-])+#([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
return pattern.test(input1);
}
if(!isvalid) {
alert('Invalid name');
document.getElementById("input1").value = "";
}
}
</script>
<script>
function phonenumber(telno) {
var phoneno = /^\+?([0-9]{2})\)?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/;
if(telno.value.match(phoneno))
{
return true;
}
else {
alert("message");
return false;
}
}
</script>
<script>
function phonenumber2(mobileno) {
var phoneno1 = /^\+?([0-9]{2})\)?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/;
if(mobileno.value.match(phoneno1))
{
return true;
}
else {
alert("message");
return false;
}
}
</script>
<script>
function validate() {
var ta = document.getElementById("ta").value;
var answer = document.getElementbyId("answer").value;
var digit1 = parseInt(document.getElementById("digit1").innerHTML);
var digit2 = parseInt(document.getElementById("digit2").innerHTML);
var sum = digit1 + digit2;
if(answer == null || answer == ""){
alert("please add the number");
return false;
}else if(answer != sum){
alert("you math is wrong");
}else if(ta == null || ta == ""){
alert("please fill in the textarea");
}else{
document.getElementById("status").innerHTML = "processing";
document.getElementById("answer").innerHTML = "";
}
}
function randomNums(){
var rand_num1 = Math.floor(Math.random() * 10) +1;
var rand_num2 = Math.floor(Math.random() * 10) +1;
document.getElementById("digit1").innerHTML = rand_num1;
document.getElementById("digit2").innerHTML = rand_num2;
}
</script
<script>
function checkEmail(inputvalue){
var pattern=/^([a-zA-Z0-9_.-])+#([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
return pattern.test(inputvalue);
}
checkEmail('rte#co') // false
checkEmail('rte#co.com') // true
</script>
<script>
var address = /^[a-zA-Z0-9-\/] ?([a-zA-Z0-9-\/]|[a-zA-Z0-9-\/] )*[a-zA-Z0-9-\/]$/;
if ( address.test($.trim($('#address').val())) == false)
{
alert('invalid address ');
}
</script>
<script>
function IsValidZipCode(zipcode) {
var isValid = /[\^$%#!#&\*:<>\?\/\\~\{\}\(\)\+|]/.test(zipcode);
if (!isValid){
alert('Invalid ZipCode');
document.getElementById("zipcode").value = "";
}
</script>
<script type="text/javascript" src="js/bootstrap-3.1.1.min.js"></script>
<script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>
<?php include("include files/favicon.php"); ?>
</head>
<body itemscope itemtype="http://schema.org/Organization">
<?php
include("include files/header.php");
?>
<?php
include("include files/navigation.php");
?>
<!--breadcrumb-->
<div id='location'>
<div id="BannerAndNavigatorHtmlBlock_StoreNavigator_pnNavigator" itemscope="" itemtype="http://schema.org/BreadcrumbList" class="btn-group btn-breadcrumb">
<span itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem" class="btn btn-success">
<a itemprop="item" href="/">
<span class="glyphicon glyphicon-home" itemprop="name">
</span>
</a>
<span itemprop="position" content="1">
</span>
</span>
</span>
<span itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem"class="btn btn-success">
<span itemprop="name">Playing Card Quote</span><span itemprop="position" content="2"></span>
</span>
</div>
</div>
<!--Main Content-->
<div class="wrapper">
<div class="container">
<div> </div>
<div class="well">
<form action="thank-you.php" method="post" id="form1" onsubmit="MM_validateForm('quantity','','R','fname','','R','email','','NisEmail','telno','','RisNum','address','','R','city','','R','state','','R','country','','R','zipcode','','R');return document.MM_returnValue && jcap();">
<fieldset>
<legend>
<h1>Fill Quote Form</h1>
</legend>
<div class="quote-form">
<div> </div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-6">Plastic Coated Paper :</label>
<div class="col-sm-3">
<select class="form-control" name="plastic_coated_paper" id="plastic_coated_paper" onchange="chgSelect('coatedpaper');">
<option selected value="0" id="selectpaper">Select Paper</option>
<option>Black Centered 330</option>
<option>Black Centered 320</option>
<option>Black Centered 315</option>
<option>Black Centered 305</option>
<option>Black Centered 300</option>
<option>Black Centered 280</option>
<option>White Centered 330</option>
<option>White Centered 320</option>
<option>White Centered 315</option>
<option>White Centered 305</option>
<option>White Centered 300</option>
<option>White Centered 280</option>
</select>
</div>
<div class="col-sm-3" style="text-align:center;">
</div>
<br>
<br>
<center>OR</center>
</div>
</div>
<div> </div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-6">100% Pure Plastic : </label>
<h2>Your Contact Information :</h2>
<form action="" method="POST">
<div> </div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-6"><i>*</i> First Name</label>
<div class="col-sm-3">
<div>
<input name="fname" id= "id" type="text" onSubmit="" tabindex="2" required="required">
</div>
</div>
<div class="col-sm-3">
</div>
</div>
</div>
<div> </div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-6"><i>*</i> Last Name</label>
<div class="col-sm-3">
<div>
<label>
<input name="lname" id="input1" type="text" tabindex="2" required="required">
</label>
</div>
</div>
<div class="col-sm-3">
</div>
</div>
</div>
<div> </div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-6"><i>*</i> Email Id</label>
<div class="col-sm-3">
<div>
<label>
<input name="email" type="email" tabindex="2" required="required">
</label>
</div>
</div>
</div>
<div class="col-sm-3">
</div>
</div>
</div>
<div> </div>
<div class="row">
<div class="form-group">
<div class="col-sm-6">
</div>
<div class="col-sm-5">(Please type in a correct email address , as the quotes will be forwarded there)</div>
</div>
</div>
<div> </div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-6"><i>*</i> Telephone Number</label>
<div class="col-sm-3">
<div>
<label>
<input name="telno" id="telno" type="text" tabindex="2" required="required">
</label>
</div>
</div>
<div class="col-sm-3">( Do not enter space)
</div>
</div>
</div>
<div> </div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-6"><i>*</i> Mobile Number</label>
<div class="col-sm-3">
<div>
<label>
<input name="mobileno" id="mobileno" type="text" tabindex="2" required="required">
</label>
</div>
</div>
<div class="col-sm-3">
</div>
</div>
</div>
<div> </div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-6"> <i>*</i> Company Name</label>
<div class="col-sm-3">
<div>
<label>
<input type="text" name="txtCompanyName" id="txtCompanyName" required="required" onclick="TestCompanyName('txtCompanyName')">
</label>
</div>
</div>
<div class="col-sm-3">
</div>
</div>
</div>
<div> </div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-6"><i>*</i> Address</label>
<div class="col-sm-3">
<input id="address" class="address" type="text" name="address"
onchange="IsValidAddress(this.form.address.value)" required="required" >
</div>
<div class="col-sm-3">
</div>
</div>
</div>
<div> </div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-6"><i>*</i> Zip Code :</label>
<div class="col-sm-3">
<input id="zipcode" class="zipcode" type="text" name="zipcode" onchange="IsValidZipCode(this.form.zipcode.value)" required="required" >
<br />
</div>
<div class="col-sm-3">
</div>
</div>
</div>
<div> </div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-6"><i>*</i> City</label>
<div class="col-sm-3">
<input class="form-control" name="city" type="text" id="city" required="required" value="">
</div>
<div class="col-sm-3">
</div>
</div>
</div>
<div> </div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-6"><i>*</i> State</label>
<div class="col-sm-3">
<input class="form-control" name="state" type="text" id="state" value="" required ="required">
</div>
<div class="col-sm-3">
</div>
</div>
</div>
<div> </div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-6"><i>*</i> Country</label>
<div class="col-sm-3">
<input class="form-control" name="country" type="text" id="country" value="" required="required">
</div>
<div class="col-sm-3">
</div>
</div>
</div>
<div> </div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-6"> Fax</label>
<div class="col-sm-3">
<input class="form-control" name="fax" type="text" id="fax" value="" required ="required">
</div>
<div class="col-sm-3">
</div>
</div>
</div>
<div> </div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-6"><i>*</i> Captcha</label>
<div class="col-sm-2">
</div>
<div class="col-sm-3">
<body>
<form name="review" ACTION="newpg.html" METHOD="POST" onsubmit="return checkform(this);">
<font color="#DD0000">Enter Code ></font> <span id="txtCaptchaDiv" style="background-color:#A51D22;color:#FFF;padding:5px"></span>
<input type="hidden" id="txtCaptcha" />
<input type="text" name="txtInput" id="txtInput" size="15" />
<input type="submit" value="Submit"/>
</form>
<script type="text/javascript">
function checkform(theform){
var why = "";
if(theform.txtInput.value == ""){
why += "- Security code should not be empty.\n";
}
if(theform.txtInput.value != ""){
if(ValidCaptcha(theform.txtInput.value) == false){
why += "- Security code did not match.\n";
}
}
if(why != ""){
alert(why);
return false;
}
}
//Generates the captcha function
var a = Math.ceil(Math.random() * 9)+ '';
var b = Math.ceil(Math.random() * 9)+ '';
var c = Math.ceil(Math.random() * 9)+ '';
var d = Math.ceil(Math.random() * 9)+ '';
var e = Math.ceil(Math.random() * 9)+ '';
var code = a + b + c + d + e;
document.getElementById("txtCaptcha").value = code;
document.getElementById("txtCaptchaDiv").innerHTML = code;
// Validate the Entered input aganist the generated security code function
function ValidCaptcha(){
var str1 = removeSpaces(document.getElementById('txtCaptcha').value);
var str2 = removeSpaces(document.getElementById('txtInput').value);
if (str1 == str2){
return true;
}else{
return false;
}
}
// Remove the spaces from the entered and generated code
function removeSpaces(string){
return string.split(' ').join('');
}
</script>
</body>
<div class="col-sm-3">
</div>
</div>
<div> </div>
<div class="row">
<div class="form-group">
<div class="col-sm-12">
<center>
<input type="submit" value="Submit" class="btn1" name="submit" id="send">
</center>
</div>
</div>
</div>
<div> </div>
</div>
</fieldset>
</form>
</div>
</div>
</div>
<!---footer---><?php include("include files/footer.php");?>
</body>
</html>
I am not able to provide validation for captcha using validation? My function is not displaying message for me if security code did not match or security code should not be empty.
What is the problem in the program? Why is not validating my captcha properly? I tried it many times but not able to validate my captcha code
What is the error in the page for captcha validation? What is the correct validation for captcha ?
The code you posted does not have any issues. It does what it is supposed to do, generate a code and validate that the input matches it before allowing the form to be submitted.
However, if you are really interested in preventing bots from submitting the form, then this code is not going to help you at all. You generate the code on the client and save it in your input. A bot would read that input and provide the captcha with no issues at all.
EDIT: suggestion for recaptcha
I would suggest that you integrate your application with an established recaptcha provider, as is for example recaptcha. Please note that the validation of the captcha input should be performed in your server
You can find further details for recaptcha here.
The code is working as you might expect. Please review the fiddle I had to made no change at all.
https://jsfiddle.net/43m63ezf/
HTML
<label>Captcha</label>
<form name="review" ACTION="palying-cards-quote.php" METHOD="POST" onsubmit="return checkform(this);">
<font color="#DD0000">Enter Code </font> <span id="txtCaptchaDiv" style="background-color:#A51D22;color:#FFF;padding:5px"></span>
<input type="hidden" id="txtCaptcha" />
<input type="text" name="txtInput" id="txtInput" size="15" />
<input type="submit" value="Submit" />
</form>
JS
function checkform(theform) {
var why = "";
if (theform.txtInput.value == "") {
why += "- Security code should not be empty.\n";
}
if (theform.txtInput.value != "") {
if (ValidCaptcha(theform.txtInput.value) == false) {
why += "- Security code did not match.\n";
}
}
if (why != "") {
alert(why);
return false;
}
}
//Generates the captcha function
var a = Math.ceil(Math.random() * 9) + '';
var b = Math.ceil(Math.random() * 9) + '';
var c = Math.ceil(Math.random() * 9) + '';
var d = Math.ceil(Math.random() * 9) + '';
var e = Math.ceil(Math.random() * 9) + '';
var code = a + b + c + d + e;
document.getElementById("txtCaptcha").value = code;
document.getElementById("txtCaptchaDiv").innerHTML = code;
// Validate the Entered input aganist the generated security code function
function ValidCaptcha() {
var str1 = removeSpaces(document.getElementById('txtCaptcha').value);
var str2 = removeSpaces(document.getElementById('txtInput').value);
if (str1 == str2) {
return true;
} else {
return false;
}
}
// Remove the spaces from the entered and generated code
function removeSpaces(string) {
return string.split(' ').join('');
}

ng-model not updating with input from textbox

This seems like a weird one to me. I have a form for adding vets to a dog walkers' database. I've used ng-model on each field in the form.
<div class="container-fluid" ng-show="nav.page == 'new'" ng-controller="dataController as data">
<div class="row" ng-show="nav.tab == 'vet'">
<div class="col-md-2">
</div>
<div class="col-md-8">
<h1>Add a Vet</h1>
<hr />
<form>
<div class="form-group">
<input type="text" class="form-control" placeholder="Name..." ng-model="data.creator.vet.Name"/>
</div>
<div class="form-group">
<input type="Text" class="form-control" placeholder="Address..." ng-model="data.creator.vet.Address"/>
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="Phone Number..." ng-model="data.creator.vet.Phone"/>
</div>
<div class="form-group">
<button class="btn btn-success" ng-click="data.newVet()">Submit</button>
</div>
</form>
</div>
<div class="col-md-2">
</div>
</div>
</div>
Yesterday it was working fine, today it won't update data.creator.vet when I input data. For the life of me, I can't see any problems with it.
The js:
app.controller('dataController', function($http) {
dataCon = this;
this.creator = {};
this.creator.client = {};
this.creator.vet = {};
this.creator.client.Dogs = [];
this.allData = {};
this.newVet = function(){
console.log("New Vet Creating....")
console.log(dataCon.creator)
vet = JSON.stringify(dataCon.creator.vet);
console.log(vet);
$http.get(SERVICE_URL + "?fn=vetCreate&vet=" + vet).then(function(response) {
dataCon.init();
});
}
});

Unable to create array of object to save MongoDB from AngularJS

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

Categories