innerHTML not working properly when used on a jQuery object - javascript

This code isn't working as expected. It is not showing any text inside of span.day where it should be showing today's day (Tuesday at the time of writing). It is also not properly adding the class "currentDay" inside of the $.each callback.
$('#showLess span.day').innerHTML=weekday[today];
$.each($('#showMore p span.day'), function(index, item) {
if(typeof item.innerHTML != 'undefined')
{
alert('item.text:' +item.innerHTML);
alert('weekday[today]'+item.innerHTML.indexOf(weekday[today]));
if(item.innerHTML.indexOf(weekday[today])!=-1) {
alert("check which element has added class currentDay:");
item.addClass('currentDay');
}else{
if(item.hasClass('currentDay')) {
item.removeClass('currentDay');
}
}
}
});
.innerHTML is not changing the HTML, additional class is not getting added as expected.
<p id="showLess" class="less">
<span class="day">**Tuesday**</span>
</p>
Why isn't the day showing?
Why is the show/hide not working?
$('.less').on('click', function(e) {
$('#showMore').show();
$('#showLess').hide();
});
$('.more').bind('click', function(e) {
$('#showLess').show();
$('#showMore').hide();
});

You are trying to invoke JS properties on jQuery objects.
For example innerHTML
And you are trying to invoke that on a jQuery object.
$('#showLessHours span.day').innerHTML
Should be
$('#showLessHours span.day')[0].innerHTML
or
$('#showLessHours span.day').html(weekday[today]);
And in your each loop item is a JS object and you are trying to add a class using jQuery. Convert that to jQuery object first .
item.addClass('currentDay');
item.removeClass('currentDay');
should be
$(item).addClass('currentDay'); or $(this).addClass('currentDay');
$(item).removeClass('currentDay'); or $(this).removeClass('currentDay')
Instead you can use the $(this) as well instead of $(item) object inside the callback as both refer to the same objects.
Another small suggestion is why do you want to mix vanilla JS and jQuery when jQuery is included and you want to use that in your application.
jsFiddle

