Firing JS function from another file from button in html file - javascript

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

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

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".

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.

Related

How do I programmatically click a button on this page when .click() does not work?

Actually, I am working on an extension which help to buy product from flipkart during flash sale. On teh product page I can't click on "Buy Now" button with the help of JavaScript its show me undefined this is the code of Buy Now button:
<form><button class="_2AkmmA _2Npkh4 _2kuvG8 _7UHT_c" type="button"><span class="_279WdV"></span> <!-- -->BUY NOW</button></form>
The Button is in this page
I am using the code to click this button in my JavaScript file
$("._2AkmmA._2Npkh4._2kuvG8._7UHT_c").click();
However, even when I go to the page on the site and, in the console, execute
$("._2AkmmA._2Npkh4._2kuvG8._7UHT_c").click();
The console shows undefined and does not start the "Buy Now" process that is started by manually using the mouse to click on the "Buy Now" button. In the console, executing
$("._2AkmmA._2Npkh4._2kuvG8._7UHT_c");
Shows:
<button class="_2AkmmA _2Npkh4 _2kuvG8 _7UHT_c" type="button"><span class="_279WdV"></span> <!-- -->BUY NOW</button>
which is the correct button that I desire to programmatically click. Note that even though I used $(), what is returned is not a jQuery Object.
If I click on that button manually, I'm shown the dialog for "Buy Now". You can go to this page and try it yourself.
I am not getting what is the problem here. Is there any problem in my code or its any kind of protection form filpkart website side?
I think you must use multi class selector in jQuery like this:
$("._2AkmmA, ._2Npkh4, ._2kuvG8, _7UHT_c").click()
As you see I use , between class
or reduce your class like this :
$("._2AkmmA").click()
You have to call the code only when All elements are full loaded, otherwise it won't find it. You must wrap in JQuery like :
$(document).ready(function(){
$("._2AkmmA._2Npkh4._2kuvG8._7UHT_c").click();
});
Your code is probably running before the DOM is fully loaded.
Try wrapping your code with $(document).ready(function(){... which will ensure that the code inside will only run once the page Document Object Model (DOM) is ready.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("._2AkmmA._2Npkh4._2kuvG8._7UHT_c").click();
});
function test(){
alert('clicked');
}
</script>
<form><button class="_2AkmmA _2Npkh4 _2kuvG8 _7UHT_c" type="button" onclick="test()"><span class="_279WdV"></span> <!-- -->BUY NOW</button></form>

When I load the page the alert("hey") function appears, why does the js function execute despite no onClick call? How do I prevent it from doing so?

When I load the html page the alert("hey") function appears immediately, why does the js function execute despite no onClick call? How do I prevent it from doing so? I'm new to js. Thanks for any help.
<body>
<div id="container"></div>
<script type="text/babel" src="js/es6.js"></script>
<script>
function toggleNav(){
alert("hey");
}
</script>
</body>
Are you sure you get such alert dialog,here i have ran for two times but without such problem,so check your code and clean your browser cache.or you can also change a browser and test it.
and if the question is still there, i think there maybe a closure function in your extra import js file.what i thought were only that, wish i can help you.
The alert Hey is not coming from the toggleNav() function, you should check your head part of HTML to see if there is a javascript file included which could be causing this, or show us what's in your es6.js file, the js function won't be executed unless it is being called like
toggleNav(); in your case.
And even if it was called on the onclick event it wouldn't be executed on the page load. Make sure you reload your page after you saved your changes.

HTML enable script code within div onclick

I have a div that looks like this:
<div id="scriptDiv">
<script src="URL" id="someId" my-token=""></script>
</div>
I can´t run the script tag within that scriptDiv until I have a token and that token is given when the user presses a button. I can´t render that token until I know that the user want to choose this choice.
So I have a button that renders some JS code when it´s pressed and adds the token to the div with this code:
$('#someId').attr('my-token', token);
So the issue is that the scriptDiv is called when the HTML page renders and I get an error. I only want the scriptDiv to be called when the user has pressed my button.
So is it possible to only call the scriptDiv when the button is pressed and not when the page is rendered?
If you don't want a script to be executed don't put it in the html or dom until you are ready
<div id="scriptDiv"></div>
Then in your button event create the script element, set it's src to the url, and then append it to the document
$("#button").click(function(){
var s = document.createElement("script");
s.src = "http://www.example.com/jsfile.js";
s.setAttribute("my-token","whatever your token is");
$("#scriptDiv").append(s);
});
You should set the token attribute of script tag inside the button click event as below.
$('#buttonId').click(function (){
$('#someId').attr('my-token', token);
});
I think you're going about this the wrong way. Look into doing a callback for when you want your code to run and bind that with an event to your button. You can control how that is done in JavaScript. For example, sorry I'm using jQuery here,
$('#myButton').on('click', function(){
//your code here
});
This way it will only run when your button is clicked.
You could put the js you want to run in a function e.g.
function scriptDiv(){
// Your js here
}
When you want the script to run (when the token is set) just use something that calls the function like:
<button onclick="scriptDiv()"></button>
You could also check every second if the token is set e.g.
setInterval(function(){if (tokenIsSet) {scriptDiv}},500);

Use JavaScript to automatically submit form

I'm have a simple form, when clicking the submit button the backend php file gets executed by my JavaScript file, results are returned via ajax, everything works great when manually clicking the button. However, when trying to use javascript to automatically submit the form every 120 seconds it is not working. The javascript never get's called which in turn causes the php to not execute...
html
<form id="send-with-ajax" name="ping">
<input type="submit" value="Execute Ping" />
<div class="ajax-response"></div>
</form>
<script type="text/javascript">
// refresh ping results every 120 seconds
var pingRefreshInterval = setInterval(function () {
console.log(
'submitting ping.php request after 120 second wait - time now:'+new Date());
document.getElementById("send-with-ajax").submit();
},120000);
</script>
<script src="js/portal.js"></script>
Again, there are not issues with my portal.js file or my php file -- The main thing to note here is that the document.getElementById("send-with-ajax").submit(); does not do anything... Any ideas?
Assuming that js\portal.js just executes a function when a POST event occurs, you could simply call that function from inside your interval.
If that won't work for some reason (maybe there's a lot of other stuff happening on your page that you didn't show us), and your call to submit() isn't working properly, you could also trigger a button click with $('input[type=submit]').click(); (assuming you only have one submit button on the page - otherwise add a class or an id and trigger on that instead).
Try using the submit() method. Or use AJAX.
If you are doing things on onsubmit event, document.getElementById("send-with-ajax").submit() doesn't trigger this event.

a href click or onclick 2 actions (two functions or more)

I have a href tag that goes like this :
href="download.php?file={$sp->attachment_1}&flag=ds&r_id={$userid}&scpl_id={$sp->sp_id};"
that works and downloads the intended file.
the issue is I want it to also call a javascript function.
so when someone click it downloads the pdf file AND calls a javascript function but I can't get it to work,
I tried using onClick but then it won't download if I put the link there.any suggestions would be greatly appreciated thank you
As soon as it redirects to the other page (download.php) you cannot run any javascript on this page.
If you want to do the javascript before, it is possible to say:
onclick='do_someting(); window.location="download.php?file=..."'
Did you tried returning True from the function,
onclick="return doAction()"
script,
function doAction(){
// do something
return true
}
If you're using jQuery you can just do this:
$("#IDOFYOURLINK").click(function() {
yourJavascriptFunction();
});

Categories

Resources