Using form values javascript - javascript

I'm trying to access form data through a Javascript function when an input is 'changed'.
Currently I use something like this:
<form>
<input type="radio" name="type" name="myValue" onchange="myFunction(this.form)>
</form>
<script>
function myFunction(form) {
var value = form.type.value;
}
</script>
And it works, however instead of writing
var value = form.type.value;
I need to write something like this
var myArray = ["type"];
var value = form.myArray[0].value;
Which is not working. Is this due to how values in arrays are handled?
I have it here on JSFiddle if that is useful.
Thanks

Try
var value = form[myArray[0]].value;
form.myArray[0] is first getting the member myArray from form, and then trying to get the first item in that. Equal to (form.myArray)[0]
form[myArray[0]] explicitly says get the member from form which is of the name of the value inside myArray[0]

You can access properties of object using [] like this:
var value = form["type"].value;
// equivalent to:
var value = form.type.value
In your case this should work:
var myArray = ["type"];
var value = form[myArray[0]].value;

'myArray' is declared as a local variable but it is NOT form's property.
So form.myArray will fail.

Related

jQuery detect input change

I'm working on a feature where the user needs to be informed that there are unsaved changes in a form in case if they decide to navigate away from the page.
I am almost done but there's a tiny problem-
I am setting a boolean dirty on input change event.
The .change() event will detect any kind of change, as in it doesn't keep track of changes. For example, if an input field has the original value hello, which is modified to bye and back to hello, it will still set the dirty boolean.
Is there any way where I can take a backup of the form with initial values and then compare it with itself at every change event?
You need a way to serialize the form data into a JSON object, and then you could either compare the JSON object by iterating the properties or by comparing the JSON.stringify values.
I have slightly modified the method of objectifying the form data from here in order to do this.
var form = document.getElementById("myForm");
var originalFormData = objectifyForm(form);
var originalFormDataString = JSON.stringify(originalFormData);
setInterval(function() {
var formData = objectifyForm(form);
var formDataString = JSON.stringify(formData);
console.log("Form is dirty: " + (formDataString != originalFormDataString));
},1000);
function objectifyForm(formArray) {//serialize data function
var returnArray = {};
for (var i = 0; i < formArray.length; i++){
returnArray[formArray[i]['id']] = formArray[i]['value'];
}
return returnArray;
}
<form id="myForm">
<input id="myInput" value="test" type="text" />
</form>
You can do something like this. Remember this solution is just a sample. You have multiple input element, than use array/object to save there defaultValue.
var defaultValue = document.getElementById("myText").defaultValue;//Get the default value
var handleChange = function (){
let value = document.getElementById("myText").value;//get the current value
if(defaultValue===value){
console.log("dirty false")
}else {
console.log("Dirty True")
}
}
<input type="text" id="myText" value="abc" onkeyup="handleChange()">
I think you can create a javascript empty initial_values = {} object. initialised it with the default values in the form of key:value pairs. and if dirty boolean is set, it can be used to compare later on.

Capturing variable names from a select

