AngularJS - Save as multiple rows - data coming from ng-repeat - javascript

Hello new to AngularJS and I am trying to wrap my head around something...
Basically I have a form that can accept 1 to many "Guests" for an event. Using ng-repeat I display the fields like so:
<div ng-repeat="guest in guests">
<input type="text" ng-model="guests[$index].first_name" />
<input type="text" ng-model="guests[$index].last_name" />
<select ng-model="guests[$index].meal" ng-options="meal.id as meal.name for meal in meals"></select>
<select ng-model="guests[$index].rsvp">
<option value="0">No</option>
<option value="1">Yes</option>
</select>
</div>
<div class="controls"><button ng-click="submit()" class="btn btn-success">Save</button></div>
And in the controller:
//DETERMINE TOTAL IN PARTY
var totalInParty = 2;
$scope.meals = RSVPRes.Meals.query();
//EDIT
if ($scope.rsvpId) {
}
//NEW RSVP SUBMISSION
else {
$scope.rsvp = new RSVPRes.RSVP();
//INITIALIZE EMPTY GUESTS
$scope.guests = [];
for (var i = 0; i < totalInParty; i++) {
$scope.guests[i] = {
first_name: '',
last_name: '',
meal: 1,
rsvp: 0
};
}
}
And my Resource
.factory( 'RSVPRes', function ( $resource ) {
return {
RSVP: $resource("../reservations/:id.json", {id:'#id'}, {'update': {method:'PUT'}, 'remove': {method: 'DELETE', headers: {'Content-Type': 'application/json'}}}),
Meals: $resource('../meals.json')
};
})
Now all this works really well - I am just having trouble saving the data. I would like to save each Guest (First Name, Last Name, Meal & RSVP) as it's own row.
If I try this:
$scope.submit = function() {
for(var i = 0; i < $scope.guests.length; i++){
$scope.rsvp.first_name = $scope.guests[i].first_name;
$scope.rsvp.last_name = $scope.guests[i].last_name;
$scope.rsvp.meal_id = $scope.guests[i].meal;
$scope.rsvp.rsvp = $scope.guests[i].rsvp;
$scope.rsvp.$save();
}
$state.transitionTo('rsvps');
};
It creates two rows (total_in_party set to 2) but it's always the 2nd persons data.
Feel like I am close, I looked a quite a few ng-repeat examples, but couldn't find one that deals with my specific case!
Any help is appreciated.
SOLVED
I totally duffed my thinking about the Resource, creating a new RSVP object now everytime in the loop.
$scope.submit = function() {
for(var i = 0; i < $scope.guests.length; i++){
$scope.rsvp = new RSVPRes.RSVP();
$scope.rsvp.first_name = $scope.guests[i].first_name;
$scope.rsvp.last_name = $scope.guests[i].last_name;
$scope.rsvp.meal_id = $scope.guests[i].meal;
$scope.rsvp.rsvp = $scope.guests[i].rsvp;
$scope.rsvp.$save();
}
$state.transitionTo('rsvps');
};

Move $scope.rsvp.$save(); outside the loop

Related

Update the multiple value and display using AngularJS and laravel

[{"user_id":78936,"social_id":null,"type":2,"name":"Get Raj","first_name":"Get","last_name":"Raj","email":"test1#yopmail.com"},
{"user_id":78937,"social_id":null,"type":2,"name":"James thomas","first_name":"James","last_name":"thomas","email":"jamesthoms#yopmail.com"}]
<div ng-repeat="user in profiles">
<div class="col-sm-5 col-ie-5">
<input
type="text"
name="entry_{{user.user_id}}"
ng-model="update.entry"
ng-change="save(user, update)"
>
</div>
<div class="col-sm-5 col-ie-5">
<input
type="text"
name="info_{{user.user_id}}"
ng-model="update.info"
ng-change="save(user, update)"
>
</div>
<div class="col-sm-5 col-ie-5">
<input
type="text"
name="textual_{{user.user_id}}"
ng-model="update.textual"
ng-change="save(user, update)"
>
</div>
</div>
function makeOrderItemUrl(user_id, order_id){
return 'v1/update/' + user_id + '/order_id/' + order_id;
}
$scope.save = function (person, update) {
var person = person;
var order = null,
matchCount = 0;
for (var i = 0; i < $scope.order.items.length; i++) {
if ($scope.order.items[i].user_id == person.user_id) {
order = $scope.order.items[i];
matchCount++;
}
}
if(order){
$http.post(makeOrderItemUrl(person.user_id, order.order_id), update)
.success(function(res){
$scope.update = res.data;
}).error(function () {
notify.message('There was an issue saving your changes, please try again later.');
});
}
};
Since we have two users so we will get twice input fields i.e ng-model="update.entry" two times then whenever I type in the first textbox it get reflected the same value in the second textbox as well because of the same model they are using how can I set different models and value to be saved into the database and display respectively.
Laravel
$orderItem = OrderItem::firstOrNew([
'user_id' => $user_id,
'order_id' => $order_id
]);
if($orderItem->exists){
$orderItem->entry = Input::get('entry');
$orderItem->save();
}
//This is working fine but it's hard to display.
Make update a deeper object where the user id's are used as first level keys
<input
type="text"
name="entry_{{user.user_id}}"
ng-model="update[user.user_id].entry"
ng-change="save(user, update[user.user_id])"
>
Then $scope.update would look like:
{
id1: {
textual: '...',
entry: '...',
info: '...'
},
id2: {
textual: '...',
entry: '...',
info: '...'
}
}

