My guess is that this javascript just finds the div called divid and then uses it with the sendit function.
var somevalue = 19;
if (navigator.appName.indexOf("Microsoft") != -1) {
thediv = window["divid"];
} else {
thediv = document["divid"];
}
thediv.sendit(somevalue);
I would imagine in jQuery it would look something as simple as this:
var somevalue = 19;
$('divid').sendit(somevalue);
But it's not working!! What could I be missing?
I should say that it's in the middle of other javascript code, could that be a problem?
You would need to get the actual DOM object (not the JQuery collection) to access the function that you set on it.
$('divid').get(0).sendit(somevalue);
Assuming there is an element with ID 'divid' you need to use the ID selector #
var somevalue = 19;
$('#divid').sendit(somevalue);
That may not be the whole answer as it's unclear where sendit is defined.
Related
I know that there is a really simple jQuery way to to this, but now I would like to understand why my code is not working properly:
function insertAfter(referenceNode, newNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
var menuHelp = document.querySelector(".menu_help");
for (var i = 0;i<menuHelp.length;i++){
menuHelp[i].onmouseenter = function(){
menuHelpPopup = document.createElement("div");
menuHelpPopup.setAttribute('class','menu_help_popup');
menuHelpPopup.innerHTML = "test";
insertAfter(menuHelp[i], menuHelpPopup);
}
menuHelp[i].onmouseleave = function(){
menuHelpPopup.remove();
}
}
What I'm trying to do is to create a popup and insert it after elements with a certain class when mouseover on them..
DEMO http://jsfiddle.net/r5e8rvkg/
Please make sure menuHelp is a nodeList, so you should use document.querySelectorAll;
When the mouse enter, the value of i is menuHelp.length. so you should use this, like insertAfter(this, menuHelpPopup)
I used getElementsByClassName and it seemed to have worked.
var menuHelp = document.getElementsByClassName('menu_help');
Please checkout here: http://jsfiddle.net/r5e8rvkg/1/
First, use querySelectorAll instead of querySelector.
More importantly, you need to take care that in your code:
menuHelp[i].onmouseenter = function(){
menuHelpPopup = document.createElement("div");
menuHelpPopup.setAttribute('class','menu_help_popup');
menuHelpPopup.innerHTML = "test";
insertAfter(menuHelp[i], menuHelpPopup);
}
The value i would not be passed in correctly because the event onmouseenter is Async. When the function is called, the value of i is actually i === menuHelp.length, which results in menuHelp[i] === undefined.
You need to use Closure, as shown in my JSFiddle code.
The document.querySelector() method returns only the first element with the specified selector. To get each element with class 'menu_help', you need to use the document.querySelectorAll() method.
In other words, replace:
var menuHelp = document.querySelector(".menu_help");
With
var menuHelp = document.querySelectorAll(".menu_help");
I know the question sounds strange, but it's really very simple. I have the following function which isn't working:
function start40Counter(counter40_set){console.log(counter40_set);
var gid = counter40_set[0];
var seat = counter40_set[1];
var suits = counter40_set[2];
var cont = "";
$.each(suits, function (num, suit) {
cont += "<a class='suitpick' onClick='pickSuit(counter40_set);'><img src='"+base+"images/someimg.png' title='Odaberi' /></a>";
});
$('#game40_picks').html(cont);
}
counter40_set is [10, 3, ["H", "S"]]. The part of the function that fails is the part this:
onClick='pickSuit(counter40_set);'
It says that counter40_set is not defined. I understand that. This wouldn't even work if counter40_set was a simple string instead of an array. If I try onClick='pickSuit("+counter40_set+");' I get a different error, saying H is not defined. I get this too, the array is rendered and JS doesn't know what H and S are.
I also tried passing the array elements (counter40_set[0] etc) individually but it still fails with the last element (["H", "S"]).
So, how do I pass this data to the onClick function in this case? There must be a more elegant way than concatenating the whole thing into a string and passing that to the function?
Btw, this is a simplified version. What I should really be passing in every iteration is [suit, counter40_set] so that each link chooses a different suit. I'm asking the simplified question because that will be enough to send me down the right path.
It cannot work,because the context is lost and thus "counter40_set" is not set.
To fix it simply use jquery for the onlick as well:
$('#game40_picks').empty(); // get rid of everything
$.each(suits, function (num, suit) {
var line = $("<a class='suitpick'><img src='"+base+"images/"+cardsuits[suit].img+"' title='Odaberi "+cardsuits[suit].name+"' /></a>");
line.click(function(ev){
ev.preventDefault(); // prevent default click handler on "a"
pickSuit(counter40_set);
});
$('#game40_picks').append(line);
});
this way the "counter40_set" is available for the click function.
You shouldn't use the onClick HTML attribute. Also, using DOM functions to build nodes saves the time it takes jQuery to parse strings, but basically the method below is to create the element and attach a click event listener and then append it to the specified element.
function start40Counter(event){console.log(event.data.counter40_set);
var counter40_set = event.data.counter40_set;
var gid = counter40_set[0];
var seat = counter40_set[1];
var suits = counter40_set[2];
var cont = "";
$.each(suits, function (num, suit) {
var link = document.createElement('a');
link.className = 'suitpick';
$(link).on('click', {counter40_set: counter40_set}, start40Counter);
var img = document.createElement('img');
img.src= base + "images/" + cardsuits[suit].img;
img.title = 'Odaberi ' + cardsuits[suit].name;
link.appendChild(img);
$('#game40_picks').append(link);
});
}
Not tested but it might work out of the box.
I have some ajax onclick stuff that updates this line when the value is selected from the menu:
<li id="li_273" data-pricefield="special" data-pricevalue="0" >
The intention is to take the that value (data-pricevalue) and then multiple it by the amount that is entered from another input box. Here's my function to try to make that happen:
$('#main_body').delegate('#element_240','keyup', function(e){
var temp = $(this).attr("id").split('_');
var element_id = temp[1];
var price = $('#li_273').data("pricevalue");
var ordered = $(this).val();
var price_value = price * ordered;
price_value = parseFloat(price_value);
if(isNaN(price_value)){
price_value = 0;
}
$("#li_273").data("pricevalue",price_value);
calculate_total_payment();
});
Except I get the following error:
Uncaught TypeError: Cannot call method 'data' of null
It appears as tho my attempt to get the price value out of getElementById isn't correct. Any suggestions?
UPDATE: The code above has been edited from your suggestions and thanks to all. It appears to be working just fine now.
This part is wrong:
var price = document.getElementById('#li_273').data("pricevalue").val();
Instead, you should use jQuery all the way here:
var price = $('#li_273').data("pricevalue");
Btw, you shouldn't use .val() because .data() already returns a string. .val() is used exclusively for input elements such as <input> and <select> to name a few.
Update
Also, the rest of your code should be something like this:
var price_value = parseFloat(price);
if(isNaN(price_value)){
price_value = 0;
}
getElementById doesn't return a jQuery object it returns just a normal DOM object.
You can wrap any DOM object in a jQuery call to get it as a jQuery object:
$(document.getElementById("li_273")).data("pricevalue").val();
Or better yet just use jQuery
$("#li_273").data("pricevalue").val()
Your call should be document.getElementById('li_273') it's a normal method and doesn't require the hash as jQuery does.
EDIT As #kennypu points out you're then using jQuery on a non jQuery object. #Craig has the best solution.
document.getElementById('#li_273').data("pricevalue").val(); should be jQuery('#li_273').data("pricevalue").val();
Again the variable price_value is not present, I think you mean price.
Ex:
$('#main_body').delegate('#element_240','keyup mouseout change', function(e){
var temp = $(this).attr("id").split('_');
var element_id = temp[1];
var price = $('#li_273').data("pricevalue").val();
var ordered = $(this).val();
var price_value = parseFloat(price);
if(isNaN(price_value)){
price_value = 0;
}
$("#li_273").data("pricevalue",price_value);
calculate_total_payment();
});
The document.getElementById('#li_273') is the problem. The method won't recognize the hash. If you want to get the element ID using that method try document.getElementById('li_273') and it will work.
Otherwise use all jQuery.
Since you're using jQuery, why are you using document.getElementById instead of $(...)? It should be:
$('#li_273').data("pricevalue")
Note also that the data() method is only defined on jQuery objects, not DOM elements. And you don't need to call val() after it -- that's for getting the value of form elements.
Your getElementById is wrong with javascript you do not need the #, if your using jQuery do it like this instead (Also I removed the .val() because its not needed):
$('#main_body').delegate('#element_240','keyup mouseout change', function(e){
var temp = $(this).attr("id").split('_');
var element_id = temp[1];
var price = $('#li_273').data("pricevalue");
var ordered = $(this).val();
price_value = parseFloat(price_value);
if(isNaN(price_value)){
price_value = 0;
}
$("#li_273").data("pricevalue",price_value);
calculate_total_payment();
});
So in JavaScript I can do the following:
var someObj = document.getElementById("foo");
var fooClick = foo.onclick;
var someOtherObj = document.getElementById("bar");
someOtherObj.onclick = fooClick;
I'm wondering, what is the jQuery equivalent to the code above?
Thanks!
Is it really required that you get the event handler from another object? That doesn't seem like a great idea to me. A better way would be to define the handler, and assign it to both objects.
var clickHandler = function(e) { alert('click!'); };
$('#foo,#bar').click(clickHandler);
var someObj = $("#foo").get(0);
var fooClick = someObj.onclick;
$("#bar").click(fooClick);
or if you want this in one line:
$("#bar").click($("#foo").get(0).onclick);
Just adding to Daniel Schaffer's answer (+1'd), you can also inline your click 'handler' definition, for example:
$("#foo, #bar").click( function() {
alert( this.id + ' was clicked.' );
} );
The behaviour should be the same, but depending on your coding style taste, you may prefer this (I do).
I'm trying to turn more into a hyperlink, but it's like it totally ignores the last wrap.
$j('#sub > div[id^="post-"]').each(function() {
var sid=this.id.match(/^post-([0-9]+)$/);
var sfimg = $j(this).find("img");
var sfhh = $j(this).find("h2");
var sfpt = $j(this).find("p:not(:has(img)):eq(0)");
var more = 'more';
$j(this).html(sfimg);
$j(sfimg).wrap($j('<a>').attr('href', '/blog/?p='+sid[1]));
$j(this).append(sfhh).append(sfpt);
$j(sfpt).wrap($j('<div>').attr('class', 'sfentry'));
$j(this).append('<div class="morelink">'+more+'</div>');
$j(more).wrap($j('<a>').attr('href', '/blog/?p='+sid[1]));
});
You over-using the jquery function ($j(), in your case) and your doing things in the wrong order. Also, there may be cases (possibly) that $(this).find('img'), for instance, might return more than one element... Not sure of your scenario, though.
Try this (may not be perfect, but it should lean you in the right direction):
$j('#sub > div[id^="post-"]').each(function() {
var sid = this.id.match(/^post-([0-9]+)$/);
var sfimg = $j(this).find("img");
var sfhh = $j(this).find("h2");
var sfpt = $j(this).find("p:not(:has(img)):eq(0)");
var more = 'more';
sfimg.wrap($j('<a>').attr('href', '/blog/?p='+sid[1]));
$j(this).html(sfimg);
sfpt.wrap($j('<div>').attr('class', 'sfentry'));
// You do realize what you have will append the paragraph to your h2 tag, right?
// I think you want:
/*
$j(this).append(sfhh).end().append(sfpt);
*/
$j(this).append(sfhh).append(sfpt);
$j(this).append('<div class="morelink">'+more+'</div>');
$j('.morelink',this).wrap($j('<a>').attr('href', '/blog/?p='+sid[1]));
});
There were all sorts of crazy things going on in that code. Remember that you need to modify the objects before appending them to another object (unless you have some unique way of identifying them after the fact, i.e. IDs).
Good luck.
Why do you expect $j(more) to match anything?