jquery .each , if statements do not work - javascript

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 ?

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

Change :
if (index =6)
{
console.log("Mobile");
}
To :
if (index == 6)
{
console.log("Mobile");
}
If you use a simple '=' you set the variable

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

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

Related

Using 2 conditions with an IF statement in Cypress

Hello I'm trying to run the following code but somehow it does not work. The same code will work if I simply separate the IF statement in 2 and nest it.
My intention is to select only one element from the dropdown list but buy using includes, I'm getting 2 results; that is why I was trying to add an extra condition to it.
cy.get("#autocomplete").type("ne");
cy.get(".ui-menu-item").each(($el) => {
if ($el.text().includes("Netherlands" && $el.text().length === 11)) {
cy.wrap($el).click();
}
Do you happen to know why that is? is there a better way of doing this? thank you
You could do it with a .filter() with a function parameter.
This variation is not currently in the Cypress docs, but they are using jQuery under the hood so refer here jQuery docs, filter(function).
Note the function receives the raw DOM element so use innerText instead of jQuery .text().
You can add multiple criteria, but with === it checks for an exact match and the length check isn't needed.
cy.get("#autocomplete").type("ne");
cy.get('.ui-menu-item') // all items
.filter((index, el) => el.innerText === "Netherlands") // precise match
.eq(0) // take the first
.click(); // select it
There is a ) missing after the text Netherlands, you have to add that and there is an extra bracket ) added after 11, you have to remove that. So, your code should be:
cy.get("#autocomplete").type("ne");
cy.get(".ui-menu-item").each(($el) => {
if ($el.text().includes("Netherlands") && $el.text().length === 11) {
cy.wrap($el).click();
}
I had a somewhat similar issue where I want to select an item in a custom select component (so not a native select element).
I used a derivation of the most upvoted answer to achieve this:
cy.get('my-component .ng-dropdown-panel .ng-option')
.filter((_, el) => {
return el.querySelector('span.badge-location')?.textContent === locationName
&& el.querySelector('span.platform-name')?.textContent === platformName;
})
.should('have.length', 1)
.click();
The code loops through all possible option elements and finds the one I'm looking for and clicks on that one.

Any chance to reduce the size of this snippet of code?

IS there any way I could reduce the size of the snippet of code below? Something like if (!$('body#pagina_blog_1 to body#pagina_blog_10).length) Online javascript minifier tools do not help.
jQuery(function($){
if (!$('body#pagina_blog_1, body#pagina_blog_2, body#pagina_blog_3, body#pagina_blog_4, body#pagina_blog_5, body#pagina_blog_6, body#pagina_blog_7, body#pagina_blog_8, body#pagina_blog_9, body#pagina_blog_10').length)
return;
// do stuff
});
Yes you can: $('*[id^="pagina_blog_"]')
For more details refer jquery selectors: http://api.jquery.com/attribute-starts-with-selector/
If you know it's an id on the body tag, you don't even need to use selectors as you can just get the id string directly and compare it to anything you want using a regex. For example, you could do this:
if (document.body.id.match(/^pagina_blog_\d+$/)) {
// code here
}
Or, for just any one or two digits at the end:
if (document.body.id.match(/^pagina_blog_\d{1,2}$/)) {
// code here
}
Or, if you wanted to actually see if the number after the id is in some specific numeric range such as 1-10, you could do this:
var num, matches = document.body.id.match(/^pagina_blog_(\d+)$/);
if (matches) {
num = +matches[1];
if (num >= 1 && num <= 10) {
// code here
}
}
It's not really minifying, but how about just
if ( $('[id^="pagina_blog_"]').length === 0 ) {
// do stuff
}
Give them a shared class to select on.
If you must use the ids for some reason, I would suggest...
!$('body').is('[id^="pagina_blog_"]')
The reason you do not want to put the id selector as the first selector is this would result in a complete dom scan, which is not desired. However in your logic it looks like your only concerned with the body tag having it.

_.findWhere from underscorejs to JQuery

I am trying to implement this code: http://jsfiddle.net/wQysh/351/ in my project.
Everything is fine except for the line:
t = _.findWhere(sc, { id : Number(a.trim()) });
They have used underscorejs and I want to translate this to JQuery without using another lib.
I went through the doc and it stated:
findWhere_.findWhere(list, properties)
Looks through the list and returns the first value that matches all of the key-value pairs listed in properties.
If no match is found, or if list is empty, undefined will be returned.
But still I am confused about this since I am not sure what to return exactly (as first value). Can anyone give me a JQuery alternative to that line?
Thanks in advance..
If you don't the generic nature of _.findWhere() you can use a simple while loop, and compare the id to the numeric value of a (fiddle):
t = 0; // t is used as a counter
aValue = Number(a.trim()); // assign the value to a variable instead of iterating it
while (t < sc.length && sc[t].id !== aValue) { t++; }; // find the index where the id is the as the aValue
t < sc.length && toSet.push(sc[t]); // if t is less the sc.length we found the item in the array
If you need a findWhere without underscore try this gist.
I also used this example in my project. And also needed use JQuery instead of Underscore.
Here is my solution:
t = sc.filter(function (el) { return el.id === a });
It work perfect for me;
If you use number for ids, you can also convert a to integer
t = sc.filter(function (el) { return el.id === parseInt(a, 10) });

What is wrong with this if function based on iFrame selector?

I am trying to hide an iframe w/ the class of cs-iframe if it is on a certain URL by creating an if statement with the src URL
Right now, the selection part is not working with the if statement.
var theiFrame = document.getElementByClass("cs-iframe");
function hideiFrame() {
if (theiFrame.src = "http://www.test.com") {
alert("successful selection");
};
};
Thank you Sunday Stack Gods
The function is named document.getElementByClassName. It does not return a single element, but an array of elements.
Then, in your if condition, you do theiFrame.src = "http://www.test.com". With a single equal sign, this is an assignment expression, just like on the first line of your code. To check if two values are equal, you should use == or === (to see why there are two operators, see this question).
Finally, you could do this entirely in CSS, by using an attribute selector:
iframe[src="http://www.test.com"] {
display: none;
}

Syntax explanation please

I'm trying to understand 2 different lines of code below. My javascript is weak, trying to improve it with jquery (hmmmm)
What I'm trying to use the drag sort plugin from http://dragsort.codeplex.com/ specifically I'm using the http://dragsort.codeplex.com/SourceControl/changeset/view/74794#1025059 example.
I've gotten to the stage now where I've used this approach
var serialStr = "";
$("#list1 li").each(function(i, elm) {
serialStr = (i > 0 ? "|" : "") + $(elm).children().html();
});
The example has the following.
var serialStr = new Array();
$("#list1 li").each(function(i, elm) {
serialStr[] = = $(elm).attr("itemId");
});
The reason I have the first approach is that I was testing everything out and its what they had in the HTML example. I'm now trying to save the state so I've moved onto the php example.
So my question is what is the primary difference going on in the different lines here? My understanding of the first line is that its selecting each child element inside of the li tag on list1 I don't really get the (i > 0 ? "|" : "") bit.
In the second snipplet from what I understand its selecting every attribute with the itemID assignee in list1 li ?
serialStr[] = (i > 0 ? "|" : "") +$(elm).children().html() is a shorthand if-clausule. It does the same as:
if(i > 0) {
serialStr[] = "|" +$(elm).children().html();
} else {
serialStr[] = "" +$(elm).children().html();
}
The expression (i > 0 ? "|" : "") is using the conditional operator condition ? expr1 : expr2 to not to prefix the first value with | but only every following values.
But the expression serialStr[] = = $(elm).attr("itemId") is invalid syntax. Javascript does not have a push operator [] like PHP has. Use Array.prototype.push instead.
I don't think you've pasted the code exactly as neither snippet makes sense. The first seems to want to be concatenating strings together, but is missing the += that would make that happen; the second is making a list, presumably to join() together afterwards, but is using some odd []= syntax that does not exist in JavaScript.
I don't really get the (i > 0 ? "|" : "") bit.
First time round the loop, pick "", subsequent times pick "|". This is the traditional way to make a string where each element is separated by a character.
But join() is generally a cleaner way to do that, and you can use map() to run a function over an array returning a new array, instead of having to manually create one:
var itemIds= $('#list1 li').map(function() {
return $(this).attr('itemId');
}).get().join('|');
(Or $(this).html() if you really want to get the HTML content, which sounds a bit questionable.)
map() is a jQuery function but ECMAScript Fifth Edition has a map() method on plain arrays too. About map in general.

Categories

Resources