How to include javascript onclick event in Chtml::link - javascript

I have tried with this code, but it wont work. it works fine when i write it to onmouseover event.
echo CHtml::link('Form',
array('id'=>'submitButton'),
array('class'=>'linkClass','onclick'=>'formSubmit();'))
//Javascript
echo CHtml::script("
function formSubmit(){
$('#supplier-form').submit();
}");

Try writing javascript code inside the script tags:
<script>
function formSubmit(){
$('#supplier-form').submit();
}
</script>

after hours of searching finally found the answer.
just add return false inside onclick event after you call function name.
array('class'=>'linkClass','onclick'=>'formSubmit(); return false;'))
and javascript function should be inside <script> tags as rdanusha mentioned
<script>
function formSubmit(){
$('#supplier-form').submit();
}
</script>

Related

Jquery inside PHP block

The Jquery will not run. After the button is clicked, I'd like it add text, "Hello Everyone" after the Say: between the tags. The jquery.js file is uploaded to my server and is in the same place as the testpage.php file.
Should my button be inside <html></html> or is it something else?
my testpage.php code:
<?php
echo '<button id="some-btn">Test</button>
<script src="jquery-3.2.0.min.js"></script>
<p>Say: </p>
<script>
$(document).ready(function () {
$("#some-btn").click(fucntion (){
$("p").append("Hello Everyone");
});
});
</script>';
?>
You have mistakes in your code. E.g. fucntion is misspelt, should be function
<?php
echo '<button id="some-btn">Test</button>
<script src="jquery-3.2.0.min.js"></script>
<p>Say: </p>
<script>
$(document).ready(function () {
$("#some-btn").click(function (){
$("p").append("Hello Everyone");
});
});
</script>';
Like Qirel mentionned, I prefer to break the php. That way you prevent having too large strings in PHP.
Should my button be inside or is it something else?
Your elements should be between your body tags. You can also change your click function to the next one:
$(document).on('click', "#some-btn",function (){
$("p").append("Hello Everyone");
});
This way your event will trigger even for the elements that are added to the DOM once it is rendered.

javascript executes before browser has finished rendering the page

This question is not a duplicate of some of the other PHP & Javascript questions that have been asked here before, at least not one I have been able to find.
I have a .php file that contains some HTML elements that get rendered by the PHP for the sake of argument here we will say the file is located at http://url.php. It is looking for certain GET tags, and including a div if those get tags exist.
<?php if(isset($_GET['VAR']))
{
echo '<div id="VARDIV"></div>';
}?>
Of course I realize that this all happens on the server, and gets sent back to the clients web browser where the javascript takes over.
But in the javascript (on the same PHP page) I have the following code that executes on page load looking for that div tag and doing something with it:
if(document.getElementById("VARDIV")!==null)
{
alert('div exists!');
}
While the page loads this should logically pop up the div if the URL is http://url.php?VAR correct?
However it does not. If I run the javascript code a second time in the console it works fine, so its not a misspelling (such as getElementsById or something silly like that).
How can this possibly render out of order like this? Should the PHP engine not render the HTML then pass it back to the browser before one line of JS is executed?
EDITED FOR CLARITY BASED ON COMMENTS BELOW:
<script type="text/javascript">
function doDIVStuff()
{
if(document.getElementById("VARDIV")!==null)
{
alert('div exists!');
}
}
doDIVStuff();
</script>
<html>
<body>
<?php if(isset($_GET['VAR']))
{
echo '<div id="VARDIV"></div>';
}?>
</body>
</html>
use either window.onload() or document.onload(), see differences here
you could also place your script just before the end of your tag in the html although there could be unintended consequences in certain things in IE, seen here
Try to use jquery and document ready event:
$(document).ready(function(){
if(document.getElementById("VARDIV")!==null)
{
alert('div exists!');
}
})
If you do not want to include jquery js lib, you can use the solution here:
pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it
Actually if you place the javascript code at the end of file after all php and html code it must work.I have tested it.
<?php if(isset($_GET['VAR']))
{
echo '<div id="VARDIV">Dilip</div>';
}?>
<script type="text/javascript">
if(document.getElementById("VARDIV")!==null)
{
alert('div exists!');
}
</script>
but i think it is better to use onload event
window.onload=function(){if(document.getElementById("VARDIV")!==null)
{
alert('div exists!');
}};
Or if you are ok to use jquery then its awesome..
$(document).ready(function(){
if(document.getElementById("VARDIV")!==null)
{
alert('div exists!');
}
})
Any JavaScript that is not inside a function is executed sequentially as the page is interpreted. Your doDIVStuff(); call is executing before any HTML is interpreted on the page, therefore your "VARDIV" is not yet available in the DOM for the JS to read.
As others have suggested, the best approach is to listen for when the page is done loading and then trigger the call to your function.
Wrap in doc rdy() or just do something like this:
<html>
<head>
</head>
<body>
<?php if(isset($_GET['VAR']))
{
echo '<div id="VARDIV"></div>';
}?>
<script type="text/javascript">
function doDIVStuff()
{
if(document.getElementById("VARDIV")!==null)
{
console.log('div exists!');
}
}
doDIVStuff();
</script>
</body>
</html>
I'd say you should create a javascript file and put your code there so you can debug it.

How to integrate jquery code without any code in the html file