Restoring default drop down value with angularjs

Although I have got this working, the way it works seems improper. I have a drop down list (DDL) that displays a list of teams. The top and default entry is "Select Team... ". Although my DDL is tied to a model, "Select Team..." shouldn't be part of it since "Select Team..." has no meaning to the domain model.
When a user clicks "Add New" the form clears and all DDLs should revert to their default values.
Here are the related controller functions:
scope.addUser = function() {
resetToNewUser();
$scope.profileVisible = true;
$scope.oneAtATime = true;
$scope.accordionStatus = { isFirstOpen: true, isFirstDisabled: false };
}
function resetToNewUser() {
$scope.selectedUser.NtId = "";
$scope.selectedUser.UserId = -1;
$scope.selectedUser.IsActive = true;
$scope.selectedUser.FirstName = "";
$scope.selectedUser.LastName = "";
$scope.selectedUser.JobTitle = "";
$scope.selectedUser.Email = "";
$scope.selectedUser.SecondaryEmail = "";
$scope.selectedUser.PhoneNumber = "";
for(var i = 0; i < $scope.roleList.length; i++) {
if($scope.roleList[i].RoleSystemName.trim() === "BLU") {
$scope.selectedUser.Role = $scope.roleList[i];
}
}
$scope.selectedUser.SupervisorId = null;
//HACK BELOW//
document.getElementById('selTeam').selectedIndex = 0; // <-- This works, but feels like a hack.
$scope.selectedUser.IsRep = false;
for(var i = 0; i < $scope.signingAuthorityList.length; i++) {
if($scope.signingAuthorityList[i].SigningAuthoritySystemName === "SME") {
$scope.selectedUser.SigningAuthority = $scope.signingAuthorityList[i];
}
}
$scope.selectedUser.IsOutOfOfficeEnabled = false;
$scope.selectedUser.OutOfOfficeStartDate = null;
$scope.selectedUser.OutOfOfficeEndDate = null;
$scope.selectedUser.OutOfOfficeAppointedRepId = null;
}
Here's how the DDL is defined in the template:
<div class="form-group">
<label for="" class="control-label col-sm-2 required">Team</label>
<div class="col-sm-10">
<select class="form-control" id="selTeam"
ng-model="selectedUser.Team"
ng-options="team as team.TeamName for team in teamList track by team.TeamId">
<option value="">Select Team...</option>
</select>
</div>
</div>
Is there a better way to do this?
You could always just remove the ability for the user to select your placeholder option, right? Something like this:
<option value="" disabled selected hidden>Select Team...</option>
You html part looks good, but I think on js side you make a lot of logic. What happens if there will be added new options on the server? Better get state of the new user from the backend, customize it with the select and other widgets and keep it before it will be submitted. On pseudo code it will be looks like
$scope.addUser = function() {
//create empty user on the scope
$scope.selectedUser = {};
//get the new user state from the backend
UserService.resetToNewUser($scope.selectedUser);
//setup view options
$scope.accordionStatus = {isFirstOpen: true, isFirstDisabled: false}
};
app.service('UserService', function(){
this.resetToNewUser = function(user){
$http({
method: 'GET',
url: '/default_user/'
}).then(function successCallback(response) {
user = response;
);
};
});

Adding of users to dropdown list doesn't work

Good evening!
There's a problem with adding a user to dropdown list (ui-grid is used).
I need to push input name by id into dd list after the "addNewPerson" button is clicked, if there's no such name in the list, or to call "alert", if there is.
Here's a code, responsible for the dd list creation in html:
<ui-select ng-model="person.selected" theme="select2" style="min-width:300px;">
<ui-select-match placeholder="Select a person in the list or search by name">{{$select.selected.name}}
</ui-select-match>
<ui-select-choices repeat="person in contacts | filter: {name: $select.search} track by $index">
<div ng-bind-html="person.name | highlight: $select.search"></div>
</ui-select-choices>
</ui-select>
Button and input field:
<button type="button" id="addPerson" class="button" ng- click="addNewPerson()">Add New Person</button>
<input id="name" class="form-control" placeholder="Enter your Name">
Array of objects with the "name" field, which needs to be passed into the dd list:
$scope.contacts = [
{name: "Han Solo"},
{name: "ThetaSigma"},
{name: "Ollie Reeder"},
{name: "Amy McDonald"},
{name: "PJ Harvey"},
{name: "Sofie Marceau"},
{name: "Arthur Zimmermann"},
{name: "Michelle Dockery"},
{name: "Xavier Dolan"}
];
And, at last, the notorious function:
$scope.person = {};
$scope.addNewPerson = function () {
var nameInput = document.getElementById("name");
for (var i=0; i <= $scope.contacts.length; i++) {
if ($scope.contacts[i].name == nameInput.value.toLowerCase()) {
alert("Error, the name entered already exists");
}else{
var obj1 = {name: nameInput.value};
$scope.contacts.push(obj1);
}
}
};
I've tried various formations of the function, it either pushes nothing and alerts 10 times, or pushes names correctly, but even already existing ones, or pushes 10 times and alerts 10 times after a single adding.
I'm handicapped. Tried to find similar q/a here, but to no avail.
And sorry for my english, it'snot my native language.
Here's working codepen example.
First Change the html for the input to use scope variable:
<input ng-model="name" class="form-control" placeholder="Enter your Name">
and in the controller:
$scope.name = "";
$scope.addNewPerson = function () {
for (var i=0; i < $scope.contacts.length; i++) {
if ($scope.contacts[i].name.toLowerCase() === $scope.name.toLowerCase()) {
alert("Error, the name entered already exists");
return;
}
}
$scope.contacts.push({name: $scope.name});
};
You ng-model to bind the new user name:
<input id="name" class="form-control" placeholder="Enter your Name" ng-model="new_user_name">
Then in your js, you have to break out of your forloop :
$scope.person = {};
$scope.addNewPerson = function () {
var name = $scope.new_user_name || "";
var match_found = false;
for (var i=0; i <= $scope.contacts.length; i++) {
if ($scope.contacts[i].name == name.toLowerCase()) {
alert("Error, the name entered already exists");
match_found = true;
break;
}
}
if (!match_found) {
var obj1 = {name: name};
$scope.contacts.push(obj1);
}
};
The above answers are fine, I would just like to add the option to use functional programming style as I love to do it and for me it looks cleaner.
View
<input ng-model="name" class="form-control" placeholder="Enter your Name">
Controller
$scope.name = "";
$scope.addNewPerson = function () {
var contactIndex = $scope.contacts.map(function (contact) {
return contact.name.toLowerCase();
}).indexOf($scope.name.toLowerCase());
if (contactIndex === -1)
$scope.contacts.push({name: $scope.name});
else
console.log("Error, the name entered already exists");
}
A few notes:
When working with angular, never access DOM in view controllers, use directives instead
Functional programming style will save you a lot of typing
Using console.log instead of alerting boosts your productivity by approx. 9000%

Conditional drop down menu in javascript, problems with the selector

I have a conditional dropdown menu which works but it depends on where I put it on the page. If I don't put it in a specific position the positions in the menu don't fill at all. The problem is also that I want to add a second conditional dropdown, and that one doesn't work regardless of where I put it. So my question is: do I need to add the script twice on the page to correspond the two forms I have? I actually want both drop downs to fill with the exact same words.
document.forms[0]['List'+i].length = 1;
document.forms[0]['List'+i].selectedIndex = 0;
I'm guessing it's something related with the [0] there. I tried adding an id to the form and then writing the the second script document.forms('myId')[] but that didn't work either. How should I go about doing this?
<script type="text/javascript">
var categories = [];
categories["startList"] = ["Programming","Science","History","Business and Economics","Software","Languages","Do it Yourself","Others"];
categories["Programming"] = ["Java","C++","C.","Python","Html","Php","Mysql","ObjectiveC","Android","Others"];
categories["Science"] = ["Mathematics","Physics","Biology","Chemistry","Medicine","Astronomy","Statistics","Others"];
categories["Others"] = ["All"]
var nLists = 2; // number of lists in the set
function fillSelect(currCat,currList){
var step = Number(currList.name.replace(/\D/g,""));
for (i=step; i<nLists+1; i++) {
document.forms[0]['List'+i].length = 1;
document.forms[0]['List'+i].selectedIndex = 0;
}
var nCat = categories[currCat];
for (each in nCat) {
var nOption = document.createElement('option');
var nData = document.createTextNode(nCat[each]);
nOption.setAttribute('value',nCat[each]);
nOption.appendChild(nData);
currList.appendChild(nOption);
}
}
function getValue( L2, L1) {
$.post( "", { List1: L1, List2: L2 } );
}
function init() {
fillSelect('startList',document.forms[0]['List1'])
}
navigator.appName == "Microsoft Internet Explorer" ? attachEvent('onload', init, false) : addEventListener('load', init, false);
</script>
<form action="" method="post">
<select name='List1' onchange="fillSelect(this.value,this.form['List2'])">
<option selected>Category</option>
</select>
<select name='List2' onchange="getValue(this.value,this.form['List1'].value)">
<option selected >Subcategory</option>
</select>
<input type="Submit">
Fixed it. I just had to add either a selector or 1 there to correspond to my second form.
document.forms[1]['List'+i].length = 1;
document.forms[1]['List'+i].selectedIndex = 0;
}
var nCat = categories[currCat];
for (each in nCat) {
var nOption = document.createElement('option');
var nData = document.createTextNode(nCat[each]);
nOption.setAttribute('value',nCat[each]);
nOption.appendChild(nData);
currList.appendChild(nOption);
}
}
function getValue( L2, L1) {
$.post( "", { List1: L1, List2: L2 } );
}
function init() {
fillSelect('startList',document.forms[1]['List1'])

Generic way to detect if html form is edited

I have a tabbed html form. Upon navigating from one tab to the other, the current tab's data is persisted (on the DB) even if there is no change to the data.
I would like to make the persistence call only if the form is edited. The form can contain any kind of control. Dirtying the form need not be by typing some text but choosing a date in a calendar control would also qualify.
One way to achieve this would be to display the form in read-only mode by default and have an 'Edit' button and if the user clicks the edit button then the call to DB is made (once again, irrespective of whether data is modified. This is a better improvement to what is currently existing).
I would like to know how to write a generic javascript function that would check if any of the controls value has been modified ?
In pure javascript, this would not be an easy task, but jQuery makes it very easy to do:
$("#myform :input").change(function() {
$("#myform").data("changed",true);
});
Then before saving, you can check if it was changed:
if ($("#myform").data("changed")) {
// submit the form
}
In the example above, the form has an id equal to "myform".
If you need this in many forms, you can easily turn it into a plugin:
$.fn.extend({
trackChanges: function() {
$(":input",this).change(function() {
$(this.form).data("changed", true);
});
}
,
isChanged: function() {
return this.data("changed");
}
});
Then you can simply say:
$("#myform").trackChanges();
and check if a form has changed:
if ($("#myform").isChanged()) {
// ...
}
I am not sure if I get your question right, but what about addEventListener? If you don't care too much about IE8 support this should be fine. The following code is working for me:
var form = document.getElementById("myForm");
form.addEventListener("input", function () {
console.log("Form has changed!");
});
In case JQuery is out of the question. A quick search on Google found Javascript implementations of MD5 and SHA1 hash algorithms. If you wanted, you could concatenate all form inputs and hash them, then store that value in memory. When the user is done. Concatenate all the values and hash again. Compare the 2 hashes. If they are the same, the user did not change any form fields. If they are different, something has been edited, and you need to call your persistence code.
Another way to achieve this is serialize the form:
$(function() {
var $form = $('form');
var initialState = $form.serialize();
$form.submit(function (e) {
if (initialState === $form.serialize()) {
console.log('Form is unchanged!');
} else {
console.log('Form has changed!');
}
e.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
Field 1: <input type="text" name="field_1" value="My value 1"> <br>
Field 2: <input type="text" name="field_2" value="My value 2"> <br>
Check: <input type="checkbox" name="field_3" value="1"><br>
<input type="submit">
</form>
Form changes can easily be detected in native JavaScript without jQuery:
function initChangeDetection(form) {
Array.from(form).forEach(el => el.dataset.origValue = el.value);
}
function formHasChanges(form) {
return Array.from(form).some(el => 'origValue' in el.dataset && el.dataset.origValue !== el.value);
}
initChangeDetection() can safely be called multiple times throughout your page's lifecycle: See Test on JSBin
For older browsers that don't support newer arrow/array functions:
function initChangeDetection(form) {
for (var i=0; i<form.length; i++) {
var el = form[i];
el.dataset.origValue = el.value;
}
}
function formHasChanges(form) {
for (var i=0; i<form.length; i++) {
var el = form[i];
if ('origValue' in el.dataset && el.dataset.origValue !== el.value) {
return true;
}
}
return false;
}
Here's how I did it (without using jQuery).
In my case, I wanted one particular form element not to be counted, because it was the element that triggered the check and so will always have changed. The exceptional element is named 'reporting_period' and is hard-coded in the function 'hasFormChanged()'.
To test, make an element call the function "changeReportingPeriod()", which you'll probably want to name something else.
IMPORTANT: You must call setInitialValues() when the values have been set to their original values (typically at page load, but not in my case).
NOTE: I do not claim that this is an elegant solution, in fact I don't believe in elegant JavaScript solutions. My personal emphasis in JavaScript is on readability, not structural elegance (as if that were possible in JavaScript). I do not concern myself with file size at all when writing JavaScript because that's what gzip is for, and trying to write more compact JavaScript code invariably leads to intolerable problems with maintenance. I offer no apologies, express no remorse and refuse to debate it. It's JavaScript. Sorry, I had to make this clear in order to convince myself that I should bother posting. Be happy! :)
var initial_values = new Array();
// Gets all form elements from the entire document.
function getAllFormElements() {
// Return variable.
var all_form_elements = Array();
// The form.
var form_activity_report = document.getElementById('form_activity_report');
// Different types of form elements.
var inputs = form_activity_report.getElementsByTagName('input');
var textareas = form_activity_report.getElementsByTagName('textarea');
var selects = form_activity_report.getElementsByTagName('select');
// We do it this way because we want to return an Array, not a NodeList.
var i;
for (i = 0; i < inputs.length; i++) {
all_form_elements.push(inputs[i]);
}
for (i = 0; i < textareas.length; i++) {
all_form_elements.push(textareas[i]);
}
for (i = 0; i < selects.length; i++) {
all_form_elements.push(selects[i]);
}
return all_form_elements;
}
// Sets the initial values of every form element.
function setInitialFormValues() {
var inputs = getAllFormElements();
for (var i = 0; i < inputs.length; i++) {
initial_values.push(inputs[i].value);
}
}
function hasFormChanged() {
var has_changed = false;
var elements = getAllFormElements();
for (var i = 0; i < elements.length; i++) {
if (elements[i].id != 'reporting_period' && elements[i].value != initial_values[i]) {
has_changed = true;
break;
}
}
return has_changed;
}
function changeReportingPeriod() {
alert(hasFormChanged());
}
Here's a polyfill method demo in native JavaScript that uses the FormData() API to detect created, updated, and deleted form entries. You can check if anything was changed using HTMLFormElement#isChanged and get an object containing the differences from a reset form using HTMLFormElement#changes (assuming they're not masked by an input name):
Object.defineProperties(HTMLFormElement.prototype, {
isChanged: {
configurable: true,
get: function isChanged () {
'use strict'
var thisData = new FormData(this)
var that = this.cloneNode(true)
// avoid masking: https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/reset
HTMLFormElement.prototype.reset.call(that)
var thatData = new FormData(that)
const theseKeys = Array.from(thisData.keys())
const thoseKeys = Array.from(thatData.keys())
if (theseKeys.length !== thoseKeys.length) {
return true
}
const allKeys = new Set(theseKeys.concat(thoseKeys))
function unequal (value, index) {
return value !== this[index]
}
for (const key of theseKeys) {
const theseValues = thisData.getAll(key)
const thoseValues = thatData.getAll(key)
if (theseValues.length !== thoseValues.length) {
return true
}
if (theseValues.some(unequal, thoseValues)) {
return true
}
}
return false
}
},
changes: {
configurable: true,
get: function changes () {
'use strict'
var thisData = new FormData(this)
var that = this.cloneNode(true)
// avoid masking: https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/reset
HTMLFormElement.prototype.reset.call(that)
var thatData = new FormData(that)
const theseKeys = Array.from(thisData.keys())
const thoseKeys = Array.from(thatData.keys())
const created = new FormData()
const deleted = new FormData()
const updated = new FormData()
const allKeys = new Set(theseKeys.concat(thoseKeys))
function unequal (value, index) {
return value !== this[index]
}
for (const key of allKeys) {
const theseValues = thisData.getAll(key)
const thoseValues = thatData.getAll(key)
const createdValues = theseValues.slice(thoseValues.length)
const deletedValues = thoseValues.slice(theseValues.length)
const minLength = Math.min(theseValues.length, thoseValues.length)
const updatedValues = theseValues.slice(0, minLength).filter(unequal, thoseValues)
function append (value) {
this.append(key, value)
}
createdValues.forEach(append, created)
deletedValues.forEach(append, deleted)
updatedValues.forEach(append, updated)
}
return {
created: Array.from(created),
deleted: Array.from(deleted),
updated: Array.from(updated)
}
}
}
})
document.querySelector('[value="Check"]').addEventListener('click', function () {
if (this.form.isChanged) {
console.log(this.form.changes)
} else {
console.log('unchanged')
}
})
<form>
<div>
<label for="name">Text Input:</label>
<input type="text" name="name" id="name" value="" tabindex="1" />
</div>
<div>
<h4>Radio Button Choice</h4>
<label for="radio-choice-1">Choice 1</label>
<input type="radio" name="radio-choice-1" id="radio-choice-1" tabindex="2" value="choice-1" />
<label for="radio-choice-2">Choice 2</label>
<input type="radio" name="radio-choice-2" id="radio-choice-2" tabindex="3" value="choice-2" />
</div>
<div>
<label for="select-choice">Select Dropdown Choice:</label>
<select name="select-choice" id="select-choice">
<option value="Choice 1">Choice 1</option>
<option value="Choice 2">Choice 2</option>
<option value="Choice 3">Choice 3</option>
</select>
</div>
<div>
<label for="textarea">Textarea:</label>
<textarea cols="40" rows="8" name="textarea" id="textarea"></textarea>
</div>
<div>
<label for="checkbox">Checkbox:</label>
<input type="checkbox" name="checkbox" id="checkbox" />
</div>
<div>
<input type="button" value="Check" />
</div>
</form>
I really like the contribution from Teekin above, and have implemented it.
However, I have expanded it to allow for checkboxes too using code like this:
// Gets all form elements from the entire document.
function getAllFormElements() {
// Return variable.
var all_form_elements = Array();
// The form.
var Form = document.getElementById('frmCompDetls');
// Different types of form elements.
var inputs = Form.getElementsByTagName('input');
var textareas = Form.getElementsByTagName('textarea');
var selects = Form.getElementsByTagName('select');
var checkboxes = Form.getElementsByTagName('CheckBox');
// We do it this way because we want to return an Array, not a NodeList.
var i;
for (i = 0; i < inputs.length; i++) {
all_form_elements.push(inputs[i]);
}
for (i = 0; i < textareas.length; i++) {
all_form_elements.push(textareas[i]);
}
for (i = 0; i < selects.length; i++) {
all_form_elements.push(selects[i]);
}
for (i = 0; i < checkboxes.length; i++) {
all_form_elements.push(checkboxes[i]);
}
return all_form_elements;
}
// Sets the initial values of every form element.
function setInitialFormValues() {
var inputs = getAllFormElements();
for (var i = 0; i < inputs.length; i++) {
if(inputs[i].type != "checkbox"){
initial_values.push(inputs[i].value);
}
else
{
initial_values.push(inputs[i].checked);
}
}
}
function hasFormChanged() {
var has_changed = false;
var elements = getAllFormElements();
var diffstring = ""
for (var i = 0; i < elements.length; i++) {
if (elements[i].type != "checkbox"){
if (elements[i].value != initial_values[i]) {
has_changed = true;
//diffstring = diffstring + elements[i].value+" Was "+initial_values[i]+"\n";
break;
}
}
else
{
if (elements[i].checked != initial_values[i]) {
has_changed = true;
//diffstring = diffstring + elements[i].value+" Was "+initial_values[i]+"\n";
break;
}
}
}
//alert(diffstring);
return has_changed;
}
The diffstring is just a debugging tool

Categories