trouble with jQuery lifecycle - javascript

index.html:
<input type="text" id="inputs" name="inputs">
<input type="button" id="btnAdd" value="submit">
script.js:
(function() {
function myFunction(input) {
alert(input);
}
$('#btnAdd').click(myFunction($('#inputs').val()));
});
I'm having trouble getting my javascript to run when my button is clicked. I assume I am misusing the ready function or my page has yet to register the button, but I am unable to break at any linein the javascript when I debug the page. Can someone tell me the proper way to get this to function? Thanks.

Because of the way it's written, the code you provide for script.js would never run. You probably want to put your function into a call to jQuery so it gets executed when the DOM is loaded.
Also, you need to wrap your click callback inside an anonymous function, or else it will execute myFunction when you're trying to add the callback instead of on the actual click.
$(function() {
function myFunction(input) {
alert(input);
}
$('#btnAdd').click(function() {
myFunction($('#inputs').val())
});
});
https://jsfiddle.net/9du8rxw0/

you need to add callback to your click event and for $(document).ready(function(){ }) the short hand is $(function(){ }).and it is better to write custom functions outside of document ready.
$(function() {
$('#btnAdd').click(function() {
myFunction($('#inputs').val())
});
});
function myFunction(data) {
alert(data);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="inputs" name="inputs">
<input type="button" id="btnAdd" value="submit">

Adding a $ before your self-invoking function will tell jQuery to wait for the entire page, including your myFunction definition to load prior to execution.
like
$(function() {
function myFunction(input) {
alert(input);
}
$('#btnAdd').click(myFunction($('#inputs').val()));
});
then make sure either myFunction is declared in global scope, or better yet, wrap within your self-invoking function as well.

You need the $ in front of (function(), and your click function needs curly braces.
$(function() {
function myFunction(input) {
alert(input);
}
$('#btnAdd').click(function(){myFunction($('#inputs').val())});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<input type="text" id="inputs" name="inputs">
<input type="button" id="btnAdd" value="submit">

I'm guessing that the DOM is not yet loaded, and that your attempt to shorthand the call to .ready() is erroneous. Try prefixing with $:
Also, your event handler setup is not doing what you want.
// Need $ before your parens (shorthand for .ready())
$(function() {
function myFunction(eventData) {
alert(eventData.inputValue); // <-- get input value from eventData
}
// This is not proper usage of .click()
// https://api.jquery.com/click/
// $('#btnAdd').click(myFunction($('#inputs').val()));
// You want to pass the relevant eventData as the first param,
// and a reference to your handler in the second.
$('#btnAdd').click( { inputValue: $('#inputs').val() }, myFunction);
});
Although, if you don't need myFunction to be defined separately, you might be better off with #Gerasimos' suggestion.

Related

html button not calling its onclick js function

Why does this simple alert not work?
HTML:
<button id="mybutton" type="button" onclick="add()">Add</button>
JS:
function add(){
alert("hello???");
}
https://jsfiddle.net/k86mg0aj/
The problem is specific to JSFiddle. You need to change the LOAD TYPE to No wrap - bottom of <body>.
When using onLoad, the function won't become global one, so you can't invoke it directy from HTML. If it is global - like when using no-wrap - it works.
In my opinion the best solution for call a function in current times is to use ES6. You can create for example something like that:
var x = document.querySelector('.class');
x.addEventListener('click', function() {
});
x.addEventListener('click', () => {
});

onclick function need to execute a simple javascript function

I have a button where I am trying to add on click jquery as below
<button onclick="myFunction()">YES</button>
And
$(document).ready(function() {
function myFunction(){
$('#mycheckboxdiv').toggle();
$("div#headersteptwo").addClass("hidden");
}
})
However, on click I am getting Uncaught ReferenceError: myFunction is not defined
What am I doing wrong and how to fix this?
Updated with a sample jsfiddle
http://jsfiddle.net/3aC7W/1/
What am I doing wrong and how to fix this?
You are defining the function inside another function, i.e. the function is not defined in global scope and hence cannot be found by the inline event handler.
Just remove $(document).ready(function() { because you don't need it there:
function myFunction(){
$('#mycheckboxdiv').toggle();
$("div#headersteptwo").addClass("hidden");
}
You only have to use $(document).ready(function() { ... }); if you manipulate the DOM, and also only if you place the script before the elements in the HTML document.
The better solution of course would be to bind the event handler with jQuery (and not use inline event handlers):
$(document).ready(function() {
$('button').on('click', function(){
$('#mycheckboxdiv').toggle();
$("div#headersteptwo").addClass("hidden");
});
});
You might have to add a class or ID to the button to make the selector more specific. Have a look at the list of available selectors.
change your code to this way to achieve click :
<button id="myFunction">YES</button>
and
$(document).ready(function() {
$('#myFunction').click(function(e){
$('#mycheckboxdiv').toggle();
$("div#headersteptwo").addClass("hidden");
});
});
check it at: http://jsfiddle.net/aneesh_rr/XJ758/3/
change your code to this:
$(document).ready(function() {
window.myFunction = function(){ //you should make myFunction avaliable in global
$('#mycheckboxdiv').toggle();
$("div#headersteptwo").addClass("hidden");
}
})

javascript function does not work within jquery $(document).ready block

I am trying to call a JavaScript function from an onclick trigger.
HTML section:
<div class="my_radio">
<input type="radio" name="my_radio" value="1" onclick="my_func()"/> first button
</div><!-- end of class my_radio -->
And the JavaScript code
<script type="text/javascript">
$(document).ready(function(){
function my_func(){
alert("this is an alert");
}
});
</script>
It does not work.
But if i keep the JavaScript function out of the $(document).ready() code, it works. Following is the relevant code snippet:
<script type="text/javascript">
$(document).ready(function(){
function my_func111(){
alert("this is an alert");
}
});
function my_func(){
alert("this is an alert");
}
</script>
1) Why does not the first JavaScript code snippet work?
2) How can I get the first JavaScript code snippet working ?
EDIT :
SO FAR AS I KNOW, $(document).ready() is executed when the web page loads completely. So how can I prevent my_func() to be active before or after the complete page-loading if I write my_func() outside $(document).ready()?
It's all about javascript execution contexts and scope.
Everything that you define within a function is know only in this function.
In your first test, the function my_func() can only be used within the ready callback (and in the inner other objects). You can't reference it outside.
In your second example, the function my_func() is global to the document and accessible from anywhere.
I recognize this is maybe a verry simple explanation :-)
If you define your function within a callback, you can only use it within this callback:
$(document).ready(function(){
function something(){
alert('test');
}
//..
something(); // Will work
}
something(); // Won't work
Your first snippet doesn't work, because in in the function my_func111 is defined within the local scope of an anonymous function passed as an argument in your $(document).ready call.
You can fix your code by placing the function definition to the document scope and calling it inside ready function such as:
function my_func(){
alert("this is an alert");
}
$(document).ready(function(){
my_func();
});
I presume by "it does not work", you mean it says "my_func is not defined" or similar?
When you define a function within a function, the inner function is not visible outside of the outer function (unless it is part of the outer function's return statement).
You'll need to learn about closures, a good tutorial on which can be found here.
You'll add a global variable isReady. The $(document).ready callback section will change it to true.
Both your function and the isReady variable must be defined outside the callback of the $(document).ready, so that they can be seen from outside the scope of the callback.
<script type="text/javascript">
var isReady = false; // outside the onReady callback
function myFunc(){ // also outside the onReady callback
if (!isReady) return; // abort if not ready
alert("this is an alert");
}
// the onReady callback
$(function(){ // the newer jquery shorthand for: (document).ready(function(){
isReady = true;
});
</script>
Your HTML code needs no changes. - I changed the names to use JS and HTML conventions, but essentially it's the same as what you originally wrote...
<div class="divMyRadio">
<input type="radio" id="myRadio" value="1" onclick="myFunc()"/> first button
</div><!-- end of class divMyRadio -->
I
As a side note: The newer JQuery uses $(function(){ as shorthand for $(document).ready(function(){ to make things easier for you.

Why can't I use onClick to execute a function inside a jQuery $(document).ready function?

I'm new to JavaScript and jQuery. I want to click a button and have a js function executed. (For this example, it's just an alert, but it's actually an ajax function.)
The first alert appears, but after I click the button, I never see the second ("did it") alert. It looks like JavaScript doesn't think the doIt() function is defined when the button is clicked.
Here's the relevant code:
$(document).ready(function()
{
alert('ready');
function doIt() {
alert('did it');
};
}
)
<body>
<input name="Go" type="button" value="Go" onclick="doIt();"/>
</body>
It's because that function isn't in a global context, which is where your onclick="" is looking for it. You need to move it outside your document.ready (so it's not scoped exclusively to that closure), or (a better approach IMO) bind it inside the document.ready, here's what I mean by each:
Binding it inside (remove your onclick="" for this):
$(document).ready(function() {
alert('ready');
$("input[name='Go']").click(doIt);
function doIt() {
alert('did it');
}
});
or the anonymous version (again remove your onclick=""):
$(document).ready(function() {
alert('ready');
$("input[name='Go']").click(function() {
alert('did it');
});
});
Or move it outside (keep your onclick=""):
$(document).ready(function() {
alert('ready');
});
function doIt() {
alert('did it');
}
You define doIt in your document.ready as a function statement.
Either you should use a function expression
or declare the function out of the ready function.
$(document).ready(function()
{
alert('ready');
doIt = function() { //now has global scope.
alert('did it');
};
}
)
<body>
<input name="Go" type="button" value="Go" onclick="doIt();"/>
</body>
(yes, the onClick is not really the jQuery way of doing it and probably should be replaced by a click handler defined in the ready function, but it works and is allowed.
What you need to do is bind a "click" event to it using jquery like this.
jQuery(document).ready(function($) {
$('#my_button').click(function() {
alert('i was clicked');
});
});
<input type="button" id="my_button" value="Go" />
Here is a live jsfiddle demo for you: http://jsfiddle.net/8A5PR/
Here is the manual page for you: http://api.jquery.com/click/
Javascript has two kinds of scope, global, and function level. If you declare doIt inside a function, it will not be visible outside the function. There are a few ways to fix it
//just declare the function outside the ready function
$(function() {
});
function doIt() { alert('did it'); }
//decare a variable outside the function
var doIt;
$(function() {
doIt = function() { alert('did it'); }
});
// if you dont use var, variables are global
$(function() {
doIt = function() { alert('did it'); }
})
$(document).ready(function()
{
});
is an event handler for document.ready, the functions inside that handler are within that scope.
A better method is to insert a handler for your click event inside, then call that function there.
$(document).ready(function()
{
alert('ready');
$('body input').click(function(){
doIt();
});
function doIt() {
alert('did it');
};
});
This ALSO has the side effect of removing code from your markup (a good thing) in that you can remove that onclick from your input tag.
What you are doing right now is simply putting a function doIt() inside a (for all intents and purposes) window.onload event. This function will never get called outside of the document.ready unless you bind it to an element because it's stuck inside the scope of document.ready.
You need to move your function outside of the document.ready so it can be called by outside events.
Just a little link for reference: http://www.webdevelopersnotes.com/tutorials/javascript/global_local_variables_scope_javascript.php3
Try this...
$(document).ready(function() {
alert('ready');
$("#Go").submit(function(event) {
alert('did it');
});
});
<input name="Go" id="Go" type="button" value="Go" />
Yes, as mentioned by others you really need to move the function outside of the jquery ready declaration. Also please note that javascript is case sensitive, hence you should use onClick rather than onclick. Regards

jQuery dialog scripts for input val

I have a bit of a problem with a jQuery dialog and the way scripts are handled.
In the dialog html, I have
<input id="test">
If I do
<script type="text/javascript>
$('#test').val("haha")
</script>
after the input, it shows up. If I put it before, it doesn't work.
Now the problem is I'm trying to change the value of $('#test') using a click trigger, and I can't!
$('.testbutton').click(function() {
alert();
$('#test').val("haha");
});
The alert works, and the initial val replacement works, which means there aren't any duplicate or missing input areas.
The total script as it is now, not working:
<input type="button" class="testbutton" />
<input type="text" size="10" id="test" name="test" value="">
$('#test').val("currentvalue"); // This works
$('.testbutton').click(function() {
alert();
$('#test').val("haha");
});
Update
The dialog shows the correct value in #test once the dialog is closed and then reopened. Could this be something I'm missing?
Put your jQuery code into $(document).ready(function () {...your code...}). This will make it executed after browser creates DOM tree for your page. Otherwise javascript is not able to search/manipulate DOM elements correctly. It will look as following:
$(document).ready(function () {
$('.testbutton').click(function() {
$('#test').val("haha");
});
});
Update:
If your HTML code is loaded dynamically, then use live to bind event handler:
$(document).ready(function () {
$('.testbutton').live("click", function() {
$('#test').val("haha");
});
});
I guess you should wrap your code inside of a $(function() { //code here }); to make sure your code is run only when your DOM is ready.
The problem ended up being the # in test. For some reason the replacement works with a class identifier instead of a id identifier. I suppose it's because the # will replace only one instance, and for some reason that I have yet to discover, there is more than one instance of the dialog (or a hidden one).
Thanks for all your suggestions!

Categories