Workaround for passing parameter to jQuery ready() - javascript

I have some code called on jQuery document.ready() which is used in multiple HTML files. Now the difference is each of these HTMLs uses a different div id.
I know one option is to just check for hardcode div ids inside $(document).ready() . But I wanted to write a generic code which would take the div Ids based on the currrent/calling HTML page?
So is there any way or workaround for passing parameter to jQuery ready() ?

$(document).ready() just wants a function as an argument so you can write a function that takes your ID as an argument and returns a function for $(document).ready(). For example, instead of this:
$(document).ready(function() {
$('#some_id').click(/*...*/);
});
you could do this:
function make_ready(id) {
return function() {
$('#' + id).click(/*...*/);
};
}
$(document).ready(make_ready('some_id'));
Then you could put your make_ready in some common location and use it to build the functions for your $(document).ready() calls.

document ready just takes in an handler function as a parameter.
You can still define a generic code in you document ready function, by storing the current div id for each html.
<input type="hidden" id="current_div" value="div1" />
$(document).ready(function() {
var div_id = $('#current_div').val();
// generic code
});

Related

Calling click functions inside a main function

I just wanted to know about any downsides to calling click functions inside a main function rather than in the $(document).ready(function() {});. This is what i mean
function tester() {
$('.className-1').click(function() {
var cmtpid = $(this).attr('data-cmtpid');
alert(cmtpid);
});
$('.className-2').click(function() {
var pid = $(this).attr('data-pid');
alert(pid);
});
}
tester();
UPDATE : the tester() function will only be called once, this is all mainly because I want to avoid inline html onclick=""
Since I noticed you're using jQuery. Perhaps consider adding unbind("click") after the selector to ensure you don't accidentally bind the click more than once causing multiple executions upon click.
Also there isn't any REAL downside but I would HIGHLY recommended putting that java-script at the very end of your html document to ensure the DOM is loaded.
Example:
$('.className-1').unbind("click").click(function(){
});

Javascript - $(this).on

