How to check this i the same element JQuery [duplicate] - javascript

I'm trying to use jQuery to open / close control 'boxes' on a webpage. Unfortunately, it doesn't look very good to close a box just to re-open it if the user happens to click on the already opened box. (Boxes are mutually exclusive).
The code I'm using doesn't work, and I'm not sure why. I still get a box closing just to open up anew, which isn't the desired functionality. I created the 'val' variable for debugging purposes; in the debugger, it shows 'val' as having the exact same value as $(this), which should prevent it from getting to the .slideToggle() inside the if statement, but doesn't.
function openBox(index)
{
val = $('#box' + index);
$('.profilePageContentBox').each(function(){
if($(this).css('display') != 'none')
{
if($(this) != val)
{
$(this).slideToggle(200);
}
}
});
val.slideToggle(200);
}

You can also do:
if(val.is(this))

Using the $() function will always create a new object, so no matter what, your equality check there will always fail.
For example:
var div = document.getElementById('myDiv');
$(div) === $(div); // false!
Instead, you could try just storing the actual DOM elements, since those are just referred to inside jQuery objects.
val = $('#box'+index).get(0);
...
if (this !== val) { }

Try this:
function openBox(index)
{
val=$('#box'+index);
$('.profilePageContentBox').each(function(){
if($(this).is(":visible"))
{
if(!$(this).is("#box"+index))
$(this).slideToggle(200);
}
});
val.slideToggle(200);
}

Related

Asking if variable is equal to an integer inside jquery click not working

The title really explains most of it, but basically, this should alert when I get the click the element, but it doesn't. It also does work when I put the alert() outside of the if, and in the beginning of the jquery on click. Here's my code:
var hasClickedWelcome = 0;
//Onclick event
$(".menu-welcome" ).click(function() {
var welcomeButton = document.getElementByClassName("menu-welcome");
if(hasClickedWelcome == 0) {
alert("hello");
$(".menu-welcome").addClass("menu-welcome-clicked");
hasClickedWelcome = 1;
} else {
welcomeButton.classList.remove("menu-welcome-clicked");
hasClickedWelcome = 0;
}
});
Your if statement has no meaning
if(hasClickedWelcome == hasClickedWelcome)
This will always return true, you'll always hit this code no matter what:
alert("hello");
$(".menu-welcome").addClass("menu-welcome-clicked");
hasClickedWelcome = 1;
Therefore, you have a clear logic problem.
Edit: See Daniel Beck suggestion on comments section
Initially, you have syntactic error, there is no inbuild function like document.getElementByClassName() (unless its your custom function), so clearly even if you put your alert in beginning of click it won't work.
Also, you are checking if(hasClickedWelcome == hasClickedWelcome) which does not make sense.
Use: document.getElementsByClassName("menu-welcome"); to get array of nodes having the class. Then, rest of your logic accordingly.
//Onclick event
$(".menu-welcome" ).click(function() {
// in jQuery "this" refers to the element that was selected in a callback
// it looks like toggleClass is really what you're looking for
$(this).toggleClass("menu-welcome-clicked");
});

Command Buttons Not Responding to JS functions

I am very close to finishing this program but am unable to get past one last hurdle. I want some very simple code to execute when the command buttons are pressed. When the Submit Order button is pressed the following code should run to check that the form is completed.
function validateForm()
{
if ($("tax").value = 0)
{
alert ("You have not selected anything to order");
}
if ($("shipCost").value = 0)
{
alert("You must select a method of shipping");
}
}
And when the reset button is pressed the following code should run.
function initForm()
{
$('date').value = todayTxt();
$('qty1').focus();
}
Unfortunately the buttons are not executing the code which I am trying to execute through the following set of functions.
window.onload = function ()
{
initForm();
todayTxt();
productCosts();
shipExpense();
$('shipping').onchange = calcShipping;
calcShipping();
$("Submit Order").onclick = validateForm();
$("reset").onclick = initForm();
}
I have created a fiddle so you can see the full program: http://jsfiddle.net/KhfQ2/ Any help is greatly appreciated.
You're doing it way wrong.
With if statements, you use == instead of =.
= in A = B means assign value of B to A
== in A == B means A equals B
Read about .ready and use it instead of window.onLoad, it's quite a bad choice when it comes to binding, ie.
$( document ).ready(function() {
//taken from api.jquery.com/ready/
});
If you're using jQuery, use # when refering to ID objects, ie.
$('#tax').val();
On no account should you use spaces when giving any object a unique name or class!
Pay attention to letters. You had ".clisk()" instead of "click()".
Check it out and provide us with fixed code.
It is simple. $("Submit Order") doesn't work, because the button doesn't have this id. You can change this to something like $("btn-submit-order"). Same thing to reset.
Moreover, when you test $("tax").value = 0 I think you mistyped = instead of ==.
Other issues...
I think you mean
if ($("#tax").val() == 0)
Note:
Uses the correct selector #
Uses the jQuery val() function. The jQuery object doesn't have a value property.
Compares to 0 using loose checking, though personally I would write the line as
if (+$("#tax").val() === 0)

