Prevent Joomla from reloading page - javascript

I have a problem using a javascript inside a joomla article. On clicking the submit button, the entire page is reloaded instead of the java script being executed. The code worked when loaded in the index.php file of the joomla template, but does not work when loaded from a single article for some reason
<div class="top"><form>
<p style="text-align: right;"><label for="power">Power <input id="power" type="number" name="power" /> mW</label></p>
<p style="text-align: right;"><input class="submit" type="submit" value="Calculate" /></p>
</form></div>
The java script
<script type="text/javascript">
/*jslint node: true */
/*global $, jQuery, alert*/
"use strict";
var $jQ = jQuery.noConflict();
alert(location.hostname);
jQuery(document).ready(function () {
$jQ("form").submit(function (event) {
alert("Calculate");
event.preventDefault();
});
});
</script>
Can anyone help me where this is going wrong?

If it works when you add the code manually to a PHP file but not when placed in an article then your editor is probably removing or altering the code. Check your editor settings for something like 'Allow JS' (where this setting is depends on your editor). Alternatively, try setting the editor to 'none' and see if that works.

it looks fine, try debugging the ready() call, by placing an alert() call (or better a console.log()) inside the code, and possibly replacing the ready event to jQuery's:
<script type="text/javascript">
"use strict";
console.log("script is running");
jQuery(function () {
console.log("hooking into submit");
jQuery("form").submit(function (event) {
event.preventDefault();
console.log("alternate submit");
});
});
</script>
Then open the console to see the logs (key F12) this should at least give you some pointers on where it gets stuck.

Related

I Cannot Link my jQuery