Why it can retrieve the "modelValue" when inputText changed ?
Who can describe the flow of this script ?
Thanks
//js預載入
$(document).ready(function() {
console.log("ready!");
var iepValues = $('body').find('[model-value]');
$.each(iepValues, function() {
var modelValue = $(this).attr('model-value');
console.log("display");
//Why it can retrive the "modelValue" when inputText chagned ?
$(this).on('change', function() {
console.log("modelValue:" + modelValue);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body>
TEST1:
<input type="text" id="TxtTest1" model-value="A">TEST2:
<input type="text" id="TxtTest2" model-value="B">
</body>
Why it can retrieve the "modelValue" when inputText changed ?
Because the function hooked up with $(this).on('change', function() { ... }); is called when the value of the input changes, and that function closes over (has access to) the modelValue variable in context where it was created.
Who can describe the flow of this script ?
It calls jQuery's ready function, passing in a function to call when the DOM is ready. All of the rest of the code is in that callback.
When the DOM is ready, jQuery calls the callback.
The code logs "ready!" and the finds all elements inside body that have a model-value attribute. [Side Note: $('body').find('[model-value]') can more concisely and efficiently be written $('body [model-value]').]
The code loops through all of those elements using $.each, calling a callback function for each of them.
Inside that callback, the code grabs the value of the model-value attribute and stores it in a variable. There will be a different variable for each of the elements, each variable contained by the context of the call to the callback from $.each.
Code in each of those callbacks hooks up a handler for the change event of that element.
The handler responds to the change event by logging the value of the modelValue variable.
Recommended reading:
The jQuery API
How do JavaScript closures work?
JavaScript closure inside loops – simple practical example
If the element's model-value attribute is going to change, that code will log the value it had when the DOM was ready, not the value it has when the value of the input changes. That would seem to be the point of the code.
If the model-value attribute doesn't change, then the code is unnecessarily complicated, and could just be:
$(document).ready(function() {
console.log("ready!");
$('body [model-value]').on('change', function() {
console.log("modelValue:" + $(this).attr('model-value'));
});
});
Or even:
console.log("ready!");
$('body [model-value]').on('change', function() {
console.log("modelValue:" + $(this).attr('model-value'));
});
If you move the script tag to the bottom of the HTML, just before the closing </body> tag.
But again, that's if the model-value attribute doesn't change, or if you want to see the changed value instead of the original value. The original code will show you the original, not changed, value of the attribute.

calling a jQuery function from another JavaScript function

I want to databind a gridview on a button click event. so that i am going to add a jQuery function for databind. but that function should be called inside a JavaScript function.
like this,
function btnclick() {
//code
//here i want to call the databind function
}
$(function () {
//code
}
this is just my assumption. i don't know how to combine jQuery function and JavaScript function. any suggestion?
You can simply call the function as you call in javascript function. its quiet simple.
$(document).ready(function() {
$("#btn").click(function() {
databind();
});
});
function databind(){
//your code
}
you can bind the jquery event or use jquery inside a javascript function like this:
function btnClick(){
$("yourelement").bind("eventyouchoose",function(e){
//task to do in when the event is called
});
//perform actions using jquery in the similar way
}
Hope this helps
jQuery is simply a library written in JavaScript, so you can freely call JS/jQuery methods in any scope where they are loaded.
I'm not sure what you meant with your code sample, but a common way to perform an action on click would be with the jQuery click() method like so:
function databind() {
// some kinda magic
}
// pass your previously defined databind function as the callback
$('some-selector').click(databind);
You need to specify a selector to target the clickable button.

How to get the form of an element in jQuery

I have a javascript function that runs quite nicely from html
'onClick="my_function(this.form)"
but I also want to call this function if a specific element within the form has data keyed in I have tried
jQuery(document).ready(function($){
$('#option_field_bizpostcode').keyup(function() {
var myform = $(this).closest('form').options-i-have-tried();
my_function(myform);
});
});
options-i-have-tried() include html() (and that shows that I have html inside of the correct form ok),
get() a bit of a stab in the dark,
serializeArray() from some answers to similar questions,
and nothing at all.
In each case my function complains that its argument form, or more specifically form.myelement is undefined
Many thanks in anticipation
Well your passing the FORM Element into the function in the inline handler (onclick attribute) so you need to do the same with the jQuery handler.
jQuery(document).ready(function($){
$('#option_field_bizpostcode').keyup(function() {
var myform = $(this).closest('form')[0]; //because the form element is at the first index in the jquery object
my_function(myform);
});
});
OR even better, why don't you just stick to doing this:
jQuery(document).ready(function($){
$('#option_field_bizpostcode').keyup(function() {
my_function(this.form);
});
});
I think you should be passing myform not form
this in a jQuery callback will be the element where the handler is attached. It is the native DOM element, without any jQuery wrapper.
So presuming that #option_field_bizpostcode is a form element, you should be able to do this.form just as you would in the onclick method.
my_function(this.form);
I think if you use the first element from the closest call you will be successful:
$('#option_field_bizpostcode').keyup(function() {
var myform = $(this).closest('form')[0];
my_function(myform);
});

Passing 'this' as parameter in JavaScript

I have the following code:
HTML:
<label id="copyAddress" class="copyAddress" onclick="CopyAddress(this);">
Copy Address
</label>
JS:
function CopyAddress(copyAddressLink) {
PopulateTarget(copyAddressLink);
}
function PopulateTarget(link) {
var targetGroup = $(link).closest('someClass');
}
In PopulateTarget function 'link' variable is undefined, while in CopyAddress it has values as is should.
What can cause this problem? Is there some restriction for passing parameters in Java Script? How this should behave? If you need more code to post please tell me.
Since you are anyhow using jQuery, why are you using obtrusive Javascript?
Use this instead:
HTML:
<label id="copyAddress" class="copyAddress">Copy Address</label>
Javascript:
$(document).ready(function(){
$('#copyAddress').click(function(){
var targetGroup = $(this).closest('.someClass');
});
});
You're missing a dot on "someClass", it should be ".someClass".
Maybe your code will work after you fix that. However: since you're using jQuery (it seems you are), you should attach the click handler the jQuery way, instead of inline on the HTML. This means:
$(document).ready(function(){
$('#copyAddress').click(CopyAddress);
})
function CopyAddress() {
PopulateTarget(this);
}
function PopulateTarget(link) {
var targetGroup = $(link).closest('someClass');
}
You should not intermix your HTML and JS. You should instead attach your JS handlers programmatically in your JS code:
<!-- note: no onclick in this html -->
<label id="copyAddress" class="copyAddress">Copy Address</label>
// Wait until the page is loaded before starting to look for elements
$(function(){
// Assuming jQuery 1.7
$('#copyAddress').on('click',copyAddress);
// …alternatively, for older jQuery
$('#copyAddress').click(copyAddress);
function copyAddress(evt){
// The 'target' property of the event object passed in is the object
// upon which the event was first triggered.
PopulateTarget(evt.target);
}
});
In the case of the above, you could just use this instead of evt.target, since you bound the event directly on that object. However, this becomes more powerful if you have a variety of items on the page that perform this function. You can attach the event handler once to some parent object, and then ask—during the callback—which element was clicked on. That would look like:
// Watch for any element with a copyAddress class to be clicked on,
// even if they are added after this code has run
$(document.body).on('click','.copyAddress',function(evt){
var target = evt.target;
console.log("You clicked on",target);
});
As it seems you are using jQuery:
You can use jQuery.proxy to bind this to a specific value. It is used like this:
jQuery.proxy(function () { console.log(this); }, this);

Categories

Resources