Because .innerHTML isn't a jquery function. You can use .html() to achieve what you are trying to do. Alternatively, if you REALLY want to use .innerHTML, you can use .get() to get the actual DOM element, and then use .innerHTML but... I wouldn't recommend it.
I believe this edited fiddle solves your problem. Relevant code:
$('#showLessHours span.day').html(weekday[today]);
//...
if(item.html() != '') {
alert('item.text:' +item.text());
alert('weekday[today]'+item.text().indexOf(weekday[today]));
if(item.html().indexOf(weekday[today])!=-1) {
//...

In addition to what Sushanth said, you are also trying to invoke jQuery methods on javascript objects.
item.addClass
should by
$(item).addClass

Related

How to pass a variable to a function inside JQuery

I have something like this:
for (var i = 1; i <= numPages; i++)
{
buttons.append($("<button onclick='getJSON(i)'>"+i+"</button>"));
}
Now, passing i inside getJSON() function doesn't seem to work.
Any ideas how to solve this?
Other answerers already have described how you can do this.
However, I would recommend another way:
for (var i=1; i<=numPages;i++)
{
$("<button/>")
.addClass('myClass')
.attr('data-my-id', i)
.text(i)
.appendTo(buttons);
}
$(document).on('click', '.myClass', function() {
getJSON($(this).attr('data-my-id'));
});
It will generate the following HTML:
<button class='myClass' data-my-id='1'>1</button>
<button class='myClass' data-my-id='2'>2</button>
<button class='myClass' data-my-id='3'>3</button>
<button class='myClass' data-my-id='4'>4</button>
etc.
Why is this approach better?
Button is now generated using jQuery, but not from a string, which decreases a chance of error
It uses jQuery events instead of onclick attribute
Event delegation for convenient work with dynamically created elements
Element HTML doesn't contain behaviour (event) - it stores data (id)
jQuery is slower than a native JavaScript, but it is important only if we talk about thousands of elements. Otherwise, it is more important that code can be easily written, read and supported.
Also, here is a good article which describes why you shouldn't use onclick attribute`:
jQuery.click() vs onClick
buttons.append($("<button onclick='getJSON("+i+")'>"+i+"</button>"));
You need to concatenate is properly, the way you did for another i
Pass i to the getJSON method as a variable. You have sent it as a string by mistakenly.
for (var i=1;i<=numPages;i++)
{
buttons.append($("<button onclick='getJSON("+i+")'>"+i+"</button>"));
}

Updating jQuery from 1.8 to 1.11 <a> tag not getting appended

I am trying to update this javascript code from 1.8 to 1.11, and I am having issues. The following code used to work in 1.8, but now it only half works (without errors).
I have the following function:
function selectCountry(c_id){
var obj = $('#country a[data-index=' + c_id + ']');
if(obj.hasClass('cselect'))
return;
var clone = obj.clone();
var div = $('<div class="keyword-box"></div>');
var remove = $('×');
clone.after(remove).appendTo(div);
div.prependTo('#selected_country');
obj.hide().addClass('cselect');
return false;
}
What it used to do is create a div like this:
<div class="keyword-box">
Albania
×
</div>
But now it is creating a div like this:
<div class="keyword-box">
Albania
</div>
I am not sure why the second a tag isn't getting added to the div any more. Can anyone see why this is happening?
There's been a change in jQuery at version 1.9
Prior to 1.9, .after(), .before(), and .replaceWith() would attempt to
add or change nodes in the current jQuery set if the first node in the
set was not connected to a document, and in those cases return a new
jQuery set rather than the original set. This created several
inconsistencies and outright bugs--the method might or might not
return a new result depending on its arguments! As of 1.9, these
methods always return the original unmodified set and attempting to
use .after(), .before(), or .replaceWith() on a node without a parent
has no effect--that is, neither the set or the nodes it contains are
changed.
In your case you can just change
clone.after(remove).appendTo(div);
to
clone.add(remove).appendTo(div);
or
div.append(clone, remove);
I think your code would be much more readable if you would add the links like this:
div.append(clone);
div.append(remove);
div.prependTo('#selected_country');
The .after() API changed in jQuery 1.9. Using it in your case now has no effect. I think you should probably create the <div> and explicitly append both <a> elements individually to it.
So:
var div = $('<div class="keyword-box"></div>');
var remove = $('×');
remove.appendTo(div);
clone.appendTo(div);

Finding $(this) after a function

So here's my problem: I'm using a function and I need the function to be specific to each tr with the class "middleone". It's supposed to change the insides of a div inside of the the tr with the class "middleone". But it's not working!
I know the recursive portion of it is working, and the "navigation" should be spot on, because even when i'm using just $(this) it doesn't do anything. When using document.getElementById it works fine but of course that only targets the first div and the full version of the code has to "Go here, pull from here, put it here, go to the next area, pull from here.. etc" Here's the testing code.
$('.middleone').each(function() {
var tripleeagain = $(this).find('div')
tripleeagain.innerHTML = "$";
});
Thanks for any help
tripleeagain is a jquery object collection upon which you should use html() instead of innerHTML
Basically you could just write:
$('.middleone').find('div').html("$");
If you are doing specific stuff inside the loop then:
$('.middleone').each(function() {
//Some specific logic
var tripleeagain = $(this).find('div').html("$");
});
The problem is you are trying to access native API from a jQuery object.
var tripleeagain = $(this).find('div');// this will return a jQuery object
So you should use the jQuery API for setting the html contents
tripleeagain.html("$");
jQuery html API documentaion

selectmenu ('refresh', true)

I get form from zend framework site and put it in response in new file in function written by jquery mobile, but I get this error:
uncaught exception: cannot call methods on selectmenu prior to
initialization; attempted to call method 'refresh' .
Code of function this file:
function addItem(id) {
$.ajax({
url:'http://zf.darina.php.nixsolutions.com/order/index/create-order-mobile',
dataType:"jsonp",
data:{id_good:id},
success:function (resp) {
console.log(resp);
$('.product-table').empty();
$('.product-table').append(resp.prod);
$('.product-table').append(resp.form);
$('.add-order-btn').button();
$('.mob-size').selectmenu('refresh', true);
$('#block').page();
}
})
}
Force initialize the selectmenu(s) first:
$('.mob-size').selectmenu(); // Initializes
$('.mob-size').selectmenu('refresh', true);
or use this for short
$('.mob-size').selectmenu().selectmenu('refresh', true);
In my case, if I was not initializing the select before invoking the 'disable' method I got the error, while if I was initializing it, the select didn't disable but duplicate itself - I tried to select the object by TAG NAME instead of by CLASS or ID NAME,
$('select').selectmenu('disable');
instead of
$('.select-class-name').selectmenu('disable');
and it worked without forced initialization
you do this in your custom refresh delegation function:
var w = $("#yourinput");
if( w.data("mobile-selectmenu") === undefined) {
// not initialized yet, lets do so
w.selectmenu();
}
w.selectmenu("refresh",true);
according to enhancement resolution here
I found the same problem, but a more involved solution. When jqm wraps the select element, it puts it in a <span> element with the same class list as the select element. I changed my reference to it so that instead of reading:
row.find(".selectCompletion").selectmenu("disable");
it now reads:
row.find("select.selectCompletion").selectmenu("disable");
Specifying that jquery should only find the select element matching the class name, rather than all elements in .row that match the class name, solved the problem.
This happened to me when cloning existing select element in order to duplicate the original section multiple times.
Calling 'refresh' for the original element, worked fine, while calling it for the cloned sections was leading to the error appearing in the question.
However, calling selectmenu() was causing a 'vandalisation' to the form, as can be seen in the following image:
Explanation: top = original. bottom = vandalised cloned element right after calling selectmenu.
Solution:
The following code solved this vandalisation problem:
cloned_elem.find('select[name=MyClass]').selectmenu().selectmenu("destroy").selectmenu();
This is not an ideal solution because we must call the first selectmenu() in order to call selectmenu("destroy"), so I would be glad to hear of a cleaner solution.

jQuery load issue. Don't know how to approach this AJAX call

$("[littleBox]").load("ajax.php?eid="+$(this).attr("littlebox"));
the $(this).attr("little box") portion of the code returns undefined.
I'm trying to get the individual attribute of the initial $("[littleBox]").
this particular line of code is called as the soon as the document is ready.
when I put predefined values, such as
$("[littleBox]").load("ajax.php?eid=1");
It works as expected. Unfortunately, I need it to load specific content based on that element's attribute. Any idea how to make this work?
Loop through all items with proper this:
$("[littleBox]").each(function() {
var $this = $(this)
$this.load("ajax.php?eid="+ $this.attr("littlebox"));
});
this will not refer to $("[littleBox]") in that context, you'll have to repeat the selector - or select the element already and re-use it:
var $box = $("[littleBox]");
$box.load("ajax.php?eid=" + $box.attr("littlebox"));
post yout html that cotnain attr "little box" in it.
is it like
<a attr="little box" id="test">test<a/>
then it work like
$('#test').click(function(){
alert($(this).attr('little box'));
});

Categories