Get value of dom element in ready function - javascript

I want my textArea to resize when the page is fully loaded. I found that
$(document).ready(function() {
// Handler for .ready() called.
});
can help me, so I try to test it and put next code into that function:
$(document).ready(function() {
var element = $('#elementId');
alert(element.value);
});
But when the page is loading, alert shows undefined value of textArea, however there is text inside it.
How can I fetch those value inside ready function?

$(document).ready(function() {
var element = $('#elementId');
alert(element.val());
});

element isn't a DOM element but a jQuery wrapped object, it doesn't have any value property.
Use
$(document).ready(function() {
var element = $('#elementId');
alert(element.val());
});
or
$(document).ready(function() {
var element = document.getElementById('elementId');
alert(element.value);
});
or
$(document).ready(function() {
var element = $('#elementId');
alert(element.get(0).value);
});

You need to use DOM object to use value property and you have jQuery object you need to use val() on it.
$(document).ready(function() {
var element = $('#elementId');
alert(element[0].value);
//or
alert(element.val());
});

Related

Can't get cloned element to keep originals events

I'm trying to clone an element that is passed into a function and all events associated to it, as there are $('.example').on('click', function(e) ... )} events like this defined in document ready.
So I do following:
$('.example').on('click', function(e) {
e.preventDefault();
surpriseMe($(this));
});
and I try to clone this element along side its events here (I need to grab parent as .html() returns only inner html, hence element itself) :
function surpriseMe(element) {
var newElement = element.parent().clone(true,true).html();
surprise.insertBefore(element.parent());
if (numElements == 3) {
newMonth = $('<li class="item-dragable-placeholder">'+ newElement +'</li>
}
}
I believe true, true inside .clone() should force parent also grab its children events, but whenever I click on newly placed element, nothing happens
To use event delegation...
Change:
$('.example').on('click', function(e) { ...
To:
$(document).on('click', '.example', function(e) { ...
Note: Instead of using document, find the closest ancestor element (container) that's available on page load and use that.
when you do your insert, instead of inserting the new element, you ask to insert only the html, remove the html part, it will give you the element and its functionalities.
var newElement = element.parent().clone(true,true).html();
See the following (example)[http://jsfiddle.net/dshun/1j9khfnc/4/](please note, since the example code given is not complete. For example, the variable surprise, numElements are not declared. I made some assumptions in my fiddle)
$(document).ready(function(){
var numElements=0;
function surpriseMe(element) {
var newElement = element.parent().clone(true,true);
newElement.insertBefore( ".inner" );
numElements++;
if (numElements == 3) {
newMonth = $('li.item-dragable-placeholder').insert(newElement);
}
}
$('.example').on('click', function(e) {
e.preventDefault();
surpriseMe($(this));
});
});

JQuery get attribute from HTML element var

I have the following Jquery code:
$(function () {
$("div[id$='xxx']").click(function ()
{
$('.greenBorder').each(function (i, obj)
{
});
});
});
When a DIV called xxx is clicked, each HTML img with a class of greenBorder is iterated through. I would like to access the src attribute of each img. I can't figure out how to pull this value out. The obj function parameter contains the HTML element object, but how do I get the value out of that object? If this were C/Java/C#, I would cast it.
In the jQuery each function, you can access the current element with this. You can then jQuery select the element using $(this), and read the attribute with $(this).attr("src").
Example:
$(function () {
$("div[id$='xxx']").click(function ()
{
$('.greenBorder').each(function (i, obj)
{
console.log($(this).attr("src"));
});
});
});
Alternatively, you could use obj in place of this. You could also read the src attribute with this.src or obj.src.

Adding an Event via jQuery to newly created DOM Element

I am trying to assign an event to a newly created DOM Element:
var Element = document.createElement("div");
$(document).on('click',Element,function() {
console.log("B");
});
After executing this code and clicking on the newly created div, nothing happens.
Any idea why?
I have also tried:
var Element = document.createElement("div");
$(Element).click(function(event) {
console.log("B");
});
You need to add the element to the DOM before it will receive events.
Here's one way to do it:
var $div = $('<div>')
.text('Click Me!')
.on('click', function() {
alert('Clicked!');
});
$(document.body).append($div);
// Now you can click on it and see the alert.
Since you're using jQuery...
var Element = $("<div/>").click(function() {console.log("B");}).appendTo('body');
Of course, append it where you need it...
Just bind your event on the body and pass your selector in parameter like this:
$('body').on('click','.foo',function() {
console.log("B");
});
var Element = document.createElement("div").className = "foo";
Here the codepen :
http://codepen.io/anon/pen/xvLqo

Jquery $(this).val(); on .ready not working

I'm trying to get the value of a dropdown's option (there is an id on the select markup), when opening the web page
Using
$(document).ready(function() {
$('#cat_list').ready(function(){
var category = $(this).val();
alert(category);
});
});
I get a blank alert.
But Using .change (when selecting something else inside the dropdown) the following code works perfectly with the same function
$(document).ready(function() {
$('#cat_list').change(function(){
var category = $(this).val();
alert(category);
});
});
Finally, this works using basic javascript and it gets successfully the values on open, refresh, on form submit fail, ... etc
$(document).ready(function() {
$('#cat_list').ready(function(){
var e = document.getElementById("cat_list");
var category = e.options[e.selectedIndex].value;
alert(category);
});
});
Thanks for any help on why the first version .ready + $(this).val(); fails
Correct code is:
$(document).ready(function () {
var category = $('#cat_list').val();
alert(category);
});
$(document).ready itself means the whole document (including #cat_list) is ready to be processed. why are you checking if an element is ready or not!!??
you can directly use the value of the element like
$('#cat_list').val();
The documentation says that .ready:
Specify a function to execute when the DOM is fully loaded.
And 3 possible usage cases are:
$(document).ready(handler)
$().ready(handler) (this is not recommended)
$(handler)
However you can actually assign .ready to any element and it will be triggered:
$('#cat_list').ready(function(){
});
This code is fired. BUT this inside .ready function always refers to document.
It will work this way:
$(document).ready(function() {
$('#cat_list').ready(function(){
var category = $('#cat_list').val();
alert(category);
});
});
But actually your code is overengineered:
$(document).ready(function() {
var category = $('#cat_list').val();
alert(category);
});

Is there an easier way to reference the source element for an event?

I'm new to the whole JavaScript and jQuery coding but I'm currently doing this is my HTML:
<a id="tog_table0"
href="javascript:toggle_table('#tog_table0', '#hideable_table0');">show</a>
And then I have some slightly ponderous code to tweak the element:
function toggle_table(button_id, table_id) {
// Find the elements we need
var table = $(table_id);
var button = $(button_id);
// Toggle the table
table.slideToggle("slow", function () {
if ($(this).is(":hidden"))
{
button.text("show");
} else {
button.text("hide");
}
});
}
I'm mainly wondering if there is a neater way to reference the source element rather than having to pass two IDs down to my function?
Use 'this' inside the event. Typically in jQuery this refers to the element that invoked the handler.
Also try and avoid inline script event handlers in tags. it is better to hook those events up in document ready.
NB The code below assumes the element invoking the handler (the link) is inside the table so it can traverse to it using closest. This may not be the case and you may need to use one of the other traversing options depending on your markup.
$(function(){
$('#tog_table0').click( toggle_table )
});
function toggle_table() {
//this refers to the element clicked
var $el = $(this);
// get the table - assuming the element is inside the table
var $table = $el.closest('table');
// Toggle the table
$table.slideToggle("slow", function () {
$el.is(":hidden") ? $el.text("show") : $el.text("hide");
}
}
You can do this:
show
and change your javascript to this:
$('a.tableHider').click(function() {
var table = $(this.name); // this refers to the link which was clicked
var button = $(this);
table.slideToggle("slow", function() {
if ($(this).is(':hidden')) { // this refers to the element being animated
button.html('show');
}
else {
button.html('hide');
}
});
return false;
});
edit: changed script to use the name attribute and added a return false to the click handler.
I'm sure this doesn't answer your question, but there's a nifty plugin for expanding table rows, might be useful to check it out:
http://www.jankoatwarpspeed.com/post/2009/07/20/Expand-table-rows-with-jQuery-jExpand-plugin.aspx

Categories

Resources