adding input value in multidimensional array? - javascript

I am facing problem in java-script problem as
I have to collect all subrole from screen whenever user focus out from input field.this is my code
var subrole_id = [];
$("ul :input[class^='sub']").live('focusout', function() {
var get_id = $(this).attr('class').split("_");
var ids = get_id[2];
var ids_index = get_id[3];
subrole_id[ids][ids_index] = this.value;
});
but this is giving error
TypeError: subrole_id[ids] is undefined
subrole_id[ids][ids_index] = this.value;
Actually I want to collect value of subrole input field and add them in array with index ids one by one and before adding that value in array I have to check whether that present value is present in array or not if yes then do not add and give error.
Please suggest.

There isn't a true multidimensional array in javascript, just an array of array, so you have to create the subArray:
subrole_id[ids]=subrole_id[ids]||[];
subrole_id[ids][ids_index] = this.value;

Related

How to generate one object key with an array of stored values from multiple on click events using localstorage and Jquery

I'm new to coding, and I need to display past search values from an input field using localstorage. The only way I can think of is by using one object key with an array of stored values from an on click event. Problem is, I can only get one position to appear as a value, with each value generated replacing the last. I've tried for loops and can't seem to get it to work. This is the code I have so far:
$('.search-city').on('click', function(e){
e.preventDefault();
var textArr = [];
var text = $(".form-control").val();
textArr.push(text);
localStorage.setItem("value1", textArr);
});
$('.search-city').on('click', function(e){
e.preventDefault();
var search = localStorage.getItem("value1")
This would work:
$('.search-city').on('click', function(e){
e.preventDefault();
// get the value from local storage
var localValue = localStorage.getItem('value1');
// if we had a value, parse it back to an array, if we dont, create an empty array
var textArr = localValue ? JSON.parse(localValue) : [];
// get the text from the search input, dont use "form-control"
// you're likely to have several of those on the page
// give the element a custom class like "search-input" and use that (id would be even better)
var text = $('.search-input').val();
// add the text to the array
text = trim(text);
if (text) {
textArr.push(text);
}
// enforce a size limit here by removing the 0 index item if the count has grown too large
var maxAllowed = 10;
while (textArr.length > maxAllowed) {
textArr.shift();
}
// localstorage can only hold simple strings so we'll JSON stringify our object and store that
localValue = JSON.stringify(textArr);
localStorage.setItem("value1", localValue);
});

Adding up values to an associative array element - Javascript

I'm having some trouble adding values to existing values in arrays.
The code:
It all comes from a big string set as the value of an hidden element in the parent page.
var parent = $(window.opener.document).contents();
var data = parent.find("#hdn").val();
var sp1 = data.split("=x=");
$('#timerange').text(sp1[0]); // this is where I put the first part of the string
var sp2 = sp1[1].split("|"); // the remains of it will be used to fill arr1
var arr1 = {};
$.each(sp2, function(i, value){
if(value != ''){
var sp3 = value.split("<->");
arr1[sp3[0]] += parseFloat(sp3[2]); // this is where the problem goes. i can't sum the new value with the existing value of this element, it outputs "NaN" no matter what
$('#tableprnt tbody').append('<tr><td>'+sp3[0]+'</td><td>'+sp3[1]+'</td><td>'+sp3[2]+'</td><td>'+sp3[3]+'</td><td>'+sp3[4]+'</td><td>'+sp3[5]+'</td><td>'+sp3[6]+'</td><td>'+sp3[7]+'</td><td>'+sp3[8]+'</td><td>'+sp3[9]+'</td></tr>');
}
})
console.log(arr1);
The point of this is to append this informations to a table so I can print it.
data has the string that comes from the parent page which is something like this: 2017-12-28 - 2017-12-28=x=Company name<->big string here<->123.2<->2017-12-28<->2017-12-28<->2017-12-28<->another string here<->string<->string<->string|Company name<->big string here<->123.2<->2017-12-28<->2017-12-28<->2017-12-28<->another string here<->string<->string<->string| and it goes on.
Each element of arr1 (sp3[0] [string]) should have the sum of it's respective value (sp3[2] [float]), but all i can get is NaN for each one of these even though I'm using parseFloat().
Console displays *"{element 1: NaN, element 2: NaN}"*.
What am I missing?
Hope you can help me.
You are getting NaN because that's what should be returned as you are trying to increment the value for the key company_name
arr1[sp3[0]] += parseFloat(sp3[2]);
This would fail OR say will store NaN on the very first iteration in the value because the actual value against the key/property "Company Name" would be undefined and calling parseFloat() on undefined will return you NaN you need to check if the object has the property defined already then increment/add the value to existing value and if it is the first time then assign the value. change the above line to the following
arr1[sp3[0]] = (arr1.hasOwnProperty(sp3[0])) ? (arr1[sp3[0]] + parseFloat(sp3[2])) : (parseFloat(sp3[2]));

Getting value of selected checkbox with jquery from checkboxes without id's

I have a number of checkboxes that are generated from a JavaScript API call from a database. I need to be able to pass the values of the checkboxes which are then selected by the user, and sent to the processing page. The issue is that the checkboxes don't have ID's associated with them(or this wouldn't be a problem) They all have the same name, but no ID's.
What is the best way to find which check boxes are selected, and pass their values to the following page?
One way I started was with an array:
var options = ["option1","option2","option3"];
var option 1 = [0];
var option 2 = [1];
var option 3 = [2];
On the processing page, using:
var option1 = getFromRequest('option1') || '';
var option2 = getFromRequest('option2') || '';
var option3 = getFromRequest('option3') || '';
Is there a better way of doing this?
I've changed the implementation to the following:
var values = []
$("input:checkbox.subIndustry").each(function(){
values.push(this.value);
});
passing the values to the success page with
window.location.href = REGISTER_SUCCESS +'&values='values.join(",")
which should then get the value with
var variablname = getFromRequest('values') || "";
This is returning Undefined. Any help?
An easy way to select them would be something like $("input[type=checkbox]:checked")
However, if you wanted to keep up with them as they are checked, even if they are added after you load, you could create a variable, then asign a delegation to the "change" state of each input that is a checkbox and update this variable on each change.
It's as simple as:
var checked, checkedValues = new Array();
$(function() {
$(document).on("change", "input[type=checkbox]", function(e) {
checked = $("input[type=checkbox]:checked");
// if you wanted to get an array of values of the checked elements
checkedValues = checked.map(function(i) { return $(this).val() }).get();
// make a string of the values as simple as joining an array!
var str = checkedValues.join(); // would return something like: value1,value2,ext...
});
})
Working Example
Since all your checkboxes have the same name, you can retrieve the checked ones using a variation of:
var checked = $('input[name=ckboxname]:checked');
see: :checked selector for more information
you can simply get the values of checked checkboxes by using
$('input[name=checkboxname]:checked').val();
this will give you the value of checkbox which is checked and for all values simply use
each function of jquery.
Turns out, the answer was to utilize indexOf in the underscore.js library. The solution had to be applied in the API being used to send data.
(_.indexOf(values, '9') != -1 ? 1 : '0'),

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.

Get inputs value and separated by "|"

I have inputs and I need to get values and separated by "|" symbol.
My input:
Output what I need:
00:00|00:00|00:00
My code is :
(and it's not working)
var timesArray = $('table').find('input');
var times = timesArray.val();
$('.alltimes').val(times);
Given that .val returns the value of each element (whatever input type it is in your screenshot), then you can use .map: http://jsfiddle.net/RrCYD/.
var values = $("input").map(function() {
return $(this).val(); // map each element to its value
}).get().join("|"); // get real array and join
See comments in code:
// Create an array to store the input values
var inputValues = [];
// Iterate over input's and store their value in the array
$('table').find('input').each(function () {
inputValues.push(this.value);
});
// Create pipe=delimited string from array of values
var delimitedInputValues = inputValues.join("|");
Additional Information
MDN - array.join
jQuery - .each()

Categories

Resources