How can I get a #<HTMLDivElement> as a jQuery object?
I need to do the following: I have a list of div's with the class contents. So I iterate over it until I find the one with the additional class: "test"
here is my code:
$.each( $(".contents"), function( key, value ) {
if (value.hasClass("test"))
{
alert("got it");
}
});
I'm getting the exception: Uncaught TypeError: Object #<HTMLDivElement> has no method 'hasClass'
The each() function gives you DOM object and you have to convert it to jQuery object. You can pass value to $ jQuery function to convert it to jQuery object.
$.each( $(".contents"), function( key, value ) {
if ($(value).hasClass("test"))
{
alert("got it");
}
});
You do not need to iterate through each and simplify it like
elements = $(".contents.text")
Why not to do it simpler with:
$(".contents.test"). ...
Here jQuery will select element that has both "contents" and "test" classes set.
DEMO: http://jsfiddle.net/xfErG/
The main jQuery function can accept a DOM Element as its argument.
var foo = jQuery(HTMLElementNode);
The following two lines of code have the same end result:
var foo = jQuery('#foo');
var foo = jQuery(document.getElementById('foo'));
Related
I would like to pass the form.find element to my function AvailabilityChecker. I tried to get the elements Attribute with no success. Whats wrong?
var AvailabilityChecker = function (ev, el) {
console.log("arguments: ",Array.prototype.slice.call(arguments)); //gives: arguments: Array [ Object ]
console.log(ev);
console.log("AvailabilityChecker: ",el.attr('AvailabilityChecker') //gives Typeerror
}
form.find("input[AvailabilityChecker]").keyup(AvailabilityChecker.bind(this));
The el is not going to be an attribute magically appended as an argument. So you need to do it another way. And using .bind() is also changes how you can get the element reference
var AvailabilityChecker = function (ev) {
console.log("1-DOM", ev.target.getAttribute("AvailabilityChecker"))
console.log("1-JQ",$(ev.target).attr("AvailabilityChecker"))
}
$("input[AvailabilityChecker]").keyup(AvailabilityChecker.bind(this));
var AvailabilityChecker2 = function (ev) {
console.log("2-DOM", this.getAttribute("AvailabilityChecker"))
console.log("2-JQ",$(this).attr("AvailabilityChecker"))
}
$("input[AvailabilityChecker]").keyup(AvailabilityChecker2);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input AvailabilityChecker="aaaa">
My jQuery code is:
$('#edit').click(function(){
var data = $("#list :input").serialize();
$.post($("#list").attr('action'), data, function(json)
{
currentRow = json.rowArr[0];
$("#id").val(currentRow.id);
$("#id_disp").val(currentRow.id);
$("#shop").val(currentRow.shop);
$("#category").val(currentRow.category);
$("#item").val(currentRow.item);
$("#qnty").val(currentRow.qnty);
$("#unit").val(currentRow.unit);
$.each($("#price_based_on").children('option'), function(index, val) {
if(this.value.toUpperCase()==currentRow.price_based_on.toUpperCase())
{
console.log("Match");
this.prop("selected", true);
}
});
$("#mrp").val(currentRow.mrp);
$("#sellers_price").val(currentRow.sellers_price);
$("#last_updated_on").val(currentRow.last_updated_on);
},"json");
});
Among this, the only thing of interest are the lines:
$.each($("#price_based_on").children('option'), function(index, val) {
if(this.value.toUpperCase()==currentRow.price_based_on.toUpperCase())
{
console.log("Match");
this.prop("selected", true);
}
});
On using the statement this.prop("selected", true); I get the error:
Uncaught TypeError: this.prop is not a function
Why does this happen when .prop() is clearly a function that exists? How do I fix it?
$.each is used to iterate over an object or array. If you want to iterate over the nodes in a jQuery object, use .each like this:
$("#price_based_on").children('option').each(function() {
... code here
});
Inside the call back, this refers to the native DOM element (which doesn't have a prop method, so you probably want to do something like this to get a reference to the jQuery object that holds the DOM node:
$("#price_based_on").children('option').each(function() {
var $this = $(this);
$this.prop('selected',true)
});
this is not a jquery object, you need to add jquery selector $() around to make it jquery object, so change it to $(this).
this is not a jQuery object. Use $(this)
$(this).prop("selected", true);
Is it possible to store the reference to an element in an array or object without having a unique ID on the element?
I am having trouble with storing a subtable in another table so I can reference it later. I get the table by class with this code:
$(this).parent('tr').parent().find('.tableSomeTable');
Is the only solution to have unique id's on each element and use the .selector method?
More of my code. Abit simplified.
var rows = [];
var historyLoad;
$(document).on("click", '.details-control', function (e) {
var t = $(this);
var tr = t.closest('tr');
var row = t.parent().parent().parent().DataTable().row(tr);
var id = t.closest('tr').attr('id');
var object = {
id: id,
btnHistory: t.parent('tr').next().find('#btnHistory'),
tblHistory: t.parent('tr').parent().find('.tableHistory'),
historyLoad: historyLoad
};
if ($.inArray(id, rows) > -1) {
loadData = false;
}
else {
loadData = true;
loadHistory(object);
rows.push(object);
}
};
Here is where I am having trouble retrieving the correct elements. And I also want to save the ajaxHistory element to my object (which is working fine).
This code is not working, but if I change it to $(result.btnHistory.btnHistory.selector) I get the object. But this doesn't seem to work very good with multiple rows.
function loadHistory(result) {
result.ajaxHistory = $.ajax({
...
beforeSend: function () {
$(result.btnHistory).html(<loading txt>);
$(result.tblHistory).find('tbody').html(<loading txt>);
},
....
success: function (data) {
if (data.TotalRecordCount > 0) {
$(result.tblHistory).find('tbody').html('');
$.each(data.Records, function (e, o) {
$(result.tblHistory).find('tbody').append(<data>)
});
}
else {
$(result.tblHistory).find('tbody').html(<txt no records>);
}
$(result.btnHistory).html(<txt loading done>));
},
First off, if you are trying to find the parent table, try
var $myObj = $(this).closest('table.tableSomeTable');
instead of navigating parents.
As far as storing the jQuery reference, define a variable and then store it. The above will store the object in $myObj but that is locally scoped. If you need a global variable then define it globally and just assign it here. If you want to define it as a property within an object then define it that way. It really comes down to a scope question at this point.
EDIT: Just saw your added content.
First off, don't name it 'object'. This may run into key word issues. Use var myObj or similar instead. Next, object.btnHistory is a reference to a jQuery object. So, when you pass it to loadHistory, you do not need to apply the $(...) again. Just use the reference directly: result.btnHistory.html(...). A good habit to get into is prepending you jQuery variables with $ so you remember it is already a jQuery variable.
The .find() method returns a jQuery object. So the answer is, yes, you can store this return object in a variable:
var $yourObject = $(this).parent('tr').parent().find('.tableSomeTable');
I want to call jquery plugin function from my page, but I fail:(. My code is:
var pstps=$('#psteps_simple_horiz_layout').psteps({
steps_width_percentage: true,
alter_width_at_viewport: '1300',
steps_height_equalize: true
});
step_num=2;
pstps.go_to_step(step_num);
The plugin is Pine Steps wizard. It's code is:
function($) {
$.fn.psteps = function(options) {
// Build main options before element iteration.
var opts = $.extend({}, $.fn.psteps.defaults, options);
// Iterate and transform each matched element.
var all_elements = this;
all_elements.each(function(){
var psteps = $(this);
psteps.psteps_version = "0.0.1alpha";
.......................................................
psteps.go_to_step = function(step_num){
var last_active_title = psteps.find('.step-title.last-active'),
.......................................................
};
.......................................................
this.pines_steps = psteps;
});
return all_elements;
};
When I run my code I get error:
Uncaught TypeError: undefined is not a function
It is failing on the following line because go_to_steps is not a jQuery extension (and the return value from psteps() is the original jQuery object:
pstps.go_to_step(step_num);
You need the instance of the actual plugin. Looking at the plugin code, it connects the instance as a property on the DOM element called pines_steps, so you need to get that property as your class instance:
var pstps=$('#psteps_simple_horiz_layout').psteps({
steps_width_percentage: true,
alter_width_at_viewport: '1300',
steps_height_equalize: true
})[0].pines_steps;
Then you can call
pstps.go_to_step(step_num);
Common pattern:
The usual way plugins are authored is to also accept a function name, as a string, in a first parameter, so they can call methods like this:
$('#psteps_simple_horiz_layout').psteps("go_to_step", step_num);
however this plugin is missing the code to do that
I have a constructor which I then make the object library_science1 with:
function librarytech(humanity,food,wood,metal,wealth)
{
this.humanity=humanity;
this.food=food;
this.wood=wood;
this.metal=metal;
this.wealth=wealth;
}
var library_science1=new librarytech(0,200,200,0,0);
I have this as a click function:
$("[id^='library_']").click(function() {
var idd = this.id;
alert(idd);
});
where the html is simply
<span id='library_science1'></span>
The code above works fine, alerting 'library_science1' nicely... it even works when I use the alert to directly pull one of the objects properties.
$("[id^='library_']").click(function() {
alert(library_science1.food);
});
But I have many library_[SOMETHING] objects, corresponding each to there own
<span id="library_[SOMETHING]"></span> line.
I'm trying to pull the objects properties depending on which one is clicked. Such as:
$("[id^='library_']").click(function() {
alert(this.id.food);
});
or
$("[id^='library_']").click(function() {
var x = this.id;
alert(x.food);
});
The end purpose being that I can ultimately do things like:
foodamount -= this.id.food
Why isn't this working :/ :(
simply because you are accessing an object in your first example and not a DOM object as in other, if their obejtos are global so you can access
alert(window[this.id].food);
or
alert(eval(this.id + ".food"));
I made a test here using eval() and this works:
$("[id^='library_']").click(function() {
alert(eval(this.id).food);
});
$("[id^='library_']").click(function() {
var x = eval(this.id);
alert(x.food);
});