Google Closure onclick event not working - javascript

I have the following button in a HTML file:
<button id="signupbutton" name="signup.submit" type="submit" class="btn">Sign up</button>
I am using pyramid and I include closure base and my script like this:
<script src="${request.static_url('app:javascripts/closure-library/closure/goog/base.js')}"></script>
<script>
goog.require('goog.events');
goog.require('goog.events.EventType');
goog.require('goog.dom')
goog.require('goog.dom.forms');
</script>
<script src="${request.static_url('app:javascripts/checks.js')}"></script>
In my javascript file checks.js I wrote:
var buton = goog.dom.getElement('signupbutton');
goog.events.listen(
buton,
goog.events.EventType.CLICK,
function(e) {
alert("Here");
});
What I get in the console is a TypeError: src is null events.js:954 (var listenerMap = src[goog.events.LISTENER_MAP_PROP_];) and nothing happens, only the page reloads!
If I create the button using google closure it works! So I can't figure out what the problem is!

its seem because your button is not in the DOM when your javascript is executed.
You should execute your script only after the button's been loaded in the DOM.
TypeError: src is null events.js:954
Example : http://jsfiddle.net/zeroc00l/ZugNX/

Related

HTML Form Input to External Javascript Variable

Most of the solutions I have found deal with localized javascript instead of an external file so I am posting this question.
Links to attempted solutions:
Turn HTML Form Input into JavaScript Variable
I want to take a html form input and use that input in an external javascript file.
The html form input comes from index.html
<script src="script/our.js"></script>
<div class="searchbar">
<form action="">
<input type="text" placeholder="search ..." name="query" onchange=formChange()>
<button type="submit">sendit bro</button>
</form>
</div>
<script>
function formChange(){
var searchThis = document.getElementsByName("query").value;
}
</script>
Then, our.js tries to use the variable like so:
var Manager;
(function ($) {
$(function () {
Manager.store.addByValue('q', searchThis);
});
})(jQuery);
With my current setup, if I searched a term ("unlock") the form will send and the page will show it has found 0 documents. It does not say that searchThis is undefined
The back end of my js works with searchThis being replaced by "*:*" to display all records instead of those with the searched string.
EDIT #1 : Manager.jquery.js to see if I need to allow for search term to be a variable an not just a string
REDACTED
EDIT #2 :
I have been trying suggestions below. Currently:
index.htmlchanged
<script>
function formChange(){
var searchThis = document.getElementsByName("query")[0].value;
console.log(searchThis);
window.searchThis = searchThis;
console.log(window.searchThis);
}
</script>
our.jschanged
Manager.store.addByValue('q', window.searchThis);
The console.logs in index.html return my search term. However if I do the same just before window.searchThis is called in our.js it returns as undefined.
EDIT #3
I have been playing with importing the searchThis variable. I cannot import window.searchThis because I get an error for unexpected . In full when I try:
import searchThis from "../index.html"
It gives me an error stating:
Failed to load module script: The server responded with a
non-JavaScript MIME type of "text/html". Strict MIME type checking is
enforced for module scripts per HTML spec.
EDIT #4 : my <form> + <script> section with adjustments
<div class="searchbar">
<form>
<input type="text" placeholder="search Nicola..." name="query" onsubmit=formChange() >
<button type="submit">sendit bro</button>
</form>
</div>
<script>
function formChange(){
searchThis = document.getElementsByName("query")[0].value;
term = searchThis;
console.log(term);
}
</script>
<script defer="defer" src="script/our.js" type="module"></script>
Ive added my form section because I could be doing something wrong here too. When I go to my main page the console.log on our.js has already been logged as undefined. When I enter a search term with onchange instead of onsubmit the console logs from my <script>. Once I hit submit, the page flashes and the log for our.js is again at the top and undefined.
EDIT #5 : pic of logs described above (before submit)
You could use the window object.
Add a new property named searchThis to the window object and assign the obtained value of the searchThis variable.
function formChange() {
var searchThis = document.getElementsByName("query")[0].value;
window.searchThis = searchThis;
}
Then, just call it by using window.searchThis:
var Manager;
(function($) {
$(function() {
Manager.store.addByValue('q', window.searchThis);
});
})(jQuery);
Update: document.getElementsByName("query") returns a NodeList. You could use document.getElementsByName("query")[0] to refer to a single element.
The availability of a variable for reuse in another external file depends on the order of loading or initialization.
The issue that you have is that our.js is running before the window.searchThis is declared.
You can do:
Add a defer attribute in the script tag. Example: <script defer="defer" src="script/our.js"></script>.
OR
Put the <script src="script/our.js"></script> at the end.
Something like this:
<script>
function formChange() {
var searchThis = document.getElementsByName("query")[0].value;
window.searchThis = searchThis;
}
</script>
<script src="script/our.js"></script>

Loading javascript function on button event

