Javascript won't go past the first two lines of code? - javascript

I am running this code:
if (div == '') {
console.log("hi"),
document.getElementById('divd').innerHTML = first,
$('draggablelamb').addClass('fade'),
$('droppable').addClass('bowl');
}
When the user presses a button (there are variables that I have left out and the elseif and else statements). However, when I run it in the browser it only goes past the first two lines of code (console.log("hi") and document.getElementById('divd').innerHTML = first) and then skips the rest and goes onto the next elseif. Why is it doing it? How can I stop it from doing this?
Update:
I now know that it goes past all the lines of code by using this:
console.log("Hi");
document.getElementById('divd').innerHTML = first;
console.log("Hello again");
$('draggablelamb').addClass('fade');
console.log("Bonjour");
$('droppable').addClass('bowl');
console.log("Guten Tag");
but just maybe doesn't carry it out?

Remove the , from the end of the first three statements.
Try,
if (div == '') {
console.log("hi");
document.getElementById('divd').innerHTML = first;
$('.draggablelamb').addClass('fade'); // add dot in the selector if it is a class
$('.droppable').addClass('bowl'); // add dot in the selector if it is a class
}

if (div == '') {
console.log("hi");
$('#divd').html(first);
$('.draggablelamb').addClass('fade');
$('.droppable').addClass('bowl');
}
1. You had commas , at the end of each line. It should be semi-colons ;.
2. You were selecting elements by class but missing the full-stop class selector .. So you had $('draggablelamb') when it should be $('.draggablelamb').
3. You've used jQuery for the selectors, so you can also use jQuery to write the innerHTML. Like this $('#divd).html(first);.

Your selectors are looking for the elements draggablelamb and droppable, but they won't find any, as there are no such elements in HTML.
Searching for something that isn't there will result in an empty jQuery object, and it will still accept calls that would change the elements in it, and simply do nothing.
If you are looking for elements with classes by those names, you need periods before the class names in the selectors:
$('.draggablelamb').addClass('fade');
$('.droppable').addClass('bowl');
Also, as Rajaprabhu Aravindasamy pointed out, commas aren't used between statements in Javascript. Although it would still work in this case, because there is a comma operator that can be used between expressions, it can cause problems in other cases.

Related

Easy level, selecting elements in DOM, optimization, creating method function

Please, do not laugh, too much. I know jQuery ans JS for a short a while.
1) How can I make this code more efficient? First line is how do I "select" elements, the second, line is how do I prep to "select", next or previous element.
jQuery('code:lt('+((aktywneZdanie+1).toString())+'):gt('+((aktywneZdanie-1).toString())+')').removeClass('class2');}
aktywneZdanie=aktywneZdanie-1
2) I can not create a function which is working as a method. What I meant is how to change:
jQuery('#something').addClass('class1')
.removeClass('class2');
to something like this:
jQuery('#something').changeClasses();
function changeClasses(){
.addclass('class1');
.removeClass('class2');}
For the first one, why do you need a selector like that? couldn't you find something less specific to hook onto? If you must keep it when joining an number and a string, JavaScript will convert the number to string behind the scenes so you don't really need the .toString() and could do the "maths" +/-1 outside of your selector making it more readable.
Edit
In regards to your comment I am not really sure what you mean, you could assign a class to the "post" items and then add the unique id to a data-attribute ID. To make it simpler you could do something like this:
var codeLt = aktywneZdanie + 1,
codeGt = aktywneZdanie - 1;
$('code:lt(' + codeLt + '):gt(' + codeGt +')').removeClass('class2');
End Edit
And the second solution should work, all your doing is passing the dom elements found from your selector into a function as a jQuery "array" in which manipulate to your needs
And for your second question why not just toggle the class on and off? having a default state which reflects class one?
jQuery('#something').toggleClass('uberClass');
Or you can pass your selector to the function
changeClasses(jQuery('#something'));
Then inside you function work on the return elements.
Edit
Your code should work fine, but id suggest checking to make sure you have got and element to work on:
changeClasses(jQuery('#something'));
function changeClasses($element){
if($element.length > 0) {
$element.addClass('class1');
}
}
End Edit
Hope it helps,
1) How can I make this code more efficient? First line is how do I "select" elements, the second, line is how do I prep to "select", next or previous element.
jQuery('code:lt('+((aktywneZdanie+1).toString())+'):gt('+((aktywneZdanie-1).toString())+')').removeClass('class2');}
aktywneZdanie=aktywneZdanie-1
I stoped creating this wierd code like this one above, instead I start using .slice() (do not forget to use .index() for arguments here), .prev(), .next(). Just those three and everything is faster and clearer. Just an example of it below. No it does not do anything logical.
var activeElem = jQuery('code:first');
var old Elem;
jQuery('code').slice('0',activeElem.index()).addClass('class1');
oldElem=activeElem;
activeElem=activeElem.next();
jQuery('code').slice(oldElem.index(),activeElem.index()).addClass('class1');
oldElem.toggleClass('class1');
activeElem.prev().toggleClass('class1');
and the second part
2) I can not create a function which is working as a method. What I meant is how to change:
jQuery('#something').addClass('class1')
.removeClass('class2');
to something like this:
jQuery('#something').changeClasses();
function changeClasses(){
.addclass('class1');
.removeClass('class2');}
This one is still unsolved by me.

