Remove item from Javascript array on change - javascript

I have a bit of situation. Basically I am adding an item to JavaScript array, which I am populating on select box change. But the problem is when I input 0, it should removed from an array.
Here is the code
var addon = new Array();
function updateAddons(){
addon.length=0;
var plan = new Array;
var planQty = new Array;
plan.length=0;
planQty.length=0;
for(var j =0 ; j< 3; j++){
$("select[name='addon_"+j+"[]'] option:selected").each(function(){
var item = {
product_name : $(this).attr('pn'),
product_cost : $(this).attr('cost'),
product_id : $(this).val()
};
if(item.product_id != 0){
plan.push(item);
}
});
$("input[name='addonQty_"+j+"[]'] ").each(function(){
if($(this).val() != 0){
planQty.push($(this).val());
}
});
}
for(var i =0; i < plan.length; i++){
var item = {
product:plan[i],
product_qty:planQty[i]
}
if(item.product.product_id != 0){
addon.push(item);
}
}
}
I have created a jsfiddle click here to view that. (check your browser console for the complete object.)
If someone can help. And please explain your answer.
Regards

I solved it myself. put a artibitary number in place of 0 and not adding in the final array.
Thanks

The main problem with you code is the following statement:
if($(this).val() != 0)
The problem is if the input is empty the value is undefined. In javascript undefined is not equal to 0. An easy way to solve this is to test for undefined as well:
if($(this).val() != 0 && $(this).val() != undefined)

Related

javascript get only array elements equal to variable

