Can anyone help with this (Javascript arrays)? - javascript

Hi I am new to Netui and Javascript so go easy on me please. I have a form that is populated with container.item data retuned from a database. I am adding a checkbox beside each repeater item returned and I want to add the container item data to an array when one of the checkboxes is checked for future processing.
The old code used Anchor tag to capture the data but that does not work for me.
<!--netui:parameter name="lineupNo" value="{container.item.lineupIdent.lineupNo}" />
here is my checkbox that is a repeater.
<netui:checkBox dataSource="{pageFlow.checkIsSelected}" onClick="checkBoxClicked()" tagId="pceChecked"/>
this is my Javascript function so far but I want to a way to store the container.item.lineupIdent.lineupNo in the array.
function checkBoxClicked()
{
var checkedPce = [];
var elem = document.getElementById("PceList").elements;
for (var i = 0; i < elem.length; i ++)
{
if (elem[i].name == netui_names.pceChecked)
{
if (elem[i].checked == true)
{
//do some code. }
}
}
}
I hope this is enough info for someone to help me. I have searched the web but could not find any examples.
Thanks.

var checkedPce = new Array();
//some other code
checkedPce[0] = stuff_you_want_to_add

If you merely want to add a value to an array, you can use this code:
var array = [];
array[array.length] = /* your value */;
You may need to use a dictionary approach instead:
var dictionary = {};
function yourCode(element) {
var item = dictionary[element.id];
if (item == null) {
item = /* create the object */;
dictionary[element.id] = item;
}
// Use the item.
}

Related

TypeError: 'undefined' is not an object in Javascript

I have a piece of Javascript code that assigns string of values to a string array.
Unfortunately if I try to add more than one string to the array, my UI simulator(which runs on JS code) closes unexpectedly. I have tried debugging but I cannot find anything. I am attaching that piece of code where the issue is. may be you guys could find some flaw? On the pop up button click the values I selcted on the UI should get stored in the array and I have a corressponding variable on the server side to handle this string array.
_popupButtonClick: function (button) {
var solutions = this._stateModel.get('solutionName');
var i;
var solutionsLength = solutions.length;
var selectedSolution = [solutionsLength];
this.clearPopupTimer();
if (button.position === StatusViewModel.ResponseType.Ok) {
for(i=0;i<solutionsLength;i++)
{
if(this._list.listItems[i].selected)
{
selectedSolution[i] = this._list.listItems[i].options.value;
}
}
this._stateModel.save({
selectedsolutions: selectedSolution,
viewResponse: StatusViewModel.ResponseType.Ok
});
} else {
this._stateModel.save({
viewResponse: StatusViewModel.ResponseType.Cancel
});
}
}
Change
var selectedSolution = [solutionsLength];
to
var selectedSolution = [];
This makes your array have an extra item that might be causing a crash.
Also,
you have an
if(this._list.listItems[i].selected)
{
selectedSolution[i] = this._list.listItems[i].options.value;
}
But no corresponding else, so your array has undefined values for i which are not entering the if.
Maybe adding an empty string might solve it:
if(this._list.listItems[i].selected)
{
selectedSolution[i] = this._list.listItems[i].options.value;
}
else
{
selectedSolution[i] = "";
}
The code is looking fine but there seems to be a piece of code which can cause error. For example, you are assigning var selectedSolution = [solutionsLength]; and for example solutionsLength is 5 then your loop runs for 5 times
for(i=0;i<solutionsLength;i++) // runs for 5 times
{
if(this._list.listItems[i].selected)
{
// but selectedSolution = [5]; which is on 0th index and from 1st to 4th index it is undefined
selectedSolution[i] = this._list.listItems[i].options.value;
}
}
So you can try to use push() like
selectedSolution.push(this._list.listItems[i].options.value);
and on initialization change it like,
var selectedSolution = [];
Hopefully this will solve your problem.
var selectedSolution = [solutionsLength];
keeps the value in the selectedSolution variable.
var selectedSolution = [3];
selectedSolution[0] gives the values as 3
So make it simple
var selectedSolution = [];

remove items from array with the same id one by one

the problem is that I have multiple objects with the same id. As you can see this works when it comes to removing all the items with the same id. How I can remove the objects one by one no matter if they are the same ID...thanks
individualObjects:[],
actions:{
increment:function(){
var obj = this.get('object');
this.get('individualObjects').pushObject(obj);
},
decrement:function(){
var obj = this.get('object');
var filter = this.get('individualObjects').findBy('obj_id', obj.get('obj_id'));
this.get('individualObjects').removeObject(filter);
}
}
Well to filter array you would need to use Array.filter to find out the items that do not belong in the "individualObjects" and later simply remove them by using "removeObjects"
decrement:function(){
var objects = this.get('individualObjects')
var notWanted = objects.filterBy('obj_id', this.get('object.obj_id'));
this.get('individualObjects').removeObjects(notWanted);
}
and solution 2
decrement:function(){
var removeObj = this.get('object');
var objects = this.get('individualObjects')
// As the condition is true given object is returned
var notWanted = objects.filter(obj => { return obj.get('obj_id') === removeObj.get('obj_id')  });
this.get('individualObjects').removeObjects(notWanted);
}
Ok so you want to remove items one by one. Weird but can be accomplished
first get the length for
var notWantedCount = objects.filterBy('obj_id', this.get('object.obj_id')).length;
Now
for(var i=0; i <= notWantedCount; i++) {
var toRemove = individualObjects.findBy('obj_id', obj.get('obj_id'));
individualObjects.removeObject(toRemove);
// Make some custom actions one by one.
}
I don't know ember, but you'll want to do a foreach on the array, and then test for id on each one. It should be something like this:
decrement:function(){
var obj = this.get('object');
self = this;
this.get('individualObjects').each(function(individualObject) {
if (individualObject.get('obj_id') == obj.get('obj_id'))
... you want to do something here? ...
self.get('individualObjects').removeObject(individualObject);
}
}
That way you can remove each object individually. Running any necessary code before or after it's removed. If you want to sort it first, you can do that before running the each function.

Javascript scope issue with jquery post and promise

I am trying to build an array from the responses of a jquery post. I have the following code:
categories_names = [];
$(categories).each(function(index, category_id) {
$.post('/modules/blog/add_post_categories', {post_id:result.result, category_id:$(category_id).val()},
function(result)
{
categories_names.push = result;
});
}).promise().done(function() {
var final_cats = categories_names.join("");
console.info(final_cats);
});
The post request inserts the category id into a table and returns the name of that category formatted like <li>Category Name here</li> so that once the array is built and all categories selected (by checkbox in the form previous to this) are entered into the database, the array can be joined and inserted as html to the final view. At the moment the code is just printing it out in the console as you can see but as you've probably guessed, it returns (an empty string)
I know this is most likely a scope issue since that's the area of javascript that still totally baffles me, so I'm hoping someone can shed some light on it.
Your .promise().done(...) isn't doing what you think it is. It's simply resolving instantly because there are no animations on the elements you are iterating over. Also, your syntax for [].push is wrong.
var defArr = $(categories).map(function(index, category_id) {
return $.post('/modules/blog/add_post_categories', {post_id:result.result, category_id:$(category_id).val()});
}).get();
$.when.apply(null,defArr).done(function() {
//var categories_names = [];
//for (var i = 0; i < arguments.length; i++) {
// categories_names.push(arguments[i][0]);
//}
var categories_names = $.map(arguments,function(i,arr) {
return arr[0];
});
var final_cats = categories_names.join("");
console.info(final_cats);
});
categories_names.push = result;
can you try changing this to
categories_names.push(result);
because push is a method, not a variable.

Assign new value to variable using itself

This doesn't work but I can't see why it wouldn't? any help people? :)
params = qs.split("=", 2),
id = params[1];
if(id.indexOf("?") != -1){
id = id.split("?", 1);
}
basically I want to change the value of 'ID' if the IF statement is true, if not.. it skips it and the value Id remains the default.
Thanks
The result of id = id.split("?", 1) is an array (of at most 1 item), but I think you want id to be a string. That would explain why id is not a string like you want.
I agree with the other comments. Please show us the URL string you want to parse and tell us which piece you're trying to get. Usually, you look for ? first, separate after that and then divide up various key=value sections.
If you had a URL like this:
http://www.example.com?foo=bar
Here's a simple function that gets you all the query parameters into an object:
function getParms(url) {
var sections, key, pieces = url.split("?");
var results = {};
if (pieces.length > 1) {
sections = pieces[1].split("&");
for (var i = 0; i < sections.length; i++) {
key = sections[i].split("=");
results[key[0]] = key[1];
}
}
return(results);
}
Working demo: http://jsfiddle.net/jfriend00/kNG3u/

get id of checked checkbox in gridview in javascript

I am having checkbox in each itemTemplate of asp:gridview
I want to get ids or values of those many selected checkboxes using only javascript
In pure javascript I'm not sure about platform portability: you'd REALLY want jQuery or some other helper library here.
With jQuery:
var values = [];
var ids = [];
jQuery.each(jQuery("input:checkbox").find(":checked"), function(){
values.push(jQuery(this).val());
ids.push(jQuery(this).attr("id");
});
will give you the ids and values of all the checked checkboxes.
EDIT: ugly, but this might work...
var values = [];
var ids = [];
var inputs = document.getElementsByTagName("input");
var i;
for(i=0;i<inputs.length;i++){
if(inputs[i].hasAttributes() && inputs.getAttribute('type') == "checkbox" && inputs.getAttribute('checked')){
values.push(inputs[i].getAttribute('value'));
ids.push(inputs[i].getAttribute('id'));
}
}
Let me know if that does what you want.
I am not exactly sure on what you are trying to do but this might help you out. This will get all of the inputs on the screen and process only the checked ones.
var inputList = document.getElementsByTagName("input");
var resultsArray = [];
for(var i = 0; i < inputList.length; i++) {
if (inputList[i].getAttribute("checked") == true) {
resultsArray.push(inputList[i]);
}
}
Sorry, forgot to tell you that this would be a list of elements. You will then need to extract them however you want to from resultsArray.

Categories

Resources