Unable validate input value in ng repeat using iteration - javascript

<tr ng-repeat="labour in labourdata">
<td>{{$index+1}}</td>
<td data-title="'Mobile No'" sortable="Mobile no">
<input type="text" class="form-control" name="mobile" id="mobile" ng-model="labour.mobile" value={{labour.mobile}} placeholder="Enter Aadhaar" typeahead="mobile.Mobileid for mobile in MobileArray" ng-blur="change_mobile(mobile)" >
</td>
<td data-title="'NAME'" sortable="NAME">
<input type="hidden" ng-model="labour.lid" id="lid" name="lid" />
<input type="text" class="form-control" id="name" ng-model="labour.name" placeholder="Name" readonly>
</td>
<td>
<input type="button" ng-click="addFormField(mobile)" class="btn btn-default" value="Add " />
</td>
</tr>
Here is Js code
//Get Mobile Number
$scope.labourdata = [{}];
$scope.MobileArray = [];
$http({method: 'GET',url: 'get-num.php',labourdata: { applicationId: 3 }})
.success(function (labourdata)
{
$scope.MobileArray = labourdata;
});
// Change Mobile number
$scope.change_mobile=function(mobile)
{
var j=-1;
var mobile = "";
for (var i = 0; i < $scope.labourdata.length; i++)
{
j++;
mobile = $scope.labourdata[i]["mobile"];
}
$http.post('get-labour-details.php', {'selectedmobile': mobile})
.success(function (data, status, headers, config)
{
var comArr = eval($scope.labourdata);
comArr[j].lid = data[0]["LabourId"];
comArr[j].name = data[0]["Name"];
});
}
//Add one more Field
$scope.labourdata = [{}];
$scope.addFormField = function(mobile)
{
var mobile = "";
var found = $scope.labourdata.reduce(function(previous, i)
{
if (mobile === i) return true;
return previous;
}, false);
if (found){
alert('already taken.');
}
else
{
alert('ok');
$scope.labourdata.push({});
}
}
Unable to validate input field in ng-repeat.
if we given Mobile No input filed as a '9999999999'. it displaying 'XXX' name in NAME input field.
When i click on Add button, the next row appears. Problem is while adding one more time Mobile No input filed as a '9999999999'.
it should be alert as a it's already taken. because i already selected Mobile no '9999999999' previously.
How to validate input data in iteration while clicking Add button.
Is there is any way to solve this problem?

Related

How to remove oninvalid for every input except one using javascript?

I created a form with some input fields and the user needs to fill at least one field and if the user doesn't select any then the error will be shown. I achieve that goal but I need to show my custom require message as invalid. Because of the oninvalid on every input, My code is not working properly but I want this message to show so how can I remove oninvalid from the rest of the input fields rather than the filled one?
<form>
<input name="youtube" oninvalid="this.setCustomValidity('Please fill out at least one social media field')" required/>
<input name="vimeo" oninvalid="this.setCustomValidity('Please fill out at least one social media field')" required/>
<input name="pinterest" oninvalid="this.setCustomValidity('Please fill out at least one social media field')" required/>
<input type="submit" name="submit" value="Submit" id="ls-submit">
</form>
document.addEventListener('DOMContentLoaded', function () {
const inputs = Array.from(document.querySelectorAll('input[name=youtube], input[name=vimeo], input[name=pinterest]'));
const inputListener = e => inputs.filter(i => i !== e.target).forEach(i => i.required = !e.target.value.length, i => i.oninvalid = !e.target.value.length);
inputs.forEach(i => i.addEventListener('input', inputListener));
});
I really don't have an idea what to do. We can also use alert as an error message and I tried that too but didn't get any success.
You could remove oninvalid and required from all inputs and check it instead with javascript:
var inputs = document.querySelectorAll('input');
document.querySelector('button').addEventListener('click', function() {
var valid = false;
for(i = 0; i < inputs.length; i++) {
if ( inputs[i].value != "" ) {
valid = true;
break;
}
}
if (valid) {
document.querySelector("form").submit();
}
else {
alert('Please fill out at least one social media field');
}
});
Working example (with 'alert' instead of 'setCustomValidity'):
var inputs = document.querySelectorAll('input');
document.querySelector('button').addEventListener('click', function() {
for(i = 0; i < inputs.length; i++) {
var valid = false;
if ( inputs[i].value != "" ) {
valid = true;
break;
}
}
if (valid) {
document.querySelector("form").submit();
}
else {
alert('Please fill out at least one social media field');
}
});
<form action="https://stackoverflow.com" method="GET">
<input name="youtube" value="">
<input name="vimeo" value="">
<input name="pinterest" value="">
<button type="button">submit</button>
</form>