jQuery filter method usage

What's the use of below snippet ? I extracted it from jQuery API. I don't understand it:
$("div").filter( $("#unique") )
Please be kind enough to explain this to me.
It is extracting the only one div with id=unique.
$('div'). // return all divs
filter( $('#unique') ); // take the div with id=unique
So. this statement will return you the div with id=unique.
Note
This statement can also be written as $('div#unique') or just $('#unique').
The filter method enables you to filter out only specific elements from amongst a selection. Say you want to choose all spans whose text contains more than 3 characters. So you would do this:
$("span").filter(function() { return $(this).text().length > 3; }).click(...);
The function should check for some condition and return a boolean. if it sends true that element is kept in the selection, else discarded. So for your current question, it would

Javascript Regex and getElementByID

I'm trying to search for all elements in a web page with a certain regex pattern.
I'm failing to understand how to utilize Javascript's regex object for this task. My plan was to collect all elements with a jQuery selector
$('div[id*="Prefix_"]');
Then further match the element ID in the collection with this
var pattern = /Prefix_/ + [0 - 9]+ + /_Suffix$/;
//Then somehow match it.
//If successful, modify the element in some way, then move onto next element.
An example ID would be "Prefix_25412_Suffix". Only the 5 digit number changes.
This looks terrible and probably doesn't work:
1) I'm not sure if I can store all of what jQuery's returned into a collection and then iterate through it. Is this possible?? If I could I could proceed with step two. But then...
2) What function would I be using for step 2? The regex examples all use String.match method. I don't believe something like element.id.match(); is valid?
Is there an elegant way to run through the elements identified with a specific regex and work with them?
Something in the vein of C#
foreach (element e in
ElementsCollectedFromIDRegexMatch) { //do stuff }
Just use the "filter" function:
$('div[id*=Prefix_]').filter(function() {
return /^Prefix_\d+_Suffix$/.test(this.id);
}).each(function() {
// whatever you need to do here
// "this" will refer to each element to be processed
});
Using what jQuery returns as a collection and iterating through it is, in fact, the fundamental point of the whole library, so yes you can do that.
edit — a comment makes me realize that the initial selector with the "id" test is probably not useful; you could just operate on all the <div> elements on the page to start with, and let your own filtering pluck out the ones you really want.
You can use filter function. i.e:
$('div[id*="Prefix_"]').filter(function(){
return this.id.match(/Prefix_\d+_Suffix/);
});
You could do something like
$('div[id*="Prefix_"]').each(function(){
if($(this).attr('id').search(/do your regex here/) != -1) {
//change the dom element here
}
});
You could try using the filter method, to do something like this...
var pattern = /Prefix_/ + [0 - 9]+ + /_Suffix$/;
$('div[id*="Prefix_"]').filter(function(index)
{
return $(this).attr("id").search(pattern) != -1;
}
);
... and return a jQuery collection that contains all (if any) of the elements which match your spec.
Can't be sure of the exact syntax, off the top of my head, but this should at least point you in the right direction

How do I concatenate a string with a variable?

So I am trying to make a string out of a string and a passed variable(which is a number).
How do I do that?
I have something like this:
function AddBorder(id){
document.getElementById('horseThumb_'+id).className='hand positionLeft'
}
So how do I get that 'horseThumb' and an id into one string?
I tried all the various options, I also googled and besides learning that I can insert a variable in string like this getElementById("horseThumb_{$id}") <-- (didn't work for me, I don't know why) I found nothing useful. So any help would be very appreciated.
Your code is correct. Perhaps your problem is that you are not passing an ID to the AddBorder function, or that an element with that ID does not exist. Or you might be running your function before the element in question is accessible through the browser's DOM.
Since ECMAScript 2015, you can also use template literals (aka template strings):
document.getElementById(`horseThumb_${id}`).className = "hand positionLeft";
To identify the first case or determine the cause of the second case, add these as the first lines inside the function:
alert('ID number: ' + id);
alert('Return value of gEBI: ' + document.getElementById('horseThumb_' + id));
That will open pop-up windows each time the function is called, with the value of id and the return value of document.getElementById. If you get undefined for the ID number pop-up, you are not passing an argument to the function. If the ID does not exist, you would get your (incorrect?) ID number in the first pop-up but get null in the second.
The third case would happen if your web page looks like this, trying to run AddBorder while the page is still loading:
<head>
<title>My Web Page</title>
<script>
function AddBorder(id) {
...
}
AddBorder(42); // Won't work; the page hasn't completely loaded yet!
</script>
</head>
To fix this, put all the code that uses AddBorder inside an onload event handler:
// Can only have one of these per page
window.onload = function() {
...
AddBorder(42);
...
}
// Or can have any number of these on a page
function doWhatever() {
...
AddBorder(42);
...
}
if(window.addEventListener) window.addEventListener('load', doWhatever, false);
else window.attachEvent('onload', doWhatever);
In javascript the "+" operator is used to add numbers or to concatenate strings.
if one of the operands is a string "+" concatenates, and if it is only numbers it adds them.
example:
1+2+3 == 6
"1"+2+3 == "123"
This can happen because java script allows white spaces sometimes if a string is concatenated with a number. try removing the spaces and create a string and then pass it into getElementById.
example:
var str = 'horseThumb_'+id;
str = str.replace(/^\s+|\s+$/g,"");
function AddBorder(id){
document.getElementById(str).className='hand positionLeft'
}
It's just like you did. And I'll give you a small tip for these kind of silly things: just use the browser url box to try js syntax. for example, write this: javascript:alert("test"+5) and you have your answer.
The problem in your code is probably that this element does not exist in your document... maybe it's inside a form or something. You can test this too by writing in the url: javascript:alert(document.horseThumb_5) to check where your mistake is.
Another way to do it simpler using jquery.
sample:
function add(product_id){
// the code to add the product
//updating the div, here I just change the text inside the div.
//You can do anything with jquery, like change style, border etc.
$("#added_"+product_id).html('the product was added to list');
}
Where product_id is the javascript var and$("#added_"+product_id) is a div id concatenated with product_id, the var from function add.
Best Regards!

Is jquery ":contains" selector accepts this kind of value "Banking and Finance"?

I'm having problem with the contains in jquery. It seems that it only accepts one word. Not a phrase or two words.
Example:
$('#div:contains('Word')'); --> This is okay
$('#div:contains('Just another word')'); --> This will return empty/this will not match.
Do you have any experience with this kind of problem?
Your reply is greatly appreciated.
What you need, is to use double quotes (instead those single quotes wrapping the whole selector), for example:
$("p:contains('John Resig')");
this will select the correct paragraph, with string 'John Resig' inside
or you can inverse it:
$('p:contains("John Resig")');
or you can use an old good escaping:
$('p:contains(\'John Resig\')');
Try it without the # and avoid using the same quoting within the code:-
$("div:contains('Just another word')");
Assuming you didn't already solve this, from your comment which included:
var selected = $(this).find(':selected').text();
if (selected.toLowerCase() != "all industries") {
if (trim(selected).length > 0) {
$("#contact-list-selectable li .contact-info-industry").parent().css("display", "none");
$("#contact-list-selectable li .contact-info-industry:contains('" + selected + "')").parent().css("display", "block");
alert($("li[style='display: block;']").text());
}
I'll assume you meant to use trim as a method on the string, or if not that you have a trim function defined somewhere else. If this is actually how your code looks and you have no custom trim function, then that's going to be your first problem, it should be: selected.trim().length
One potential issue is that while you check that the trim of selected is > 0, you don't use a trimmed version of selected when checking the contains. If you have any spaces/etc in your selected variable, it will fail for contains.
Here is an example. Note the trailing space in selected = "computer science "; that is intentional to demonstrate what happens in that case.
if you change
$("#contact-list-selectable li .contact-info-industry:contains('" + selected + "')").parent().css("display", "block");
to
$("#contact-list-selectable li .contact-info-industry:contains('" + selected.trim() + "')").parent().css("display", "block");
you can avoid this issue (working example, see here, note the trailing space is still there).
The only other issue I could think of would be if you were incorrectly forming any of your selectors and they did not actually match your DOM structure. Otherwise everything works fine in current jquery.

Categories