I've looked all around stack overflow for answers to this same problem. Usually it's simple syntax errors like omitting a closing tag or not writing the src attribute properly.
I could've sworn, though, that my html and js is correct, but I still can't get the jQuery working.
The normal javascript (function test()) works perfectly as it's linked with an html button using onclick. The $('#click') jQuery simply will not work, though.
<head>
<script type='text/javascript' src='jquery-3.2.1.min.js'></script>
<script type='text/javascript' src='test.js'></script>
</head>
<body>
<button type='button' style='margin: 1em;' id='click'>CLICK</button>
<button type='button' style='margin: 1em;' id='testButton' onclick='test()'>TEST LINKING</button>
</body>
Both js files and the html are in the same folder.
And here's the js.test:
$('#click').click(function () {
alert('jQuery Works!');
}); //NOT WORKING!
function test() {
alert('Okay!');
} //WORKING!
The problem isn't linking jQuery, it's about scope and DOM loading.
When you create a function globally it becomes a global reference that you can access whenever you want afterward.
When you call a function, or change the value of a variable, it needs a scope to know when to be called. It's generally the global scope but, when you use jQuery functions, you cannot know if your libraries are already loaded and therefore if you'll be able to access the functions they provide.
Therefore, wrap your EH in a document.ready function that is executed by jQuery itelf when the DOM is fully loaded. You can do it this way :
$(document).ready(function(){
$('#click').click(function () {
alert('jQuery Works!');
});
});
Or in a shorter way :
$(function(){
$('#click').click(function () {
alert('jQuery Works!');
});
});
Ahh, the problem here is that when you load the JS and jQuery file, browser starts going through you code, finds that it should now bind a click handler for #click, but when it actually goes to find #click on the page it doesn't get it. Because it has not been added to the dom yet !
You have three ways to deal with this :
Use the defer attribute of the script tag. It is used to define script that will not run until after the page has loaded
<script type='text/javascript' src='test.js' defer></script>
Just load your JS for the event handler after the divs like :
<head>
<script type='text/javascript' src='jquery-3.2.1.min.js'></script>
</head>
<body>
<button type='button' style='margin: 1em;' id='click'>CLICK</button>
<button type='button' style='margin: 1em;' id='testButton' onclick='test()'>TEST LINKING</button>
<script type='text/javascript' src='test.js'></script>
</body>
This is why you normally see the line
Place CSS includes in the head and JS include just before the close of the body tag
That's because without CSS your page would look ugly untill it has been loaded, and placing JS in the end would make sure that the DOM is in place for any action to be performed on it
You can use the $(document).ready(function(){ ... }) event handler. This event is triggered when the document is ready or essentially when the dom has been created. Binding you click handler here makes sure that the elem is actually available for your JS to bind to
You cant define a function in a way like this. you need to do this
$(document).ready(function() {
$('#click').click(function() {
alert('jQuery Works!');
//declare other function
});
});
`

Call an external js function from html

I have an HTML file with the following button:
<button type="button" onclick="muteaudio()" id="testButton">Mute</button>
In the head part i have
<script src="js/functions.js"></script>
In this script i have the following function
function($, window, document, undefined) {
function muteaudio(){
alert("it works");
}
}
I'm doing something wrong that is clear. But what is the correct way to call such a function?
This should work:
muteaudio = function(){
alert("it works");
};
Fiddle:
http://jsfiddle.net/ngn0Lfmf/
Not sure why your function doesn't work though
Check if the file is definitely loading via the F12(Developer Tool) then Sources tab.
Check that you have reloaded the page properly so the cache cleared and loaded the latest version of the file.
If the file is not there then check the path you are using, intellisense should help you find the file:
src="~" using ~ should activate the intellisense and help to find the file.
If the file is there but it is still not working then try copying the script code into your HTML file then you can determine whether it is the File or Code that is the issue:
<script type="text/javascript">
function muteaudio(){
alert("it works");
}
</script>
It may be the position of the file, try rending it in the footer.
UPDATE
I have made a JSFiddle which works with the following code and a Snippet:
function test() {
alert("in function!")
}
<input type="button" onclick="test()" value="mute" />

Sometimes jQuery plugin is not loaded

I am using jQuery a lot, but sometimes I get stuck because my browser cannot see the jQuery library, or maybe loads the library after running the my JavaScript code.
Pseudo-code to explain my question:
<html>
<head>
I always load CSS here
I always load jquery here
</head>
<body>
<p class="link-style3"><span id="my_tag"><span>Bize Hemen Yazın</span></span></p>
<script>
$(function() {
$('#my_tag').click(function(e) {
alert('tesrt');
});
});
</script>
</body>
</html>
I always put my stuff in the order like below, but this doesn't work now. When I click the <span id="my_tag">, it doesn't do anything, and doesn't return any error.
what should I do?
Here is the entire code jsfiddle
Try to avoid some syntax errors like(suggestable only)
<script type="text/javascript">
$(function() {
$('#my_tag').click(function() {
alert('tesrt');
});
})
</script>
and put your code at the top after you load the js files
A few things you can do:
inspect your document (network pane in devtools) to see if everything
is loading correctly
Move your scripts to the bottom of the page
use $(document).ready(function(){ ... });

How to make JQuery DatePicker work after dynamically loaded in a partial view?

I have lost jquery datepicker functionality in this scenario...
1- Originally I had a normal view, which worked fine, having this code for date input...
<input type="text" name="date_start" id="date_start"
value="#(Model.TimeStart)" />
<script language="javascript" type="text/javascript">
$("#date_start").datepicker();
</script>
2- Then, I converted that view in a partial view which is dynamically loaded with...
$('#TargetEmptyDiv').load("/MyController/MyAction");
3- The partial view loads ok, the data can be (manually) entered and all its fine. The only problem is that the jquery datepicker is no longer working. I tryed to assign it after the loading, using this...
$('#TargetEmptyDiv').load("/MyController/MyAction",
function () { $("#date_start").datepicker(); });
That did not work.
4- Later I've learned that jquery provides the live() and delegate() functions which are capable of attach javascript code to elements loaded "now and in the future". So, I tryed this in the document initialization...
<script type="text/javascript">
$(document).ready(function () {
$("#date_start").live("click", function () { $(this).datepicker(); });
});
</script>
and later also...
<script type="text/javascript">
$(document).ready(function () {
$("#date_start").delegate("click", function () { $(this).datepicker(); });
});
</script>
none of which worked, maybe because they directly reference to the "click" event, but the datepicker is "attached" (if that is the proper term) to the whole element.
So, question is:
How to make the jquery datepicker work on elements loaded after dynamic load???
Thanks for your time!
SOLVED:
The problem was that at the bottom of _Layout.cshtml there is this line...
#Scripts.Render("~/bundles/jquery")
..which loads the minified version of jquery libraries (already referenced by myself).
So, the libraries were loaded twice and got invalid, producing the error "datepicker() is not a function".
Just commenting or deleting that line, makes all work fine!
Put the following jQuery in the base view, not the partial view
<script>
$(document).ready(function () {
$(document).on('focus', '.datefield', function () {
$(this).datepicker();
});
});
</script>
This will work when a partial view is dynamically loaded and on page load.
Your approach in #3 looks to me like it should have worked, so it seems like you need to do some debugging. Try this:
Get the Firebug extension, if you use Firefox (Chrome has dev tools built in)
Add a debugger line to your code (see below for example)
Load your page up with Chrome or Firebug/Firefox (or any other browser's dev tools)
What should happen is that your browser will pause at that point. However, if things aren't working as you expect, it might not be hitting that code at all, and then you'd get no pause.
If you do get a pause, use the console to inspect the value of $("#date_start"); it's possible that jQuery selector isn't grabbing what you think it is.
Here's a debugger example with your code:
$('#TargetEmptyDiv').load("/MyController/MyAction", function () {
debugger;
$("#date_start").datepicker();
});
On your partial page say "/MyController/MyAction",
Partial Page Code:
<div>
<form>
<!--Other Elements-->
<input type="text" id="adate" name="adate" title="date" />
</form>
<script type="text/javascript">
$(document).ready(function(){
$( "#adate" ).datepicker();
});
</script>
</div>
Full Page(Page From Where You are Calling Ajax Request) Code:
<div id="TargetEmptyDiv"></div>
<script type="text/javascript">
function abc(){
$.ajax({
type: "POST",
url: "/MyController/MyAction",
success: function(response)
{
$("#TargetEmptyDiv").html(response);
}
});
}
</script>
call function abc and you are done.assuming you already have all jquery files loaded.
In my case, the Id of the date field that I tried to hook up the datepicker to was not what I thought it was. I am using ViewModels and the id got prefixed with the ViewModel name of my partial view.
machineghost's answer put me on to it.
So I now use Charly's answer but instead of #BirthDate I have #IdentityModel_BirthDate:
<script>
$(document).ready(function () {
$(document).on('focus', '#IdentityModel_BirthDate', function () {
$(this).datepicker({
format: 'MM/dd/yyyy',
changeMonth: true,
changeYear: true,
yearRange: "-90:+0"
});
});
});
</script>
All you need to make the datepicker work is steps 1-3.
Here's a sample:
http://jsfiddle.net/delrosario/Xd8py/
You got datepicker to work without loading the markup dynamically and your pseudo code for the dynamic version is sound from steps 1-3. The thing you need to check now is to make sure that your dependencies are being loaded before your main program (in this case make sure that jquery and jquery ui are available before running the request + datepicker setup).
1) load jquery
2) load jquery ui
3) wait till the dom is ready or the element that will contain your payload is ready
4) execute your main app that does steps 1-3 from your description.
So it would be something like this.
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="path-jquery-ui-css" />
<script src="path-to-jquery"></script>
<script src="path-to-jquery-ui"></script>
<script id="main_app">
(function () {
// wait till dom is ready before executing our code,
// in this case steps 1-3.
});
</script>
</head>
<body>
<div id="datepicker_target">datepicker target</div>
</body>
</html>
After invoking ajax, hookup your jquery to the 'ajaxStop' event. (SEE: '#section Scripts' )
$(document).ajaxStop handles the post ajax jquery call and now datapicker works after ajax call(s). yea...
Note: $(document).ready... handles the initial page load datapicker decoration, but after an ajax form reload, datepicker jquery was not executed...
#model Q_Admin.Models.AllQAViewModel
<div id="mainContent">
#using (Ajax.BeginForm("EAAll","Answer",new AjaxOptions {
UpdateTargetId = "mainContent",
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace
}))
for (int i = 0; i < Model.VMs.Count; i++)
{
#switch (Model.QAVMs[i].qN.Node1.TypeAnswer.AnswerType.Trim().ToUpper())
{
case "DATETIME":
#Html.TextBoxFor(m => m.VMs[i].CurrentNodeText,
new { #class = "datepicker", #id = "datepicker" });
break;
case "DROPDOWNLIST":
#Html.DropDownListFor(m => m.QAVMs[i].AnswerRecord.AnswerID,
new SelectList(Model.QAVMs[i].answerNodes, "ID", "NodeText.Text", Model.QAVMs[i].SelectedNodeID),
"-- Select an Answer --",
new { #onchange = "$(this).parents('form:first').find(':submit')[0].click();" }) }
break;
default:
break;
}
}
</div>
#section Scripts{
<script type="text/javascript">
$(document).ready(function () {
// debugger;
$("#datepicker").datepicker(
{
dateFormat: "mm/dd/yy",
constrainInput: true
});
});
$(document).ajaxStop(function () {
// debugger;
$("#datepicker").datepicker(
{
dateFormat: "mm/dd/yy",
constrainInput: true
});
});
</script>}
I've had this problem before. In my situation I had <script src='jQueryUI.js'></script> referenced at the bottom of the page. Moving the reference to the top of page fixed it for me.
Seems like #3 should works. But maybe you can try a hacky way like this:
<script type="text/javascript">
$(document).ready(function () {
$(this).on("mousedown", "#date_start", function (e) {
$(this).datepicker(); e.preventDefault();$(this).click();
});
});
</script>
I have this working
Action Method:
public ActionResult GetControl()
{
return View("_partial");
}
Main View:
<div id="TargetEmptyDiv"></div>
<script type="text/javascript">
$(function () {
$('#TargetEmptyDiv').load("/Home/GetControl");
});
</script>
Partial View:
#{
Layout = "";
}
<input type="text" name="date_start" id="date_start" />
<script type="text/javascript">
$(function () {
$("#date_start").datepicker();
});
</script>
Of course you have to remember to include jquery-ui.js in your Layout
<script src="#Url.Content("~/Scripts/jquery-ui-1.8.20.min.js")" type="text/javascript"></script>
My suspicion is that your JS is executing, but you have improperly referenced jquery-ui. I recommend adding all jquery libraries at a higher level than a partial view. Try putting the <script src="jquery-ui.js"> tag in either the page or the layout, not the partial view. If this doesn't fix it, try putting alert("test"); in your javascript code to make sure that it is executing.
I had the exact same problem. If using ajax, then bind the below jquery function to the document. Each time ajax is executed, this will fire. Check out the api doc here - http://api.jquery.com/category/ajax/global-ajax-event-handlers/
$(document).ajaxComplete(function (){//your code here})
I had the same problem, solved using a previous version of JQuery-UI. In my case goes to use the version 1.9.2 and 1.10.3 to JQuery version 1.10.1. Know the reason, but I think the latest versions bring some problems compactness, so I chose to use always backward to the past.
I hope it will be useful
<script type="text/javascript">$(function () {$("#datefield").datepicker();});</script>
just load this line with the content you have to load by ajax
hi: you put below code in load document event script tag in your partial view :
$(function(){
$("#date_start").datepicker();
})

javascript linking onclick to a .js to a file

I created a .js file, and then included it in the HTML pages by:
<script type="text/javascript" src="yourexternalfile.js"></script>
How do I call the function of the .js file using onclick = "...." ?
I know that it will be something like:
<input type="BUTTON" value="Exit" onclick="javascript: ???;" >
but I can't figure it out...
If you are using JQuery, you can do it like this,
<input type="button" onclick="javascript: $.getScript('../scripts/yourfilepath' , function (){ youFunctionCall() ; } );" />
This will download the JS file when the button is cliked and shall execute the function called within.
Say your function was ...
function myFunction() {
alert("hello!");
}
An example of the trigger would be ...
<input type="button" onclick="myFunction(); return false;" value="Click me!" />
To call a function inside an external file, make sure the file is loaded first and then call it as per normal (so long as it exposes itself to the scope you need it to).
include the external java script file in your page(preferably in the head tag) using
<script type="text/javascript" src="yourexternalfile.js"></script>
and then you can call any function defined in the js file
use <script type="text/javascript" src=""> to import the js file inside your page.
Knowing when a JS file is (a) loaded, and (b) done executing is tricky, as it isn't supported by all browsers.
I believe you're thinking something along the lines of:
var s = document.createElement("script"),
f = document.getElementsByTagName('body')[0];
s.type = 'text/javascript';
s.src = "https://ajax.googleapis.com/ajax/libs/dojo/1.5.0/dojo/dojo.xd.js";
s.addEventListener("load", function() {
console.log("script loaded");
});
f.appendChild(s);
Like I've mentioned above, it won't work for all browsers. And even if it does, it won't be very useful to you if you're actually trying to execute some code based on the JS that is pulled-in dynamically.
The only reliable way to execute something when a dependency is loaded is to wrap that dependency in a function. That way when the browser parses that JS it will execute that function, which will let you know that you can start using whatever it is that you wanted to bring in. This is exactly why JSONP works the way it works.
If this is what you want to do, take a look at RequireJS.
Have you tried actually putting in the name of the function? Like onclick='myFunction()'
I would suggest adding the on-click event in the JS file like so:
html:
<input type="button" id="myButton"/>
JS file:
var myButton = document.getElementById('myButton');
myButton.onclick = function(){myFunction()};
This way you can program the element from the Javascript file.
Just put it in a function that you call on-load.

Categories

Resources