jquery: how to update input value using onchange?

I created a discount function for my order page where I have an issue that is , on my order page by default when product quantity is 1 then discounted rate show correctly in Final textbox but when I change the Quantity, like 1 to 2,3,4,5.. then my code not works and the amount show without discount rate.
I try to fix this but I not understand where is mistake and how I fix that.
Below is my code which I am using please help and tell me how I make this correct.
Your help will be really appreciate.
Thank you!
function getTotal(row = null) {
if(row) {
var disc = $('#dis_1').val();//
var dec = (disc/100).toFixed(2); //
var total = Number($("#rate_value_"+row).val()) * Number($("#qty_"+row).val()) * dec;
//total = total.toFixed(2);
var rate = Number($("#rate_value_"+row))-total;
total = total.toFixed(2);
$("#amount_"+row).val(total);
$("#amount_value_"+row).val(total);
subAmount();
} else {
alert('no row !! please refresh the page');
}
}
//**---**/
//*---*//
// get the product information from the server
function getProductData(row_id)
{
var product_id = $("#product_"+row_id).val();
if(product_id == "") {
$("#rate_"+row_id).val("");
$("#rate_value_"+row_id).val("");
$("#qty_"+row_id).val("");
$("#amount_"+row_id).val("");
$("#amount_value_"+row_id).val("");
} else {
$.ajax({
url: base_url + 'orders/getProductValueById',
type: 'post',
data: {product_id : product_id},
dataType: 'json',
success:function(response) {
// setting the rate value into the rate input field
$("#rate_"+row_id).val(response.price);
$("#rate_value_"+row_id).val(response.price);
$("#dis_"+row_id).val(response.discount);
$("#dis_value_"+row_id).val(response.discount);
$("#qty_"+row_id).val(1);
$("#qty_value_"+row_id).val(1);
//DISCOUNT
var disc = $('#dis_1').val();
var dec = (disc/100).toFixed(2);
var total = Number(response.price) * dec;
var rate = Number(response.price)-total;
total = rate.toFixed(2);
$("#amount_"+row_id).val(total);
$("#amount_value_"+row_id).val(total);
subAmount();
} // /success
}); // /ajax function to fetch the product data
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<td><input type="text" name="qty[]" id="qty_1" class="form-control" required onkeyup="getTotal(1)" placeholder="Quantity"></td>
<td>
<input type="text" name="rate[]" id="rate_1" class="form-control" autocomplete="off" placeholder="Rate">
</td>
<td>
<input type="text" placeholder="Discount" name="dis[]" id="dis_1" class="form-control" autocomplete="off">
</td>
<td>
<input type="text" placeholder="Total Price" name="amount[]" id="amount_1" class="form-control" autocomplete="off">
</td>
I am using my database to fetch the amount like product real rate, discounts.
In your line of HTML
<td><input type="text" name="qty[]" id="qty_1" class="form-control" required onkeyup="getTotal(1)" placeholder="Quantity"></td>
you are always calling getTotal with a value of 1, I think you want to instead get the value of the text box when the getTotal function is called and use that as your row value. In jquery you can get the value of the box by
row = $("#qty").val()

How to assign reassign checkbox ng-model on ng-repeat

Please help me out. I have a checkboxes with models defined. I am displaying checkboxes and using the model to set if the checkbox is selected or not. Below is the code for setting the ng-model.
LoadValues(obj) {
vm.index = false;
vm.create = false;
vm.edit = false;
vm.delete = false;
vm.other = false;
var pList = obj.Functions;
var currentModule = obj.Name;
for (var i = 0; i < pList.length; i++) {
var currentItem = pList[i];
console.log(currentItem)
if (currentItem.search("Index") > 0) {
vm.index = true;
console.log(vm.index);
} else if (currentItem.search("Create") > 0) {
vm.create = true;
} else if (currentItem.search("Edit") > 0) {
vm.edit = true;
} else if (currentItem.search("Delete") > 0) {
vm.delete = true;
} else if (currentItem.search("Other") > 0) {
vm.other = true;
}
}
}
Below is the check boxes.
<tbody>
<tr ng-repeat="item in list">
<td>
{{item.Name}}
</td>
<td>
<input id="Index" type="checkbox" ng-model="vm.index" ng-click="EditRole(Right,item.Module,'Index')">
</td>
<td>
<input id="Create" type="checkbox" ng-model="vm.create" ng-click="EditRole(item.Role,'Create')">
</td>
<td>
<input id="Edit" type="checkbox" ng-model="vm.edit" ng-click="EditRole(item.Role,item.Module,'Edit')">
</td>
<td>
<input id="Delete" type="checkbox" ng-model="vm.delete" ng-click="EditRole(item.Role,item.Module,'Delete')">
</td>
<td>
<input id="Other" type="checkbox" ng-model="vm.other" ng-click="EditRole(item.Role,item.Module,'Other')">
</td>
</tr>
</tbody>
The problem is it assigns the same ng-model to all the items in the list. I have tried to find solutions nothing is helping. Your help would be very much appreciated.
i am reading my data from a json file. Below is some example data:
[
{"Role":"Staff","Admins":[{"Name":"Username","userRights":["UserEdit","UserCreate"]
}]
The easiest way to use ng-model on a checkbox is to pass it an abject. The code below converts an array of items into an object for the checkboxes.
I created a variable called $scope.userRights which contains all of the available options.
In the HTML we loop though each field displaying its name and then loop though all of the userRights.
The submit button then converts the object back into the array format we received.
HTML
<div ng:controller="MainCtrl">
<button ng-click="submit()">Submit</button>
<table>
<tr ng-repeat="field in fields">
<td ng-bind="field.Name"></td>
<td ng-repeat="right in userRights">
<label>
<input type="checkbox" ng-model="field.userRights[right]" /> {{right}}
</label>
</td>
</tr>
</table>
<pre ng-bind="fields | json"></pre>
</div>
JavaScript
app.controller('MainCtrl', function($scope) {
$scope.userRights = ["UserEdit","UserCreate","UserSomethingElse"];
$scope.fields = [
{"Name":"Username","userRights":["UserEdit","UserCreate"]},
{"Name":"Password","userRights":["UserEdit"]}
];
// Convert array to object
$scope.fields.forEach(function(field) {
var res = {};
field.userRights.forEach(function(right) {
res[right] = true;
});
field.userRights = res;
});
function objectValues(obj) {
var res = [];
var keys = Object.keys(obj);
for (var i=0; i<keys.length; i++) {
if (obj[keys[i]]) res.push(keys[i]);
}
return res;
}
// Convert object to array
$scope.submit = function() {
$scope.fields.forEach(function(field) {
field.userRights = objectValues(field.userRights);
});
};
});
Demo
Your ng-model has to be like so:
ng-model="item.index"
And then in your controller inside the for loop:
current_item.index = true;
Hope it helps =)

JavaScript form same values

How can I make a form so they cannot repeat the same values in the Input?
I tried a way like:
var text1 = document.getElementById('num1').value;
var text2 = document.getElementById('num1').value;
var textform = [text1,text2];
if (
text1 == text2 ||
text2 == text1
) {
alert("repeated numbers");
return false;
}
But this is gets me into two troubles:
- If I put no value, it will say: Repated Numbers
- If I want to make this for 100 form values, it takes a lot of code
You could give all of your text elements the same class, and grab their values by class name to simplify building the array of text values.
<input type="text" class="checkDupe" id="input1" />
<input type="text" class="checkDupe" id="input2" />
Then grab their values in javascript
var checkDupes = document.getElementsByClassName('checkDupe');
var textArray = [];
for(var i = 0; i < checkDupes.length; i++){
textArray.push(checkDupes[i].value);
}
Now that we have an array of values that they entered, check to see if any of them repeat by sorting the array, and seeing if any two elements side-by-side are the same.
textArray.sort();
var dupes = false;
for(var i = 0; i < textArray.length; i++){
if(textArray[i] === textArray[i + 1]) dupes = true;
}
If we find any duplicates, let the user know.
if(dupes) alert('Repeated numbers!');
You could do something like this:
var text1 = document.getElementById('num1').value;
var text2 = document.getElementById('num2').value;
var textform = [text1, text2];
var seen = {};
textform.forEach(function(value) {
if (seen[value]) {
alert('Bad!');
}
seen[value] = true;
});
In the code above, we loop over each value in the array. The first time we encounter it, we push it into a map. Next time (if) we hit that value, it will exist in the map and it will tell us we've seen it before.
If you give all the input's a common class then you quickly loop through them.
The HTML:
<input type="text" name="num1" class="this that number"></input>
<input type="text" name="num2" class="this number"></input>
<input type="text" name="num3" class="that number"></input>
<input type="text" name="num4" class="number"></input>
<input type="text" name="num5" class=""></input> <!-- we don't want to check this one -->
<input type="text" name="num6" class="number that this"></input>
<input type="text" name="num7" class="this that number"></input>
The JavaScript:
// get all the inputs that have the class numbers
var ins = document.querySelectorAll("input.numbers");
// a tracker to track
var tracker = {};
// loop through all the inputs
for(var i = 0, numIns = ins.length; i < numIns; ++i)
{
// get the value of the input
var inValue = ins[i].value.trim();
// skip if there is no value
if(!inValue) continue;
// if the value is already tracked then let the user know they are a bad person
// and stop
if(tracker[inValue])
{
alert("You are a bad person!");
return;
}
// track the value
tracker[inValue] = true;
}
You could also enhance this to let the user know which inputs have duplicate values:
// get all the inputs that have the class numbers
var ins = document.querySelectorAll("input.numbers");
// a tracker to track
var tracker = {};
// loop through all the inputs
for(var i = 0, numIns = ins.length; i < numIns; ++i)
{
// get the value of the input
var inValue = ins[i].value.trim();
// skip if there is no value
if(!inValue) continue;
// if the value is already tracked then error them
if(tracker[inValue])
{
// mark the current input as error
ins[i].className += " error";
// mark the first found instance as an error
ins[tracker[inValue]].className += " error";
}
// save the index so we can get to it later if a duplicate is found
tracker[inValue] = i;
}
Here's a way of doing it that automatically picks up all the text inputs in your document and validates based on what you're looking for. Would be simple enough to expose the valid value and make this the validation handler (or part of one) that handles a form submission.
<meta charset="UTF-8">
<input id="num1" type="text" value="foobar1">
<input id="num2" type="text" value="foobar2">
<input id="num3" type="text" value="foobar3">
<input id="num4" type="text" value="foobar4">
<input id="num5" type="text" value="foobar5">
<button onClick="checkValues();">Validate</button>
<script>
function checkValues() {
var inputs = document.getElementsByTagName('input');
arrInputs = Array.prototype.slice.call(inputs);
var valid = true;
var valueStore = {};
arrInputs.forEach(function(input) {
if (input.type == 'text') {
var value = input.value.toUpperCase();
if (valueStore[value]) {
valid = false;
} else {
valueStore[value] = true;
}
}
});
if (valid) {
alert('Valid: No matching values');
} else {
alert('Invalid: Matching values found!');
}
}
</script>
With jquery you can iterate directly over the inputs.
<form>
<input type="text" >
<input type="text" >
<input type="text" >
<input type="text" >
<input type="text" >
<input type="text" >
<button>
TEST
</button>
</form>
function checkValues(){
var used = {};
var ok = true;
$('form input[type="text"]').each(function(){
var value = $(this).val();
if(value !== ""){
if(used[value] === true){
ok = false;
return false;
}
used[value] = true;
}
});
return ok;
}
$('button').click(function(event){
event.preventDefault();
if(!checkValues()){
alert("repeated numbers");
};
});
https://jsfiddle.net/8mafLu1c/1/
Presumably the inputs are in a form. You can access all form controls via the form's elements collection. The following will check the value of all controls, not just inputs, but can easily be restricted to certain types.
If you want to include radio buttons and checkboxes, check that they're checked before testing their value.
function noDupeValues(form) {
var values = Object.create(null);
return [].every.call(form.elements, function(control){
if (control.value in values && control.value != '') return false;
else return values[control.value] = true;
});
}
<form id="f0" onsubmit="return noDupeValues(this);">
<input name="inp0">
<input name="inp0">
<input name="inp0">
<button>Submit</button>
</form>
For old browsers like IE 8 you'll need a polyfill for every.
You can simply get all inputs iterate them twice to check if they are equals
var inputs = document.getElementsByTagName('input');
for (i = 0; i < inputs.length; i++) {
for (j = i + 1; j < inputs.length; j++) {
if (inputs[i].value === inputs[j].value) {
console.log('value of input: ' + i + ' equals input: ' + j);
}
}
}
<input value="56" />
<input value="12" />
<input value="54" />
<input value="55" />
<input value="12" />

1 button 2 functions

I've got a conflict issue with a form. The idea is that I need to store the datas in the form field in a table with a local storage in Javascript, and I need to send an email simultaneously with the same button with PHP. When I try it, either the button implement the table, either it send the mail. It depends of the position of the action inside the arrows. Here is my code :
<script>
var Contacts = {
index: window.localStorage.getItem("Contacts:index"),
$table: document.getElementById("contacts-table"),
$form: document.getElementById("contacts-form"),
$button_save: document.getElementById("contacts-op-save"),
$button_discard: document.getElementById("contacts-op-discard"),
init: function() {
// initialize storage index
if (!Contacts.index) {
window.localStorage.setItem("Contacts:index", Contacts.index = 1);
}
// initialize form
Contacts.$form.reset();
Contacts.$button_discard.addEventListener("click", function(event) {
Contacts.$form.reset();
Contacts.$form.id_entry.value = 0;
}, true);
Contacts.$form.addEventListener("submit", function(event) {
var entry = {
id: parseInt(this.id_entry.value),
first_name: this.first_name.value,
last_name: this.last_name.value,
company: this.company.value,
address: this.address.value,
city: this.city.value,
zip: this.zip.value,
state: this.state.value,
country: this.country.value,
phone: this.phone.value,
email: this.email.value,
nature_of_contact: this.nature_of_contact.value,
};
if (entry.id == 0) { // add
Contacts.storeAdd(entry);
Contacts.tableAdd(entry);
}
else { // edit
Contacts.storeEdit(entry);
Contacts.tableEdit(entry);
}
this.reset();
this.id_entry.value = 0;
event.preventDefault();
}, true);
// initialize table
if (window.localStorage.length - 1) {
var contacts_list = [], i, key;
for (i = 0; i < window.localStorage.length; i++) {
key = window.localStorage.key(i);
if (/Contacts:\d+/.test(key)) {
contacts_list.push(JSON.parse(window.localStorage.getItem(key)));
}
}
if (contacts_list.length) {
contacts_list
.sort(function(a, b) {
return a.id < b.id ? -1 : (a.id > b.id ? 1 : 0);
})
.forEach(Contacts.tableAdd);
}
}
Contacts.$table.addEventListener("click", function(event) {
var op = event.target.getAttribute("data-op");
if (/edit|remove/.test(op)) {
var entry = JSON.parse(window.localStorage.getItem("Contacts:"+ event.target.getAttribute("data-id")));
if (op == "edit") {
Contacts.$form.first_name.value = entry.first_name;
Contacts.$form.last_name.value = entry.last_name;
Contacts.$form.company.value = entry.company;
Contacts.$form.address.value = entry.address;
Contacts.$form.city.value = entry.city;
Contacts.$form.zip.value = entry.zip;
Contacts.$form.state.value = entry.state;
Contacts.$form.country.value = entry.country;
Contacts.$form.phone.value = entry.phone;
Contacts.$form.email.value = entry.email;
Contacts.$form.nature_of_contact.value = entry.nature_of_contact;
Contacts.$form.id_entry.value = entry.id;
}
else if (op == "remove") {
if (confirm('Are you sure you want to remove "'+ entry.first_name +' '+ entry.last_name +'" from your contacts?')) {
Contacts.storeRemove(entry);
Contacts.tableRemove(entry);
}
}
event.preventDefault();
}
}, true);
},
storeAdd: function(entry) {
entry.id = Contacts.index;
window.localStorage.setItem("Contacts:index", ++Contacts.index);
window.localStorage.setItem("Contacts:"+ entry.id, JSON.stringify(entry));
},
storeEdit: function(entry) {
window.localStorage.setItem("Contacts:"+ entry.id, JSON.stringify(entry));
},
storeRemove: function(entry) {
window.localStorage.removeItem("Contacts:"+ entry.id);
},
tableAdd: function(entry) {
var $tr = document.createElement("tr"), $td, key;
for (key in entry) {
if (entry.hasOwnProperty(key)) {
$td = document.createElement("td");
$td.appendChild(document.createTextNode(entry[key]));
$tr.appendChild($td);
}
}
$td = document.createElement("td");
$td.innerHTML = '<a data-op="edit" data-id="'+ entry.id +'">Edit</a> | <a data-op="remove" data-id="'+ entry.id +'">Remove</a>';
$tr.appendChild($td);
$tr.setAttribute("id", "entry-"+ entry.id);
Contacts.$table.appendChild($tr);
},
tableEdit: function(entry) {
var $tr = document.getElementById("entry-"+ entry.id), $td, key;
$tr.innerHTML = "";
for (key in entry) {
if (entry.hasOwnProperty(key)) {
$td = document.createElement("td");
$td.appendChild(document.createTextNode(entry[key]));
$tr.appendChild($td);
}
}
$td = document.createElement("td");
$td.innerHTML = '<a data-op="edit" data-id="'+ entry.id +'">Edit</a> | <a data-op="remove" data-id="'+ entry.id +'">Remove</a>';
$tr.appendChild($td);
},
tableRemove: function(entry) {
Contacts.$table.removeChild(document.getElementById("entry-"+ entry.id));
}
};
Contacts.init();
</script>
<form action="mailer.php" method="post" class="onerow">
<label class="col6">First name:
<input type="text" name="first_name" />
</label>
<label class="col6">Last name:
<input type="text" name="last_name" />
</label>
<label class="col6">Company:
<input type="text" name="company" />
</label>
<label class="col6">Address:
<input type="text" name="address" />
</label>
<label class="col6">City:
<input type="text" name="city" />
</label>
<label class="col6">Postal/zip code:
<input type="text" name="zip" />
</label>
<label class="col6">State/province:
<input type="text" name="state" />
</label>
<label class="col6">Country:
<input type="text" name="country" />
</label>
<label class="col6">Phone number:
<input type="text" name="phone" />
</label>
<label class="col6">Email:
<input type="text" name="email" />
</label>
<label class="col12">Why are you looking for our solutions ?
<SELECT name="nature_of_contact" size="1">
<OPTION>I'm a distributor and I want to sell your products in my country.
<OPTION>I'm a beautician I want to buy a product.
<OPTION>I'm a doctor.
<OPTION>I'm a distributor.
</SELECT>
</label>
<div class="col12">
<input type="button" id="contacts-op-discard" value="Discard" />
<input type="submit" id="contacts-op-save" value="Save" />
<input type="hidden" name="id_entry" value="0" />
</div>
</form>
</div>
<div></div>
<div id="tablecontrol" class="col12">
<h1>Contacts</h1>
<table id="contacts-table">
<tr id="contacts-head">
<th>ID</th>
<th>First name</th>
<th>Last name</th>
<th>Company</th>
<th>Address</th>
<th>City</th>
<th>Postal/Zip</th>
<th>State/province</th>
<th>Country</th>
<th>Phone number</th>
<th>Email</th>
<th>Kind of prospect</th>
<th>Actions</th>
</tr>
</table>
</div>
</div>
See JSFIDDLE
One way would be:
Change the submit button from type 'submit' to 'button' and add the event onClick()to it.
Create a function -let's say readFromdata()- that reads the values from your form. Store the data into a container.
Create a function -let's say sendFromdata()- that sends the data to your php script. Hint: Ajax would be your friend. Configure your Ajax so, that the data will be send asyncrosly.
Create a function -let's say printFOverview()- that extends your html table, for the displaying the result.
Call sendFromdata() and printFOverview() within the function readFromdata() and pass the data container to these methods.
Add the call readFromdata() to the attribute onClick().
You could do the following:
Add an event.preventDefault() to your handler
Then store things in localStorage
If things are stored submit the form with Contacts.$form.submit();
EDIT
Change the event handler from submit to click and remove it from the form to add it to the Contacts.$button_save button and add a preventDefault() just after.
As you changed the event handler from the form to the button you need to change the form values from this to Contacts.$form because this was in the scope of the form which is not the case anymore.
Contacts.$button_save.addEventListener("click", function(event) {
event.preventDefault();
var entry = {
id: parseInt(Contacts.$form.id_entry.value),
first_name: Contacts.$form.first_name.value,
last_name: Contacts.$form.last_name.value,
// and so on
Remove the input type="submit" and create a normal button instead:
<button id="contacts-op-save">Save</button>
Then you could submit the form after storing in storeAdd / storeEdit functions as said with Contacts.$form.submit();.
storeAdd: function(entry) {
entry.id = Contacts.index;
window.localStorage.setItem("Contacts:index", ++Contacts.index);
window.localStorage.setItem("Contacts:"+ entry.id, JSON.stringify(entry));
Contacts.$form.submit();
},
storeEdit: function(entry) {
window.localStorage.setItem("Contacts:"+ entry.id, JSON.stringify(entry));
Contacts.$form.submit();
},
storeRemove: function(entry) {
window.localStorage.removeItem("Contacts:"+ entry.id);
// eventually here too?
Contacts.$form.submit();
},
Also you call the form element by its id , but the form has no id assigned.
$form: document.getElementById("contacts-form")
So give your form that ID:
<form id="contacts-form" action="mailer.php" method="post" class="onerow">

Categories

Resources