krishna
krishna

Reputation: 4089

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

Upvotes: 0

Views: 120

Answers (2)

Ayame__
Ayame__

Reputation: 1000

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>

Upvotes: 1

krishna
krishna

Reputation: 4089

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

Upvotes: 0

Related Questions