if statement not working properly in jquery - javascript

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

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]);
}
}
}

Get last 4 characters of every element of array in JavaScript

I would be surprised if this hasn't been asked in the past. I was unable to find something that works. I have an array of strings and I would like to create a new array with only the last 4 characters of each of the elements. The code is below. What do I need to change to make it work?
for(i=0; i<userScanDataObjects.length;i++){
// if statement used to select every alternative element from the array as th rows are duplicated
if (i%2 !==0){
deviceID_raw.push(userScanDataObjects[i].deviceID.value);
deviceID.push(deviceID_raw[i].substring(5,8));
}
['11114444', '22224444'].map(function(string) { return string.substring(string.length - 4, string.length) })
You can use Array.map depending on your targeted browser support/polyfills. And you can do the following:
for( var i = 0; i < array.length; ++ i ) {
array[i] = array[i].substr(-4);
}

How to match and remove an object from javascript array?

I am trying to delete an element based on string match for a object property but when I do a slice on the javascript array the array size decreases and indexes change. Please help e with a solution. Here is a jsfiddle link for the same.
Code
var selection = JSON.parse('[{"Connectors":"c1"},{"Connectors":"c2"},{"Schedules":"s1"},{"Schedules":"s2"},{"Gauges":"g1"},{"Gauges":"g2"},{"Gauges":"g3"}]');
removeitem("Gauges");
function removeitem(item) {
for (var i = 0; i < selection.length; i++) {
if (selection[i].hasOwnProperty(item)) {
selection.splice(i, 1);
}
}
}
Add i--;
function removeitem(item) {
for (var i = 0; i < selection.length; i++) {
if (selection[i].hasOwnProperty(item)) {
selection.splice(i, 1);
i--;
}
}
}
jsfiddle example
Assuming you don't have a problem with having undefined as the new value, then you could call delete[i]; instead of selection.splice(i, 1); in that case the length does not change and neither will the indices.
Both Abhi1964 and Loolooii solution seems to work fine and solve problem, but i would personally keep the filtered results in separate array instead of manipulating index/deleting value in the same array, reason being, separate array would make code look simpler to read and understand. Reviewer need not to understand the index manipulation or keep track of undefined.
var selection = JSON.parse('[{"Connectors":"c1"},{"Connectors":"c2"},{"Schedules":"s1"},{"Schedules":"s2"},{"Gauges":"g1"},{"Gauges":"g2"},{"Gauges":"g3"}]');
removeitem("Gauges");
var filteredResult = [];
function removeitem(item) {
for (var i = 0; i < selection.length; i++) {
if (selection[i].hasOwnProperty(item)) {
}else{
filteredResult.push(item);
}
}
}
//use filtered result as per your need.
Note:
I have not run this code, if some error seems to be there, please feel free to edit.

Remove item from Javascript array on change

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)

Javascript function not getting a value from an input box and loop through an array

im trying to gather an amount from a input box and then tick a certain amount of boxes which is an array.
this is what i got so far and it doesnt work :S
function checkAmount(ting) {
var boxes = document.getElementsByTagName("input");
for (var i = 0; i < ting.value; i++) {
if (boxes[i].name == "vote[]") {
boxes[i].checked = true;
}
}
}
And im calling it with this:
uncheckAll();
checkAmount(document.getElementsByName(\'ammount\'));
getElementsByName returns an array and your function is expecting a single element, you need to access the first element like this:
checkAmount(document.getElementsByName(\'ammount\')[0]);
Change the ting.value to boxes.length in the for loop:
function checkAmount(ting) {
var boxes = document.getElementsByTagName("input");
for (var i = 0; i < boxes.length; i++) {
boxes[i].checked = (boxes[i].name == "vote[]") ;
}
}
Try this:
boxes.item(i).checked = checked
sorry not sure how to insert javascript into the post
are you posting your real code?
If so, you realize that you are spelling 'amount' wrong in your function call?
From your statement "gather an amount from an input box" I think you expect ting to be a number entered into a text box and so you are calling a function that expects a number with a value that should resolve to an array of form element objects?
var m = document.getElementsByName("amount");
m will be an array!
in other words, it might work better if you made sure you were passing a number when you call checkAmount:
checkAmount(documents.forms[0].amount.value)
or:
checkAmount(documents.getElementsByName("amount")[0].value)
It would help a lot if you post the actual HTML and actual javascript code.
There are several problems with the code you posted, as indicated by the previous answers and replies. Try something like this:
function checkAmount(ting) {
var boxes = document.getElementsByTagName("input");
for (var i = 0; i < ting.value && i < boxes.length; i++) {
if (boxes[i].name == "vote[]") {
boxes[i].checked = true;
}
}
}
Called like this:
uncheckAll();
checkAmount(document.getElementsByName(\'ammount\')[0]);
Now you are safe from array out of bounds errors no matter the value typed in the input field and the call to checkAmount should work.
Try using
checked=checked
instead of
checked=true

Categories

Resources