JavaScript not allowing input before running - javascript

Im having issues with this javascript running prior to the user input, can someone help me fix this.
im just trying to make a little html page with a textbox and a button, that then clicked opens a new windows with a modified URL.
<input type="text" name="enter" class="enter" value="" id="lolz" />
<button type="button" id="the_button">Count</button>
document.getElementById('open').addEventListener('click', myFunction());
function myFunction() {
var button = document.getElementById("the_button");
var siteid = document.getElementById('lolz').value
button.onclick = count();
function count() {
window.location = "http://www.websiteimusing.com/" + siteid;
}
}
You can check the code out here
The Actually generate output from that website's code is this
Updated Code
document.getElementById('the_button').addEventListener('click', myFunction);
function myFunction() {
var button = document.getElementById("the_button");
var siteid = document.getElementById('lolz').value
button.onclick = count();
function count() {
window.location = "http://www.websiteimusing.com/" + siteid;
}
}

There's no element with id open in your code, so you're trying to add an event listener to null. The console will tell you the same:
Uncaught TypeError: Cannot call method 'addEventListener' of null
Also make sure to remove the parens from your event listener function, as the other posters have stated.

Change to:
document.getElementById('open').addEventListener('click', myFunction);
When you put () after a function name, it means to call the function at that time.

On this line
document.getElementById('open').addEventListener('click', myFunction());
you are calling the function by adding the ()
change that to:
document.getElementById('open').addEventListener('click', myFunction);

Related

Why isn't my function not working this button element?