I would like to call a Javascript function once the button is displayed on screen. What I am looking for is similar to the 'onclick' attribute:
<input type="button" class="button-class" onclick="function(this)">
However, I would like the function to be called as soon as the button is displayed on screen i.e. it should be instantaneous (button creation=function call). I have already tried 'onload' but this does not seem to work. Is there a way to do this please?
Thank you
Put an script element invoking the function after the button element
<input type="button" class="button-class" onclick="fn(this)" value="button" id="btn">
<script>
function fn(obj){
console.log(obj)
}
fn(document.getElementById("btn"));
</script>
#Questionnaire, you can't do what you want since an action should take place for a button (click event) to execute code.
As a good practice, load your Javascript code after the page is done loading. This is to avoid blocking the rendering of HTML code since
Javascript is synchronous.
...
<script type="text/javascript">
function init() {
// Code for your button function here
}
window.onload = init();
</script>
</html>
The code above is pretty much it.
Just write the function name in onclick property instead of function(this) like the following..
<script>
function myFunc(e){
//do something
}
</script>
<input type="button" class="button-class" onclick="myFunc(this)">
#Bartman pointed out how the .ready() funtion handled it as a document.ready.
So i came up with a small solution to run the waanted funtion once the input button is created. Hotfix but cant imagine another solution
I hope this helps. If not please add a comment so i can edit the answer.
function clickFunc(e) {
alert("click event");
}
function loadFunc() {
alert("load event");
}
$("#button").click(function() {
$("div").append("<input id=\"but\" type=\"button\" class=\"button-class\" onclick=\"clickFunc(this)\">");
$("body").append("<script>loadFunc();<\/script>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="button" type="button">
<div></div>

Javascript: Load an HTML page with button click

I have a button defined in HTML.
I want to load a page background.html when this button is clicked. But I want to do it from javascript, not from inside the .html file. So on my register.js file I have below:
$(document).ready(function() {
$("#btnApply").click(function() {
window.open("background.html");
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="btnApply" value="Register">
But this doesn't load the page. What am I missing?
<input type = "button" id = "btnApply" value = "Register" onclick="loadPage()">
then the function could be in your register.js file as :
function loadPage()
{
window.location="background.html";
}
It might be because popups are blocked on that page. All you need is to allow them (a screenshot from Chrome):
And ensure that you:
Run this code in the browser (otherwise you will not have window object)
background.html is in the same folder as your script
The open() method opens a new browser window. If you want it to load from the same window use location object.
window.location.assign("background.html");

Javascript form.submit() works only when debugging

I have a weird problem when I try to submit a form. My page contains a html table and one column has a link that deletes the line from the DB calling a js function.
The html/php line is the following one:
<input type="hidden" name="deleteid" value=0>
print ", delete";
The javascript function is the following one:
function delete_line(team_id) {
if (confirm('<?php echo $txt_confirm_del_team;?>')){
document.formName.elements.deleteid.value = team_id;
document.formName.submit();
}
}
If I put a breakpoint on the line "document.formName.submit();", the called page can read the parameter "deletedid". If not, the parameters are not passed to the page called by the submit.
Btw, I have another issue if I use getElementById() to retrieve the element or the form in the javascript function: it says the getelementbyid is null (and it's not because I can retreive it using the syntax document.formName.elements.deleteid)
thanks
There may be some other event handlers there, you can open the page in Chrome and right click the anchor, then choose "inspect element" and then check out the event handlers in the "event listeners" tab.
As far as the code you posted; there is nothing wrong with it. The following works just fine for me:
<html>
<head>
<title>test</title>
</head>
<body>
<a onclick="javascript:delete_line(22);">delete</a>
<script>
function delete_line(nr){
console.log(nr);
}
</script>
</body>
</html>

Script not executed after FORM element

I have an .aspx page. I populate a public variable in the code behind (.cs) page and then access that variable in JS on client side. I have the script declared after the FORM tag as below :-
<body>
<form>
...
</form>
<script language="javascript" type="text/javascript">
debugger;
var data = "<%=cSharpData%>";
</script>
</body>
After postback this script does not get executed first time, but when I click on any other server button on the page, then it gets executed.
Any idea why?
Is your postback done with ajax?
If so then only part of the page is refreshed and the script is not executed again.
You can wrap it in a function and add that function to the postback callback handler.
This is how I did it on one site:
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function () { edit.update(); });
Putting some Javascript after a <FORM> element does not mean it will get processed after the form has been submitted. It gets processed as the HTML is rendered, which is what you are seeing.
If you want to run some Javascript after POSTing a form then you need to use a onClick handler, something like this:
<FORM NAME="myform" ACTION="" METHOD="GET">
<INPUT TYPE="text" NAME="inputbox" VALUE=""><P>
<INPUT TYPE="button" NAME="button" Value="Click" onClick="dosomejavascriptstuff()">
</FORM>
have you tried to execute it with jquery $(document).ready()?
something like:
<script language="javascript" type="text/javascript">
$(document).ready(function(){....});
</scrip>
updated
without jquery
/* registr event on document load */
if ( document.addEventListener ) {
document.addEventListener( "DOMContentLoaded", log4link, false );
} else if ( document ) {
document.attachEvent("onreadystatechange",function(){
if ( document.readyState === "complete" ) {log4link();}
});}
Thanks for your replies. I got closer to the issue but I do not know the solution :(
The C# variable contains a path info as "D:\" and when I set this on a JS variable I get the error as "Unterminated String Constant".
How do I overcome this.
Actually this was the problem, why the script was not getting executed. As soon as I removed the "\", it worked !

Categories