I'm trying to compare the variable determineHour against the array stationRentalsHours, whenever the variable would be equal to a stationRentalsHours element, I'd like to add that element to another Array (stationRentalsHoursTemp), but only the values that match. I tried with simple operators, but that doesn't put anything into the temp array. I also tried using JQuery $.inArray, but that gives me some strange results, Equal to those in the original array. Are there any other methods of comparing a variable with an array for this particular task?
Thank you for any help.
function updateChart() {
if(canvas3){canvas3.destroy();}
var determineHour = selectNumber.options[selectNumber.selectedIndex].innerHTML;
for (var i = 0; i < stationRentalsHours.length; i++) {
/*if(determineHour == stationRentalsHours){
stationRentalsHoursTemp.push(stationRentalsHours[i]);*/
if( $.inArray(determineHour, stationRentalsHours[i])){
stationRentalsHoursTemp.push(stationRentalsHours[i]);
}
}
In this case, instead of using $.inArray, you can simply use the for loop and the index to test the equality. I guess you mixed up two things:
var determineHour = selectNumber.options[selectNumber.selectedIndex].innerHTML;
for (var i = 0; i < stationRentalsHours.length; i++) {
if( determineHour == stationRentalsHours[i]){
stationRentalsHoursTemp.push(stationRentalsHours[i]);
}
}
Better yet, use filter:
var determineHour = selectNumber.options[selectNumber.selectedIndex].innerHTML;
stationRentalsHoursTemp = stationRentalsHours.filter(function(val){return val == determineHour;});
Instead of
if( $.inArray(determineHour, stationRentalsHours[i])){
Try
if( $.inArray(determineHour, stationRentalsHours) != -1){
Your commented out code would do the trick with a slight amendment to the if condition. Your original condition was comparing a string to an array instead of an individual element in that array:
function updateChart() {
if(canvas3){
canvas3.destroy();
}
var determineHour = selectNumber.options[selectNumber.selectedIndex].innerHTML;
for (var i = 0; i < stationRentalsHours.length; i++){
if(determineHour == stationRentalsHours[i]){
stationRentalsHoursTemp.push(stationRentalsHours[i]);
}
}
}

How to fix code that returns undefined?

I have this code:
const liked_users = promises[1];
const disliked_users = promises[0];
if (liked_users.length > 0 || disliked_users.length > 0){
for(var i = 0; i < liked_users.length; i++){
for(var j = 0; j < disliked_users.length; j++){
for(var k = 0; k < _USERS.length; k++){
if(_USERS[k].useruid == liked_users[i].likedUseruid || disliked_users[j].dislikedUseruid){
_USERS.splice(i, 1);
i--;
break;
}
basically what is happening is that I access the firebase database and I pull out some data from my objects.
The problem comes where sometimes liked_users is going to be blank and therefore liked_users[i].likedUseruid will return undefined. When they are defined, the code runs fine.
How can I put in some conditional or block of code that allows it to be read in a way that accepts it can be undefined or doesn't run the code until it is defined? I can show more code if it will help.
In JavaScript if you put just variable name in if condition then it will check its available or not.
For example put this block
if(_USERS[k].useruid == liked_users[i].likedUseruid || disliked_users[j].dislikedUseruid){
....
}
in this
if(_USERS[k].useruid && liked_users[i].likedUseruid && disliked_users[j].dislikedUseruid){
....
}
The above condition will check that _USERS[k].useruid is available or not and will continue...
You can make condition as per your need.
I hope this will help you.

Javascript 2D Array Loop Stopping

Im writing a program to which I need to retrieve values from multiple input boxes and stash them in a 2D array so that I can $.post them to a php file.
The problem is, the loop seems to stop upon reaching "scoresScores[j][k] = $(this).val;" part. But whenever I comment out that part, it will loop just fine. What seems to be the problem?
UPDATE: It's not just the loop that stops, all the code below scoresScores doesn't get executed.
if(flag){
studIDs = [];
scoreScores = [[]];
pScores = [];
$(".studID"+term).each(function(i){
studIDs[i] = $(this).text();
for(var j = 0; j < countTypes; j++){
pScores[j] = $("#txtPScoreEdit"+term+"-"+j).val();
$(".txtScoreEdit"+term+"-"+j).each(function(k){
if(k == i){
scoreScores[j][k] = $(this).val();
}
});
}
});
when($.post("/res/php/editScores.php",{
studIDs: studIDs,
scoreSubjEDP: <?php echo $_GET['EDPCode']?>,
scoreTerm: term,
scoreScores: scoreScores,
pScores: pScores
})).done(function(){
location.reload();
});
}
It's because scoreScores only has one nested array # index === 1
So when you loop and j > 0 or k > 0 it will fail.
You just need to make sure the indexes are valid.
edit:
If sparse arrays are OK, the following should work:
if(k == i){
if(!scoreScores[j]) { scoreScores[j] = []; }
scoreScores[j][k] = $(this).val();
}

if statement not working properly in jquery

I have two arrays: arr and myArraycode. Both have some values retrieved from a database. The values of myArraycode are displayed in select on each row. Now I need to disable all rows which have a value not appearing in the arr array.
For example,
arr =["abc","cde"];
myArraycode=["sample","abc","cde"];
I have three table rows which have sample in one row, abc in another and cde in a third. Now i need to disable the row with sample because sample is not in the array arr.
I have tried the following code:
var kt = 0;
var kts = 0;
var sk=0;
var sv =0;
while(kt < myArraycode.length)
{
if($.inArray(myArraycode[kt],arr) === -1 )
{
$("#table tr").find('td').find("select:contains("+myArraycode[kt]+")").closest('tr').find('input[type=text]').attr("disabled","disabled");;
$("#table tr").find('td').find("select:contains("+myArraycode[kt]+")").closest('tr').find('select').attr("disabled","disabled");;
}
kt++;
}
Please help me to solve the problem.
Demo
arr =["abc","cde"];
myArraycode=["sample","abc","cde"];
for(var i=0; i < myArraycode.length; i++)
{
if($.inArray(myArraycode[i],arr) === -1 )
{
$('option[selected="selected"]:contains("'+myArraycode[i]+'")').parent().attr('disabled','disabled');
}
}
I've corrected some of the syntax errors, but this should do the trick for you
For performance reasons you could also either use a decremental for loop or save the array.length value in a variable so the loop doesn't need to recalculate the value every run
I have updated your answer in jsfiddle
Note that the HTML requires the selected attribute for this to work
<option value="sample" selected="selected">sample</option>
I tried the following code to disable select box having selected value as sample
$( document ).ready(function(e){
arr =["abc","cde"];
myArraycode=["sample","abc","cde"];
for(var i=0; i < myArraycode.length; i++)
{
if($.inArray(myArraycode[i],arr) === -1 )
{
$("select").each(function(){
if($(this).val() == myArraycode[i])
{
$(this).closest('tr').find('select').attr('disabled','disabled');
}
});
}
}
});
Demo

className null or not an object again

The problem with IE.
Here is the code:
if (($.browser.msie)) {
var first_el = 0;
var targie = document.getElementById(targId).getElementsByTagName("div");
for (var i = 0; i < targie.length, first_el < 1; i++) {
if ((typeof targie[i].className != 'undefined') && (targie[i].className != null)) {
if ((targie[i].className == "category list even") || (targie[i].className == "category list") || (targie[i].className == "good list even") || (targie[i].className == "good list")) {
var targ = targie[i];
first_el += 1;
}
}
}
}
And the error - className null or not an object
Found a similar topics, but the solutions did not help me.
Thanks in advance
I don't think that's the actual error message. It is more like cannot access property "classname", targie[i] is null or not an object, isn't it?
Your problem seems to be the condition part of your loop: i < targie.length, first_el < 1 which uses the comma operator. This means your loop will run as long as it did not find an element - even if there are no more elements. Change it to i < targie.length && first_el < 1 and it should work.
Btw, you seem to use jQuery. Why don't you use a DOM selector like $("#"+targid+" div.list")? Then, you could use an each loop to set up your variables, or just add a :first selector and go on with jQuery.
I think you should use getAttribute('class'); if user's broser is IE

Categories

Resources