Nothing seems to be working on my button element. Here I have more than one function to test if it gives the alert window-- they don't work but it seems like its correctly written. I will provide 2 function codes which either don't work and the html button element being targeted to help inspect the code. I am 1 month into javascript so I apologize in advance if the mistake in here turns out to be a silly mistake.
HTML button element:
<form input='text' action="" method="post" name="entry" class="journalentry" id='form'>
<textarea name='entrybody' rows='12' cols='90' placeholder="Anything you want to write about the day you are thinking of." class="journalentry"></textarea
<button type='submit' onclick= "test()" id='submitid' class='submitbutton'>Submit</button>
</form>
function #1 (creating the element from javascript and adding an event listener. this one doesnt use the html form but function #2 does):
var submitelement = document.createElement('BUTTON');
var submittextnode = document.createTextNode("SUBMIT ME");
submitelement.appendChild(submittextnode);
document.body.appendChild(submitelement);
var submitattr = document.createAttribute("id");
submitAttr.value = "submitbutton";
submitelement.setAttributeNode("submitAttr");
submitelement.addEventListener('click', function() {
alert('88888');
})
function #2 (commented out function #1 and wrote this code out. still doesn't work) :
document.getElementById("submitbutton").addEventListener("click", test();
function test () {
var url = 'http://news.google.com';
var method = "GET";
var httpObj = new XMLHttpRequest();
httpObj.open(method, url, 'true');
httpObj.addEventListener("readystatechange", processRequest, false);
}
function processRequest (e) {
if (httpObj.readyState == 4 && httpObj.status == 200)) {
// time to partay!!!
var response = httpObj.responseText;
alert(response);
}
}
Function is not triggering that means you've made some blunders in your coding (syntax error).
Try Correcting Following Issues:-
1.Replace this line document.getElementById("submitbutton").addEventListener("click", test(); with this one document.getElementById("submitbutton").addEventListener("click", test());
2. Shift this line document.getElementById("submitbutton").addEventListener("click", test());
before closing your <script> tag(at the end).
How to debug javascript program?
You can easily debug it by going right clicking on main window screen-> a drop down will appear select inspect element option a window will appear -> click console on tabs. Here you can see your javascript errors red highlighted.

Can't call function with button click (javascript)

I have a very strange issue. I have a button which currently prints a barcode label using the following code:
<button id="printButton">
PRINT BARCODE LABEL
</button>
This button then successfully calls:
printButton.onclick = function()
{ CODE }
The problem is that I wish to be able to print multiple barcode labels with a single button press. So, I changed the javascript function to:
function print()
{ CODE }
And added
printButton.onclick = function()
{
print();
}
With the idea being that I can ultimately call multiple print functions (print1() print2() etc) from the same button press. The problem is, when I rewrite the code as above, nothing happens, even though it seems to me that the exact same thing should happen as happened before? Any idea? I am happy to post the full code if anyone thinks that might help.
i would do:
$('#printButton').on('click',function (){
//call print method
});
var a1 = function (_func) { console.log('print'); if (_func != null) { _func()} }
printButton.onclick = function () {
a1(a1(a1(a1(null))));
}
<button id="printButton"> PRINT BARCODE LABEL</button>
function print(){alert('print func');}
printButton.onclick = print;
<button id="printButton">
PRINT BARCODE LABEL
</button>

I keep getting this error in javascript? (radio, checking them in javascript)

For some reason I keep getting this error, I don't know why.
Uncaught TypeError: Cannot set property 'checked' of null js.js:4
check js.js:4
(anonymous function)
Here is my code:
document.body.onload="check()";
function check()
{
document.getElementById("urlchoice").checked=true;
}
First check if document.getElementById("urlchoice") is null or not.
window.onload = check;
function check(){
if(document.getElementById("urlchoice")!=null){ // available
document.getElementById("urlchoice").checked = true;
}
}
the error points for an unidentifed element with id "urlchoice", are you sure it exists?
<body>
<input id="urlchoice" type="radio">
<script>
document.body.onload = check();
function check(){
document.getElementById("urlchoice").checked=true;
}
</script>
</body>
seems to work (i removed the double quotes of the document.body.onload = check(); line, it don't work with it
Assuming you have an element with the ID urlchoice (whose absence would be trivial to diagnose, but I don't think that is causing your problem because you say that check is getting called), try window.onload, not document.body.onload.
EDIT
Again, assuming the document has a radio button element with id = urlchoice, and that the script is properly invoked and is running,
Try:
function check() {
document.getElementById("urlchoice").checked=true;
}
window.onload=check;
or
window.onload = function () {
document.getElementById("urlchoice").checked=true;
}
These really should work.

How do I temporarily disable a submit button for 3 seconds (onsubmit), then re-enable it?

I am fairly new to using javascript and here is what I have so far:
<!-- this is to disable the submit button and then re-enable it after 3 sec -->
<script type="text/javascript">
function enable()
{
var x = document.LAYOUTFORM.getElementById("create_button");
setTimeout(x.removeAttribute("disabled"), 3000);
}
</script>
And for the button I have this:
<INPUT TYPE="SUBMIT" VALUE=" Create PDF " class="FORMBUTTON" ID="create_button" onclick="javascript:this.disabled=true;javascript:enable();">
I have messed with this for hours and most of you will look at it and know what is wrong immediately. My form ID and name is LAYOUTFORM. Can anyone tell me what I am doing wrong here?
For bonus points I would also like the text of the button to temporarily change to "Creating..." while it is disabled, and then back to Create PDF again.
Simplest way:
<input ... onclick="lockoutSubmit(this)">
In your javascript:
function lockoutSubmit(button) {
var oldValue = button.value;
button.setAttribute('disabled', true);
button.value = '...processing...';
setTimeout(function(){
button.value = oldValue;
button.removeAttribute('disabled');
}, 3000)
}
Drop the LAYOUTFORM between document and getElementById.
Just an fyi, using firebug, chrome developer tools, or whatever the equivalent tools are for IE, you can monkey with your javascript on the console. Console.log will also output text and even objects (in CDT) which you can inspect. Very useful for exploring :)
Several problems. First, in the onclick attribute, you use javascript: which is for URLs. Stuff inside the onclick attribute is already evaluated as code. Second, the code in your setTimeout should either be string or a function name. You should do something more like this:
HTML:
<INPUT TYPE="SUBMIT" VALUE=" Create PDF " class="FORMBUTTON" ID="create_button" onclick="disable();">
JavaScript:
<script type="text/javascript">
function disable() {
x=document.getElementById("createbutton");
x.disabled=true;
x.value="Creating...";
setTimeout(enable, 3000);
}
function enable() {
x.disabled=false;
x.value=" Create PDF ";
}
</script>
You can access the button either by id that is globally unique
or by the name unique to the enclosing form
So you have to either
var x = document.getElementById("create_button");
or
var x = document.LAYOUTFORM.elements["create_button_name"];
(Assuming create_button_name is the name of the button:
<input type="submit" value=" Create PDF " id="create_button" name="create_button_name" class="formButton" onclick="javascript:this.disabled=true;javascript:enable();">
)
The first parameter of the setTimeout should be a function:
setTimeout(removeAttr, 3000);
function removeAttr() {
x.removeAttribute("disabled")
}
BTW, HTML need not be (and should not be, for readability etc) all uppercase.
There are two main problems with your JavaScript:
The .getElementById() method belongs to document, not to your form (or any other) element.
setTimeout() expects the first parameter to be a function (or a string, but there's almost never a situation when using a string is appropriate).
Try this:
function enable() {
var x = document.getElementById("create_button");
setTimeout(function() {
x.removeAttribute("disabled");
}, 3000);
}
You may like to combine the disabling and re-enabling into a single function:
<INPUT TYPE="SUBMIT" ... onclick="temporaryDisable(this);">
function temporaryDisable(el) {
el.disabled = true;
setTimeout(function() {
el.disabled = false;
}, 3000);
}
Note that you don't need to use .removeAttribute(), you can just set the .disabled property directly (like you were already doing when you disabled the element).
EDIT: Just saw the "bonus points" part of your question. You just need to set the .value property:
function temporaryDisable(el) {
var oldLabel = el.value;
el.value = "Creating...";
el.disabled = true;
setTimeout(function() {
el.disabled = false;
el.value = oldLabel;
}, 3000);
}
<script type="text/javascript">
function disDelay(obj){
obj.setAttribute('disabled','disabled');
setTimeout(function(){obj.removeAttribute('disabled')},30000)
}
</script>
<input type="submit" value="Submit" onclick="disDelay(this)">
http://www.webdeveloper.com/forum/showthread.php?164239-Temporarily-Disable-Submit-Button

How can I pass arguments to anonymous functions in JavaScript?

I'm trying to figure out how to pass arguments to an anonymous function in JavaScript.
Check out this sample code and I think you will see what I mean:
<input type="button" value="Click me" id="myButton" />
<script type="text/javascript">
var myButton = document.getElementById("myButton");
var myMessage = "it's working";
myButton.onclick = function(myMessage) { alert(myMessage); };
</script>
When clicking the button the message: it's working should appear. However the myMessage variable inside the anonymous function is null.
jQuery uses a lot of anonymous functions, what is the best way to pass that argument?
Your specific case can simply be corrected to be working:
<script type="text/javascript">
var myButton = document.getElementById("myButton");
var myMessage = "it's working";
myButton.onclick = function() { alert(myMessage); };
</script>
This example will work because the anonymous function created and assigned as a handler to element will have access to variables defined in the context where it was created.
For the record, a handler (that you assign through setting onxxx property) expects single argument to take that is event object being passed by the DOM, and you cannot force passing other argument in there
What you've done doesn't work because you're binding an event to a function. As such, it's the event which defines the parameters that will be called when the event is raised (i.e. JavaScript doesn't know about your parameter in the function you've bound to onclick so can't pass anything into it).
You could do this however:
<input type="button" value="Click me" id="myButton"/>
<script type="text/javascript">
var myButton = document.getElementById("myButton");
var myMessage = "it's working";
var myDelegate = function(message) {
alert(message);
}
myButton.onclick = function() {
myDelegate(myMessage);
};
</script>
The following is a method for using closures to address the issue to which you refer. It also takes into account the fact that may which to change the message over time without affecting the binding. And it uses jQuery to be succinct.
var msg = (function(message){
var _message = message;
return {
say:function(){alert(_message)},
change:function(message){_message = message}
};
})("My Message");
$("#myButton").click(msg.say);
By removing the parameter from the anonymous function will be available in the body.
myButton.onclick = function() { alert(myMessage); };
For more info search for 'javascript closures'
Event handlers expect one parameter which is the event that was fired. You happen to be renaming that to 'myMessage' and therefore you are alerting the event object rather than your message.
A closure can allow you to reference the variable you have defined outside the function however if you are using Jquery you may want to look at its event specific API e.g.
http://docs.jquery.com/Events/bind#typedatafn
This has an option for passing in your own data.
<input type="button" value="Click me" id="myButton" />
<script type="text/javascript">
var myButton = document.getElementById("myButton");
myButton.myMessage = "it's working";
myButton.onclick = function() { alert(this.myMessage); };
</script>
This works in my test suite which includes everything from IE6+. The anonymous function is aware of the object which it belongs to therefore you can pass data with the object that's calling it ( in this case myButton ).
The delegates:
function displayMessage(message, f)
{
f(message); // execute function "f" with variable "message"
}
function alerter(message)
{
alert(message);
}
function writer(message)
{
document.write(message);
}
Running the displayMessage function:
function runDelegate()
{
displayMessage("Hello World!", alerter); // alert message
displayMessage("Hello World!", writer); // write message to DOM
}
Example:
<input type="button" value="Click me" id="myButton">
<script>
var myButton = document.getElementById("myButton");
var test = "zipzambam";
myButton.onclick = function(eventObject) {
if (!eventObject) {
eventObject = window.event;
}
if (!eventObject.target) {
eventObject.target = eventObject.srcElement;
}
alert(eventObject.target);
alert(test);
};
(function(myMessage) {
alert(myMessage);
})("Hello");
</script>
What you have done is created a new anonymous function that takes a single parameter which then gets assigned to the local variable myMessage inside the function. Since no arguments are actually passed, and arguments which aren't passed a value become null, your function just does alert(null).
If you write it like
myButton.onclick = function() { alert(myMessage); };
It will work, but I don't know if that answers your questions.

Categories