1

This might be very basic but I couldnt really find a solution to this. I am creating my own website. I have written a javascript file, simply called "main.js".

I can call my entire script in my HTML file like so:

<script src="main.js"> 
</script>

And I see in the console that everything works as it should. However, this is not what I want. What I want is the code in the JS script to be fired upon a click on my button. This is what I tried:

                <input class="button" onclick="main()" type="submit"
                    value="Submit" name="">
                </div>

So I want the script that I have referenced somewhere else in the HTML file to fire the "main" function when my button is clicked. But what happens currently is that the click onto the button simply reloads the page.

So, to get this all into one question: I want to click my html button and then fire a single function from another script that is called "main.js".

How can I achieve that?

Thank you

0

3 Answers 3

4

I think this might be because of your type: submit. Try changing it to type="button".

Hope this helps!

Sign up to request clarification or add additional context in comments.

Comments

1

You are trying to call a function called main, but you need to run a script that creates a function. The browser won't go looking in a JS file with the same name as the function automatically.

Edit main.js so the code appears inside a function.

function main () {
    // Your code here
}

If you don't want the form to be submitted after the JS function is called, then don't use a submit button to trigger it. Use a type="button".

2 Comments

right, this is all clear to me. But i want to click my html button and then fire a certain function from the main.js. for instance in my main.js file there is a function called "button()". I want to click my button in my html and then fire "button()".
@innomotionmedia — If you want to call button then say onclick="button()" and not onclick="main()".
0

A submit button triggers a reload as it submits the formto the server, unless your main function returns false.

Adding

return false;

at the end of main should do the trick.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.