Jason_Hough
Jason_Hough

Reputation: 464

jquery .each , if statements do not work

I am trying to remove empty columns in sharepoint display forms. I am quite new to JQuery so bear with me!

I have:

$("td.ms-formbody").each(function (index) {
  if (index=6)
  {
    console.log("Mobile");

So it loops through all the formbody tags and when it comes to the sixth one it should display "Mobile" to console.log but it is just logging 'Mobile' x the count of the formbody tags. So it seems that the IF is not working. Can anyone advise ?

Upvotes: 0

Views: 687

Answers (4)

infamoustrey
infamoustrey

Reputation: 718

It look like you are new to passing functions as parameters as well.

Consider the following code:

$("td.ms-formbody").each(function(){});

In this example I am parsing through all occurrences of the td.ms-formbody selector. I am passing a function through to each occurrence which can then operate on each instance of that selector. Currently I'm doing nothing.

Now consider the following:

$("td.ms-formbody").each(function(){
    $("td.ms-formbody").index($(this));
});

This is one way of obtaining the index of each element. What JQuery is doing is getting all elements matching the selector and assigning them an arbitrary number based on the order in which they appear in the DOM. I can now operate on this information.

Using the correct conditional operator(==) and closing my if statement correctly, this will now log to the console if and when the each() function comes across a 6th element matching the selector.

$("td.ms-formbody").each(function(){
    if($("td.ms-formbody").index($(this)) == 6){
        console.log('Mobile');
    }
});

Upvotes: 0

Marcin Restel
Marcin Restel

Reputation: 280

With index = 6 you are setting the value of the variable index. You should change it to index == 6 or index === 6 (in case you'd like to respect the type of the compared values).

$("td.ms-formbody").each(function (index) {
    if (index === 6) {
        console.log("Mobile");
    }
}

By the way, it seems that you'd like to apply something to the sixth column. You could use a direct selector for that, no need to search for it with a loop.

:nth-child() selector

Upvotes: 1

Jan Schmutz
Jan Schmutz

Reputation: 890

$("td.ms-formbody").each(function (index) {
  if (index == 6) {
  console.log("Mobile");
  }
}

Upvotes: 0

user7867717
user7867717

Reputation: 283

Change :

if (index =6)
{
console.log("Mobile");
}

To :

if (index == 6)
{
console.log("Mobile");
}

If you use a simple '=' you set the variable

Upvotes: 0

Related Questions