In the back end I have written some code that reads through a file and outputs to a list of JavaScript arrays for example, the page will see:
<script>
var peanuts = ["1","s","g","3","n"];
var cashewNuts = ["d","a","f","d","n"];
var PecanNuts = ["6","m","3","x","m"];
var BrazilNuts = ["j","n","7","v","s"];
var goingNuts = ["a","e","7","m","y"];
</script>
I then want to use an array based on the value of a somewhere else in that page.
So for example:
if($('select').val()===0){
alert(firstArray[1]);
}
My issue is that the variable names are decided on what is contained in the read file, I can't know this information. Is there a way to say for example
//collect the value from the select and assign it to a var
var varN = $('select').val();
//then collect another variable that has the variable name that
//equals the value of the 'varN'
I know this seems horrendous but unfortunately based on what I need to do, it is what I need to do :(
Yes. If for example your vars are in the global scope, you can do
var val = window[varN][0]; to get peanuts:1
If you do
var nuts = {
peanuts : ["1","s","g","3","n"],
cashewNuts : ["d","a","f","d","n"],
PecanNuts : ["6","m","3","x","m"],
BrazilNuts : ["j","n","7","v","s"],
goingNuts : ["a","e","7","m","y"]
}
then you can use
var val = nuts[varN][0];
If the variables are declared directly in <script>, you can use window[varN].

Get form elements and store into an array using javascript

I am trying to get the input elements in a form using JavaScript. Then I am trying to organize it by putting it into an array by its name attribute. Can anyone please help?
function getFields(formName, attr){
var form=document.getElementById(formName);
var fields=form.getElementsByTagName('input');
var fieldCount=fields.length-1;
var fieldNames=[];
for(var a in fieldCount){
fieldNames[a]=fields[a].getAttribute(attr)
}
return fieldNames[1];
}
It's already in an associated array via the DOM object:
var form = document.getElementById("myForm");
form.elements['myInputName'] //Returns <input name="myInputName">
form.elements['myInputName'].value //Returns the value

Trouble with getting access to an object's property

I'm having a trouble with getting access to an object's property.
Isn't it possible to get access to an object's property like this?
key["heading"]
key in the code above is a variable.
This code below is the code I'm working on right now.
alertHeading.on('blur', function(){
var inputtedVal = $(this).val();
var key = alertMode.val();
chrome.runtime.getBackgroundPage(function(backgroundPage) {
var background = backgroundPage.background;
//(1)This works fine.
background.setStorage(key, {heading:inputtedVal});
console.log(background.getStorage(key));// Object {heading: "aaa"}
//(2)This doesn't work.
var alertObject = background.getStorage(key["heading"]);
console.log(alertObject);// null. I'm expecting to get "aaa".
});
})
I think I'm making a very simple mistake which comes from my lack of javascript knowledge.
Please help me out to solve this problem.
Your key isn't an object, it's a string. It is the return from background.getStorage(key) that is an object, so you can do this:
var alertObject = background.getStorage(key)["heading"]; // note () and [] placement
// OR, in two steps:
var alertObject = background.getStorage(key);
var heading = alertObject["heading"];
EDIT:
"I haven't understood why it's not an object but a string yet"
Your key variable is set to the return from jQuery's .val() method:
var key = alertMode.val();
...which returns a string that is the value of the form element that it is called on. Add in a console.log(key) and you'll see.

Javascript Form: Only Changed Fields

I have a php-site with a form on which i output preselected values via php. On form submit I want to check which values have changed and just submit these via javascript.
These are the preselected values I passed over from php. It's important that I keep the associative array structure.
var pbData = jQuery.parseJSON("{
"GameMode":"DEATHMATCH",
"Current Map":"VEGAS JUNKYARD",
"Current Missions":["VEGAS JUNKYARD","VILLA","PRESIDIO","KILL HOUSE","MURDERTOWN","CQB TRAINING","STREETS","THREE KINGDOMS CASINO","IMPORT\/EXPORT;"],
"RoundDuration":"3 minutes"}");
I marked the error in the code.
<script>
function displayVars(){
var form = document.getElementById('settings');
var elems = form.elements;
var txt = "";
for (var index = 0; index < elems.length; index++){
var selIndex = elems[index].selectedIndex;
if (typeof selIndex !== "undefined"){
//the Index Name in the json-object and the name of the form-field are the same
var idxName = elems[index].name;
//HERE is the problem. I want to access the subobject via a variablename, so i can iterate through it, but that doesnt work.
console.log ("pbData default = "+pbData.idxName); //always undefined
if (elems[index].value !== pbData.idx_name){
//building a POST-Url
txt = txt + elems[index].name + "=" + elems[index].options[selIndex].value+"&";
}
}
}
console.log (txt);
return false;
}
</script>
I know that I could do this differently, also with jQuery. In my case as I have the preselected values as a php-variable in any case, i think it's easier like this.
I would really like to know how I can iterate through the subobjects via a variable that contains the object names.
This is due to how you'e trying to access the property of the (JSON) object. Consider
var o1 = {idxName: true},
o2 = {foo : 'bar'},
idxName = 'foo';
o1.idxName; // true
o2.idxName; // undefined
o2[idxName]; // 'bar'
You need to access the property via pbData[idxName].
Additionally, you're not escaping quotes in your JSON string, and line breaks need to be escaped as follows
var pbData = jQuery.parseJSON("{\
\"GameMode\":\"DEATHMATCH\",\
\"Current Map\":\"VEGAS JUNKYARD\",\
\"Current Missions\":[\"VEGAS JUNKYARD\",\"VILLA\",\"PRESIDIO\",\"KILL HOUSE\",\"MURDERTOWN\",\"CQB TRAINING\",\"STREETS\",\"THREE KINGDOMS CASINO\",\"IMPORT\/EXPORT;\"],\
\"RoundDuration\":\"3 minutes\"}");
In Javascript you could keep an object or array with initial values and only post those values that are changed.
But in fact, I would do something similar, but in PHP. You can keep the original values in the session and compare the posted values to those initial values to see what has changed. That way, you won't depend on Javascript. Not only may Javascript be disabled, but also, a fast user may theoretically post the form before the Javascript has run. To move this check to PHP eliminates that risk.

Categories

Resources