Trigger event not working or suspected passing on index

.full-arrow is an arrow that selects the next page. .full-navigation is a navigation bar, quite simply boxes in a line that change colour when you select them. The rest of the function isn't on here but you get the general idea.
When I create a trigger event to the function below the first one, it goes through okay but I'm unsure whether it's not picking up the index() or whether it's just not working at all. Weirdly, it works the first time but I think that's because the same_page variable is declared as 0 in the beginning.
The reason I'm also doubting whether it's the index() not being passed on is because the alert("foo"); isn't coming up.
$(".full-arrow").click(function() {
$(".full-navigation li:eq(" + same_page+1 + ")").trigger("click");
});
$(".full-navigation li").click(function(event) {
//alert("foo");
//alert(same_page);
same_page = $(this).index();
if(same_page == $(this).index()) { return false; }
});
Where are you getting the same_page variable from? Try using parseInt( same_page, 10 )--I have a hunch it's actually a string.

jQuery that works in Firefox but not in IE

Ok guys/girls.
Below is some jQuery that runs in Firefox but no IE. I have no idea why it craps out in one and not the other.
Anyone??
function SwapTextAssetforPOS() {
$("*").each(function () {
if ($(this).children().length == 0) {
$(this).text($(this).text().replace('Assets', 'POS'));
$(this).text($(this).text().replace('Asset', 'POS'));
$(this).text($(this).text().replace('assets', 'POS'));
$(this).text($(this).text().replace('asset', 'POS'));
}
});
}
Sorry folks - the error that I get is:-
SCRIPT65535: Unexpected call to method or property access.
jquery-1.6.min.js, line 16 character 60352
EDIT:------------------------------------------------------------------------------------
Ok so an update - I removed the * selector and IE no longer blows up, my issue now is that I cant figure how to get it to do the replace on the element. I have the following code to ping up all the text elements in the object:
function SwapTextAssetforPOS() {
var containerElementByID = $("#assetDetailContents");
containerElementByID.children().children().each(function () {
var $this = $(this);
alert($this.text());
});
This chucks me up an alert for every bit of text, however some is contained within a table, some is within a span, and some is just there. I have no control over a majority of this stuff so my new question is how do I get the previous replace to work using this type of selector. -- I can believe how painful this is..
Cheers again
I see the problem in my IE browser. When you do the $("*").each... it takes every single element in the page (including title, script, etc). When you do .text(), looks like it fails for some elements in IE for which .text() doesn't make sense. Replace "*" for "div" and it should work for the divs for example.Maybe you could do something like if ($(this).text()) {$(this).text($(this).text().replace('Assets', 'POS'));} to make sure the text() is defined for that element.
Still, going through the whole DOM is overkill. Can you add a class to the elements that can have the text?, like class="replaceable" so you could just do a $(".replaceable").text(...
Ok folks - so firstly thanks for the help.
I have resolved the issue by cobbling a number of suggestions together and by doing a little bit of investigative work.
In a nutshell IE was crapping out when it ran up against an tag. I no not why but this is where it fell over every time.
function SwapTextAssetforPOS() {
var overlaycon = $("#jq-selectionHelper").find("*:not(img)"); //This line simply looks at the div surrounding the template and returns (to an array I believe) every element therein except for img tag
//as this breaks in IE when tying to do the replace text stuff below.
overlaycon.each(function () {
var $this = $(this);
if ($this.children().length == 0) {
$this.text($(this).text().replace('Assets', 'POS'));
$this.text($(this).text().replace('Asset', 'POS'));
$this.text($(this).text().replace('assets', 'POS'));
$this.text($(this).text().replace('asset', 'POS'));
}
});
}
This code runs and I believe is a lot more efficient than my original offering. Any further suggestions for performance re-factoring are welcome but thank the lord this is now working.
Thanks again for all the help.
Regards
This code has no problem as seen here . I tested in IE and FF both works fine
http://jsfiddle.net/wKWRC/
You should use F12 developer tool for IE and see what error you are getting that way others can know what exact problem is . You can debug script and see where you are getting error . IE is sensitive to javascript errors and its possible there is some error before you are calling this function .
http://msdn.microsoft.com/en-us/library/gg699336%28v=vs.85%29.aspx
Just a hunch but you might be running out of memory in IE.
First, using $('*') is never advisable, its better that you narrow it down with a selector like $('p').
Also, every time you call $(this) you create a new jQuery object, so if there are a lot of elements on your page you're making 9 objects every time.
The convention is to set $this = $(this) at the begining of the function so you only use one object.
function SwapTextAssetforPOS() {
$("*").each(function () {
var $this = $(this);
if ($this.children().length == 0) {
$this.text($this.text().replace('Assets', 'POS'));
$this.text($this.text().replace('Asset', 'POS'));
$this.text($this.text().replace('assets', 'POS'));
$this.text($this.text().replace('asset', 'POS'));
}
});
}
try it like this
for (var i = 0, replacements = ['Assets','assets','asset','Asset']; i < 4; i++)
$("*:contains('" + replacements[i] +"')").map(function() { this.innerHTML = this.innerHTML.replace(/asset(s){0,1}/igm, 'POS'); })

If Statements Skipping or Evaluating Strangely, JavaScript and jquery

So in jQuery, I have a global variable "currentSubNav" that stores a current visible element. The following code executes on "mouseenter".
I need it to get store element's ID, check to see if there was one. If there wasn't, set the new visible element to the default.
$('#mainMenu a').mouseenter(function() {
var newName = $(this).attr("id");
if(newName == ''){
var newName = "default";
}
Then it checks to see if the new element matches the current one. If so, it returns. If not, it performs the animations to bring in the new one.
if(newName == currentSubNav){
return;
}else{
$("div[name=" + currentSubNav + "]").animate({"left": "+=600px", "opacity": "toggle"}, "slow");
$("div[name=" + newName + "]").css({"margin-top": "0"});
$("div[name=" + newName + "]").fadeIn(2000);
$("div[name=" + currentSubNav + "]").animate({"left": "-=600px"}, 0);
currentSubNav = newName;
return;
}
});
I'm using Chrome at the moment, and according to the dev tools that isn't what happens.
Problem #1
"$(this).attr("id");" isn't returning undefined as the documentation claims. It seems to be returning "". BUT, when I have the if statement as I do above, it skips over the statement entirely. I set a breakpoint, but it never pauses execuation, so the statement is never evaluated.
Problem #2
After the animations occur, instead of using the return at the end of the statements it goes back and uses the return for the "newName == currentSubNav" if statement. I guess that not a big deal, but it's not the intended behavior.
I'm fairly new to JavaScript, and it appears I'm missing something about how JavaScript works. But I can't find what anywhere. Any help?
EDIT: It seems to be working in FireFox, (though jQuery isn't returning undefined, it is returning ''). So this is a Chrome problem at the moment.
I would change the assignment of "newName" as follows:
var newName = $(this).attr('id') || 'default';
That's more idiomatic, and it'll handle cases where you're getting null instead of an empty string, or vice-versa, and when it doesn't really matter anyway.
I suspect that some of the "problems" you're seeing are more a matter of the Chrome debugger than the actual way that the code is running.

Categories

Resources