I want to clear my code a little bit and I want to run my jquery code without any function call in the html file. My actual code is :
HTML:
<head>
<script src="js/colorpick.js"></script>
<script>
$(document).ready(function() {
colorpick_start();
});
</script>
</head>
JS:
function colorpick_start() {
...
}
But if I write for example an alert in the first row of the js without any function call, that works.
alert('test');
function colorpick_start() {
...
}
But this is not working for jquery selectors or something. Is there any solution to get my jquery working without code in the html file?
I want my html file to look like this, if this is possible:
<head>
<script src="js/colorpick.js"></script>
</head>
The
$(document).ready(function() {
Waits until the DOM is ready for selectors etc.
If you add the
$(document).ready(function() {
to your colorpick.js file it will wait for the DOM to be ready and then execute colorpick_start().
And believe me this catches out most people when they start using JQuery.
In order to achieve this:
<head>
<script src="js/colorpick.js"></script>
</head>
Move the document ready call to the js file you are referencing in your HTML file and make sure that the method called is present.
$(document).ready(function() {
colorpick_start();
});
This should so it.
Put your script
<script src="js/colorpick.js"></script>
before </body> tag. This will ensure that your page is loaded fully before script starts.
$(document).ready(function() {
colorpick_start();
});
this code is working because you are calling your function after document is loaded. document load is event. you can put your function on any event you want, but it wont start if you just define your function. You have to somehow call your function. example would be on click (or on document load)
<div id="example"></div>
$("#example").on('click', function () {
your function here
});
Use that code:
$(function(){
$('.colorpicker').val("colorpicker"); //or whatever you like
});
Plnkr example code

Extracting JavaScript into separate file (from HTML). Duplicate call to function needed

See the source of http://marakana.com/s/post/1096/samples/try6.htm
It defines a function and calls it on load of document. (Which is the final step of this tutorial)
I tried to put it into a seperate JS file.
Runs correctly only if I call onload both in JS and in HTML.
But not only body onload or only from JS. I guess I am doing something wrong.
So, following works:
<head>
<script src="Scripts/makeWYSIWYG.js" type="text/javascript"/>
<script type="text/javascript">
window.onload = function () {
makeWYSIWYG(document.getElementById('editor'));
};
</script>
</head>
<body onload="makeWYSIWYG(document.getElementById('editor'));">
Why do I need to call the function twice?
I only have the function definition in "Scripts/makeWYSIWYG.js"
function makeWYSIWYG(editor) {
...
return editor;
};
Thanks,
There are no reason to call the function twice. The is enough.
With the first window.onload you could be changing a former function callback assignment (i.e. in a imported script).
The problem was actually the closing tag, "/>", here:
<script src="Scripts/makeWYSIWYG.js" type="text/javascript"/>
I should have written:
<script src="Scripts/makeWYSIWYG.js" type="text/javascript"> </script>
I guess the second script was helping the tag to be closed and making it run...
More info here: Why don't self-closing script tags work?

Loading javascript in body onload with 2 functions

I am trying to load 2 javascript events/functions in the body onload as follows :-
<body onLoad="getSubs(document.form1.HotelID.options[document.form1.HotelID.selectedIndex].value);getTags(document.form1.HotelID.options[document.form1.HotelID.selectedIndex].value);">
Whenever I load using 2 functions the first one aborts - but if I just load the one it works fine - am I doing something wrong is it no possible to put 2 functions within the onload?
try this:
<html>
<head>
<script language="javascript">
function func1(){
//the code for your first onload here
alert("func1");
}
function func2(){
//the code for your second onload here
alert("func2");
}
function func3(){
//the code for your third onload here
alert("func3");
}
function start(){
func1();
func2();
func3();
}
</script>
</head>
<body onload="start()">
</body>
</html>
Multiple onload
Just do it from java script instead, one of the link shared into a comment explains well why it is best to use this approach over inline attributes.
<head>
<script>
document.body.onload = function() {
getSubs(...);
getTags(...);
};
</script>
</head>
<body>
...
</body>
I would avoid at all cost to have inline javascript, that is what you did in the code of your question: add javascript within an HTML attribute.
Best practice is to add your javascript in a separate file, see the related question on this principle What is Unobtrusive Javascript in layman terms?
So you'd have an other file called for instance "myjsfile.js", then you reference it from your HTML page
<script src="./path/to/your/myjsfile.js"></script>
Here is the answer to where to place this reference: Where to place Javascript in a HTML file?
Your "myjsfile.js" file would simply have:
window.onload = function(){
getSubs(...);
getTags(...);
};
Another thing to avoid: add javascript within the same HTML file. The reason is also based on the same principle of unobstrusive javascript. What is Unobtrusive Javascript in layman terms?
But I guess there are corner cases where you may want to do that.
If you really have to, do use window.onload instead of the inline javascript onload="...", see why here window.onload vs <body onload=""/>
Just add the following to your HTML file:
<script type="text/javascript">
window.onload = function(){
getSubs(...);
getTags(...);
};
</script>
Here is the answer to where to place this code: Where to place Javascript in a HTML file?
Note: Yes, in the same place as where you would put the reference to an external javascript file
Another thing: I do not know where your getSubs() and getTags() functions are defined. But if you want your code to work, it needs to call these functions after the file (or part of javascript) that defines them has been loaded.
In short: make sure the javascript file containing the definitions of getSubs() and getTags() is referenced before your code.
One thing that you could do is create a new JS function that accepts the document.form1.HotelID.options[document.form1.HotelID.selectedIndex].value parameter and call the two functions in the newly created function.
I tried calling two functions using the below code and it worked fine for me.
<html>
<body onload="callStart();callAgain();">
<script type="text/javascript">
function callStart() {
alert('First');
}
function callAgain() {
alert('Again');
}
</script>
</body>
</html>

Categories

Resources