jQuery - calling a javascript function

11,378

Solution 1

I would say you don't really need jquery for this, but if you are dead set on using it, you should re-evaluate your logic here. Give your button an id first, you don't need it, but it's good to do it anyway:

<button id="btnClickMe">Click Me<button>

then, use that to trigger a jquery event on, thus calling your function:

$('#btnClickMe').click(function() { //You can either link directly to a func here
alert('Whatever'); //Or you can write the code for your func directly into the handler here
}); 

Solution 2

You could not pass callback function to text(). Call the hello method after changing the text.

Live Demo

Change

$("p").text("Hi", Hello());

To

$("p").text("Hi");
Hello();

Solution 3

If you only want to call Hello() from Initiate(), you simply call it as follows:

function initiate()
{

    Hello();
}
Share:
11,378
frrlod
Author by

frrlod

Updated on June 04, 2022

Comments

  • frrlod
    frrlod almost 2 years
    function initiate()
    {
    
        $("p").text("Hi", Hello());
    }
    
    function Hello()
    {
        alert("Hello, you have called another function");
    }
    

    HTML:

    <p>This is a paragraph.</p>
    <p>This is another paragraph.</p>
    <button onclick="initiate()">Click me</button>
    

    Right now the script calls the function initiate() upon the button click, and then the other function, Hello() is called, while changing all paragraphs in the html to "Hi".

    What I would like is that the function Initiate() will call the function Hello() using jQuery, and do nothing else.

    (In other words, how do I simply call a function using jQuery?)

  • James Hill
    James Hill about 11 years
    He doesn't just want to call Hello, he wants to set the text on a paragraph to Hi as well.
  • frrlod
    frrlod about 11 years
    This is what I'd like to do, just with jQuery. is that possible?
  • frrlod
    frrlod about 11 years
    That doesn't seem to work for me, it doesn't call the function Hello() - what I would like is to call the function without having to change the <p> elements.
  • Evan Knowles
    Evan Knowles about 11 years
    I'm confused, do you want to set the text on the paragraph? If so, what was wrong with the initial code? Otherwise, jQuery is in javascript, so you can use normal javascript syntax within jQuery.
  • Ja͢ck
    Ja͢ck about 11 years
    +1. Exactly what OP wants: "the function Initiate() will call the function Hello() using jQuery, and do nothing else."