i'm new to javascript and jquery and was wondering if someone could let me in on why this isn't working correctly.
i have a drop-down box that a user selects a value from, then "Processes." When processed the value of the drop-down as well as a textbox is stored in an array. I want the user to be able to then basically store the same drop-down selection and textbox data in the array again but now in a new value pair.
First store would be
TestArray[0][0] = "Textbox Value"
If "Processed" again, it would be
TestArray[1][0] = "Textbox Value"
that way I can parse through later and figure how many times the user "Processed" the drop-down selection;
var oneClickReport = $("#reportName").val();
if(oneClickReport == "Sample Report One"){
var arrayOneCount = reportOneArray.length;
var totalHouseholds = 0;
$("#reportChecks span:visible").each(function(){
if($(this).find(':checkbox').prop('checked')){
var HHName = $(this).text();
reportOneArray.push(HHName);
arrayTest[arrayOneCount][totalHouseholds] = HHName;
}
totalHouseholds += 1;
});
for(i = 0; i < arrayOneCount; i+=1){
alert(arrayTest[0][i]);
}
}
But when trying to "Process" for the second time, I receive the error of;
SCRIPT5007: Unable to set property '0' of undefined or null reference
on line;
arrayTest[arrayOneCount][totalHouseholds] = HHName;
You need to initialize your array. I'm not sure what exactly you want to do but you need an array like this
var arrayTest = []
And you will need to initialize subsequent value like
arrayTest[1] = []
Then you can access your array
arrayTest[1][0] = []
I made an example for you
var oneClickReport = $("#reportName").val();
var arrayTest = [] # You may need to put this elsewhere
if(oneClickReport == "Sample Report One"){
var arrayOneCount = reportOneArray.length;
var totalHouseholds = 0;
$("#reportChecks span:visible").each(function(){
if($(this).find(':checkbox').prop('checked')){
var HHName = $(this).text();
reportOneArray.push(HHName);
if(!arrayTest[arrayOneCount]){ arrayTest[arrayOneCount] = []; }
arrayTest[arrayOneCount][totalHouseholds] = HHName;
}
totalHouseholds += 1;
});
for(i = 0; i < arrayOneCount; i+=1){
alert(arrayTest[0][i]);
}
}
your problem with var arrayOneCount = reportOneArray.length; and you're not changing this value
Related
I am using ajax to call DB and using DOM to create the HTML for a small weather widget.
So I have an Array of element called _weather.
Its populate fine, however I am having touble to refresh the data in the array.
I have a button that if clicked call this function and pass the city name _town
My idea is to remove the value from array and call the function _checkNewTown to display the city I just removed from the array.
var _update_city = function(_town){
ntown = _town;
town = _town;
_weather.prototype.removeByValue = function (town) {
for (var i = 0; i < this.length; i++) {
var c = this[i];
if (c == town || (town.equals && town.equals(c))) {
this.splice(i, 1);
break;
}
}
};
_checkNewTown(ntown);
}
However its not working and its returning
SCRIPT5007: Unable to set value of the property 'removeByValue': object is null or undefined
weather_widget.js, line 121 character 3
I tried change it but could not figure out what to use.
Any help will be apprecciated
You can use Array.prototype.filter to remove items from an array like so:
var weather = [{city: 'city1', ....}, ....];
var city = 'city1';
var filtered = weather.filter(function (i) {
return i.city !== city;
});
I have multiple checkboxes in a view and each one has some data attributes, example:
Once the button is clicked I'm iterating through all the checkboxes which are selected and what I want to do is get the data-price and value fields for each selected checkbox and create JSON array.
This is what I have so far:
var boxes2 = $("#modifiersDiv :checkbox:checked");
var selectedModifiers = [];
var modifierProperties = [];
for (var i = 0; i < boxes2.length; i++) {
for (var k = 0; k < boxes2[i].attributes.length; k++) {
var attrib = boxes2[i].attributes[k];
if (attrib.specified == true) {
if (attrib.name == 'value') {
modifierProperties[i] = attrib.value;
selectedModifiers[k] = modifierProperties[i];
}
if (attrib.name == 'data-price') {
modifierProperties[i] = attrib.value;
selectedModifiers[k] = modifierProperties[i];
}
}
}
}
var jsonValueCol = JSON.stringify(selectedModifiers);
I'm not able to get the values for each checkbox and I'm able to get the values only for the first one and plus not in correct format, this is what I'm getting as JSON:
[null,"67739",null,"1"]
How can I get the correct data?
You can use $.each to parse a jquery array, something like:
var jsonValueObj = [];
$("#modifiersDiv :checkbox:checked").each(function(){
jsonValueObj.push({'value':$(this).val(),'data-price':$(this).attr('data-price')});
});
jsonValueCol = JSON.stringify(jsonValueObj);
Please note it's generally better to use val() than attr('value'). More information on this in threads like: What's the difference between jQuery .val() and .attr('value')?
As for your code, you only had one answer at most because you were overwriting the result every time you entered your loop(s). Otherwise it was okay (except the formatting but we're not sure what format you exactly want). Could please you provide an example of the result you would like to have?
if you want to get an object with all checked values, skip the JSON (which is just an array of objects) and make your own....
var checked =[];
var getValues = function(){
$('.modifiers').each(function(post){
if($(this).prop('checked')){
checked.push({'data-price':$(this).attr('data-price'),'value':$(this).attr('value')});
}
});
}
getValues();
sure i'm missing something obvious here.. but mind is elsewhere
This should give an array with values (integers) and prices (floats):
var selected = [];
$("#modifiersDiv :checkbox:checked").each(function()
{
var val = parseInt($(this).val(), 10);
var price = parseFloat($(this).data("price"));
selected.push(val);
selected.push(price);
});
Edit: Updated answer after Laziale's comment. The $(this) was indeed not targeting the checked checkbox. Now it should target the checkbox.
I keep having issues iterating over some JSON to put in select options
(btw, ignore the actual values for "label", those are garbage atm).
Here is an example that my php is passing into this:
[{"value":"1","label":"04-22-12"},{"value":"4","label":"04\/04\/12"}]
I am currently trying this loop:
*note, dateSelect is defined somewhere else
for (res in JSON.parse(request.responseText)) {
var date = document.createElement("option");
date.value = res.value;
date.text = res.label;
dateSelect.add(date, null);
}
However, it is adding "undefined" into my options...
How do I get it so each value and corresponding label is put in there correctly?
You have an Array, so don't for-in.
In your code, res is the property name (the index of the Array in this case) in the form of a string, so the properties you're looking for aren't going to be defined on the string.
Do it like this...
for (var i = 0, parsed = JSON.parse(request.responseText); i < parsed.length; i++) {
var res = parsed[i];
var date = document.createElement("option");
date.value = res.value;
date.text = res.label;
dateSelect.add(date, null);
}
I was trying to get the country name and put it in the temparray, so that I can use the temparray to check the country (line 14). The problem is temparray can only contain one value and upon increasing the array length size by using temparray.length = 4, the heat map won't show up in the page.
The code below is to check duplicate name entry from within the array. If the country name is repeated, it will add the past value and its current value and add it into the data table again as the old row.
var i;
var suq = 0;
var temparray = [""];
var rowcount= 0;
//set the value
for (i = 0; i<count; i++){
var countryname = countryarray[i];
var hostcount = hosthitcount[i];
//document.write("hello");
for (rowcount=0;rowcount<temparray.length;rowcount++){
//check for any repeated country name
if (temparray[rowcount] != countryname){
data.setValue(suq, 0, countryname);
data.setValue(suq, 1, hostcount);
temparray[rowcount] = countryname;
//document.write("win");document.write("<br/>");
suq++;
}else{
//get the hits //rowindex
var pastvalue = data.getValue(rowcount,1);
//add the previous value with current value
var value = parseInt(hostcount)+parseInt(pastvalue);
value+= "";
//document.write(value);
//put it in the table
data.setValue(rowcount,1,value);
// document.write("lose");document.write("<br/>");
}
}
}
I don't really understand what you are trying to do with temparray. It can surely contain more than one element with a temparray.push(countryname). Maybe this JavaScript array reference will help you?
var AppPatientsList = JSON.parse(JSON RESPONSE);
var AppPatientsListSort = AppPatientsList.sort(function(a,b){
return a.firstName.toLowerCase() <b.firstName.toLowerCase()
? -1
: a.firstName.toLowerCase()>b.firstName.toLowerCase()
? 1 : 0;
});
var DataArray = [];
for (var i = 0; i < AppPatientsListSort.length; ++i) {
if (AppPatientsListSort[i].firstName === search.value) {
var appointment = {};
appointment.PatientID = AppPatientsListSort[i].PatientID;
appointment.ScheduleDate = AppPatientsListSort[i].ScheduleDate;
alert(appointment.ScheduleDate); // Works fine, i get the date...
}
DataArray[i] = appointment;
}
var RowIndex = 0;
var ScheduleDate = "";
for (i = 0, len = DataArray.length; i < len; i++) {
// Throws me error in this place... WHY?
if (ScheduleDate != DataArray[i].ScheduleDate) {
ScheduleDate = DataArray[i].ScheduleDate;
}
}
What's wrong with this code, why i am not able to access the ScheduleDate?
You are only initializing the appointment variable when you are inside the if clause, but you are adding it to the array on every iteration.
If the first element of AppPatientsListSort does not have the value you search for, DataArray[0] will contain undefined.
In the second loop you then try to access DataArray[0].ScheduleDate which will throw an error.
Update:
Even more important, as JavaScript has no block scope, it might be that several entries in DataArray point to the same appointment object.
Depending on what you want to do, everything it takes might be to change
DataArray[i] = appointment;
to
DataArray.push(appointment);
and move this statement inside the if clause so that only appointments are added that match the search criteria.
Further notes: To have a look what your DataArray contains, make a console.dir(DataArray) before the second loop and inspect the content (assuming you are using Chrome or Safari, use Firebug for Firefox).