Unobtrusive Javascript on a Submit Button - javascript

I'm trying to write an unobtrusive function on a submit button without the use of jQuery and the like. I have the following bit of code in my HTML form:
document.getElementById('help_submit').onclick = function (){
window.alert("You clicked on the Submit Button on the Help Request form.");
};
And I'm trying to use on the following HTML button:
<input type="submit" id="help_submit" value="Submit Help Request" />
However when I try to fire the event, the form doesn't pop up with the Message Box and submits anyway.
I check the developer tools in Chrome and I see the following error:
Uncaught TypeError: Cannot set property 'onclick' of null
Where did I go wrong with the coding?

It seems likely that you are running your Javascript too early before the DOM has loaded and thus document.getElementById('help_submit') does not find the DOM element because it is not yet in the page. You can fix this by moving the script that contains this code to right before the </body> tag so all DOM elements will be present when the script runs. For more details on this issue, consult this answer: pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it.
In addition, your submit handling code needs to prevent the default action of the submit button or the form will submit anyway. Though, if you don't want the form to submit, then you should just stop using a submit button and use a regular button.
In addition to moving the script to the end of the DOM, I'd suggest you change your event handling code to this:
document.getElementById('help_submit').addEventListener('click', function (e) {
e.preventDefault();
window.alert("You clicked on the Submit Button on the Help Request form.");
});
Working demo: http://jsfiddle.net/jfriend00/vcjtv0kz/

I'm not experienced in JavaScript, but, following on the comment and the answer already given, try changing your code the following way:
Remove the given code (it will be used differently at the next steps).
Inside the script tag inside the head element, try creating two functions called, say, initialization and message:
function initialization()
{
element = document.getElementById('help_submit');
element.addEventListener( 'click', message, false );
}
function message()
{
window.alert("You clicked on the Submit Button on the Help Request form.");
}
At the end of this script tag, write the following:
window.addEventListener( "load", initialization, false );

Related

Javascript Form Submission issue

I need to get a form to submit but when it submits I need it to disable the button because the query takes a few seconds to run and the people using this form don't understand loading pages and so they will click 5 or 6 times on the button submitting the form way to many times. I had a working method in Chrome but in IE it submits twice and I know why but I don't know how to get it to work for both. Here is the form line:
<form method="post" id="submitItem" action="secondPage.php">
I have tried various versions of this such as using onSubmit or other related ideas but none work. The "Working" solution in chrome that submits twice in IE is that form call and the following JS:
$( document ).on( "click", ".once-only", function(){
$(".once-only").prop('disabled', true);
$('form').submit();
});
The class "once-only" is attached to the submit button so upon clicking submit that button gets disabled in both browsers but because I have "action='....'" in the form instantiation line it submits using that and the ".submit()". Chrome does not submit using the action but only the ".submit()". Is there a way to get this working? I have tried a large combination of changing the JS to use a function or taking out the ".submit()" or even changing what is in the form line but I haven't figured one out. Any ideas? IE has been giving me problems with this site anytime I use JS, the AJAX only works in chrome for all my other pages so I REALLY hate using IE but more than half the people using the site don't even know what chrome is. Any tips? I can share any other code if needed!
Try this:
$( document ).on( "click", ".once-only", function(event) {
event.preventDefault(); //this should disable the default form submit action
$(".once-only").prop('disabled', true);
$('form').submit();
});
but in IE it submits twice
For that you can first off or unbind the click followed by on
// If the button is not dynamically generated , there is no need to delegate the event
$('.once-only).off('click').on( "click",function(event){
// Rest of the code
})
For second issue
you can either use button type = "button" then use ajax instead of form action
Alternately you can use button type="submit"
$('.once-only').off('click').on( "click",function(event) {
event.preventDefault(); //prevent default behavior
$(".once-only").prop('disabled', true);
$.ajax({
url:'some url'
//Rest of code
})
});
Note ajax also works in IE
edit
or like this: onclick="this.form.submit();this.enabled=false;"
so the real answer is this
onclick="setTimeout((function(){ this.disabled = true; }).bind(this),0);"
explanation: this instructs the browser to disable the button later; since JS works in event loop, you enqueue a time-out event that'll do it outside that onclick event.
i think it is just stupid of chrome to make me do this trick.

Assign event to button from external library

Every time I press a button, there is a random chance that a alertify alert window popups. The alertify alert popup is something I use instead of javascript Alert, just to get a nicer design.
Alertify library
And here is a screenshot of the current situation:
I want to assign a event to the OK button. When I use the "inspect element" function in google chrome, I see that this green OK button has an id called "alertify-ok", so I want to assign an event when this button is pressed.
I've tried to add this part to my HTML document in the script part:
$( "#alertify-ok" ).on( "click",function() {alert("finally");});
But nothing happens. The reason why I need this to work, is that the youtube popupmodal should come up right after I've pressed the OK button. I belive the error comes because the alertify window with HTML is from an external library, so how can i do this?
Alerts and the others take callback functions on creation, https://github.com/alertifyjs/alertify.js/blob/0.3.12/src/js/alertify.js#L608. You don't need to attach another event listener, just give it the function you want it to execute. example below:
alertify.alert("alerttext", function(e) {
functionIWantToCall();
});
You can put the event on an element you know is already existent (like "body") and specify it to trigger only when the wanted element is clicked:
$(" body").on({
click: function () {...
}
}, "#trigger");

jQuery blur event firing on load, instead of when expected

I'm working on a project which will require some form validation, which I'm using jQuery for.
There's a field where a user will enter their email, and once they have filled out that field I want to check it.
Currently, the first part of my JavaScript looks like this:
$(window).load(function()
{
var email = $("#registerEmail");
email.blur(alert("stuff")); //will call a validation function
Right now, I get the "stuff" alert as soon as the page loads. My understanding was that blur would only fire once an element gained focus and then lost it -- am I misunderstanding this? Shouldn't this alert only execute once a user clicks or types in the email form and then clicks or types somewhere else, rather than immediately when the page loads?
You are actually executing the alert function when you do it that way. You need to provide a function that can be called later. Do
email.blur(function () {
alert("stuff");
});
$(document).ready(function(){
$("#registerEmail").blur(function(){
//your alert here
});
});

What triggers an HTML form to submit?

I apologise in advance for not being able to provide any actual code, as the problem appears in a page which is currently private :-/ Please bear with me.
I have an HTML form. I attached a (proprietary) calendar widget to one of the text input fields. When the user tabs into the field the calendar appears. On the calendar there are a couple of buttons (to move to the previous/next month). When the user clicks on one of these buttons the calendar updates itself accordingly, but also - the form submits! There's NOTHING in the calendar code that touches anything other than the calendar itself and the text input field it is attached to, let alone submits a form! I would appreciate any clue regarding any of the following questions:
1) What could possibly have submitted the form in such a setting?
2) What things generally submit a form, other than clicking on the submit button or hitting the enter key? (In particular, do ordinary buttons submit forms? Under which circumstances?)
3) As a workaround in case I don't manage to figure this out, is there a way to simply totally disable submitting the form (and then reenable it in an event handler attached to the submit key)?
Note(s): The calendar behaves normally other than that - responds normally to key events and to click events on the dates themselves (which are not buttons). I tried this on both Firefox and Chrome and got the same behaviour. I tried to follow the click event handler step-by-step with FireBug, and everything seemed perfectly normal - but the moment it finished the form was submitted (and the page reloaded). The widget uses jQuery 1.7.2. Any help in understanding and/or solving this will be most appreciated!
Sorry to answer my own question, but none of the given answers was complete, even though I've learnt from them and from the comments! Thanks for everyone who participated!
So:
1+2) Buttons defined by the <button> element cause submits (as if they had type="submit" set. At least in some browsers). If one wants a button not to cause a submit one should use <button type="button">, or the good old <input type="button" />.
3) (Unnecessary for me now, but it was part of the question.) There are many ways to prevent a form from submitting. Three of them are:
to handle the onsubmit event, preventing the submit (by return false; or - preferably! - by e.preventDefault();) in case a flag is not set; set the flag when handling the event(s) that should actually submit the form
to handle the onsubmit event and prevent the submit as above if the element that triggered the event is not (one of) the element(s) we want to cause a submit
to set the form action to non-action, i.e. action="#", and to have the handler for the event that should actually submit the form set the action to the proper address
The calendar can submit your form in its JavaScript source code by calling form's submit() method using jQuery or plain JavaScript.
Here is an example how to disable the form submit and allow it only in case of pressing the button.
<form id="form">
<input type="text" />
<input type="button" name="submit-button" value="Submit"/>
</form>​
<script type="text/javascript">
var form = document.getElementById('form'),
button = form['submit-button'];
form.onsubmit = function(e) {
return !!form.getAttribute('data-allow-submit');
};
button.onclick = function() {
form.setAttribute('data-allow-submit', 1);
form.submit();
};
</script>
Demo
The calendar code isn't calling submit() somewhere?
3) As a workaround in case I don't manage to figure this out, is there a way to simply totally disable submitting the form (and then reenable it in an event handler attached to the submit key)?
Unfortunately, I'm not totally sure if it's reliable that the click handler will be called before the form submit event.
( function () {
var prevent_submit = true;
$( "form" ).on( 'submit', function ( event ) {
if ( prevent_submit ) {
event.preventDefault();
}
} );
$( "input[type='submit']" ).on( 'click', function ( event ) {
prevent_submit = false;
} );
} )();
or
$( "form" ).attr( { action : "#", method : "post" } );
$( "input[type='submit']" ).on( 'click', function ( event ) {
event.target.form.action = "...";
} );
Hitting enter on text fields can sometimes trigger a form submit. See here. Especially if that is the only element in the form. One way to control the post back is to set the action to empty and fire off the event yourself with Javascript.
Check the placement of the closing form tags. I had this problem once and I finally figured out that there was some 'permissions' code within the form itself that prevented the user from reaching the closing tag because he didn't have the proper permission level to submit it. In effect this left an open form tag that then responded to other buttons elsewhere on the same page.

How do I debug why handler for "click" JavaScript event doesn't get called?

I've installed a handler for the click JavaScript event of a <button> element using the jQuery API, but the handler doesn't get called when the button is in fact clicked. How can I debug why the event handler isn't invoked? I'm developing in Visual Studio 2010 and debugging with the help of Google Chrome Developer Tools.
I'm new to JavaScript and don't know the debugging methods :)
EDIT
This is the HTML declaration of the button in question:
<button id="start-lint">Submit</button>
The relevant JavaScript:
$('button').button();
var btn = $("button#start-lint");
log.debug("Button: %s", btn);
btn.click(function () {
log.debug("Button clicked");
});
Let me know if more information is needed.
EDIT 2
Somehow I got it working, not sure what was wrong in the first place, but at least now I know how to tell if an element was found or not!
You can only debug if the code is actually fired, which it seems to not be.
You could try to see if its even finding the selector using length.
alert($("#myselector").length);
or
console.log($("#myselector").length);
For debugging javascript i recommend you to use FIREBUG for Firefox (http://getfirebug.com/) - you can set breakpoints, write to console etc, and it gives all possible displays of variables, objects etc.
Tutorial can be found here: http://www.youtube.com/watch?v=2xxfvuZFHsM
(You said you where new to jQuery/Javascript, so hope it helped :D)
Inline JavaScript is executed as the page loads, so if the button is defined after the JavaScript the code won't find it and so can't attach the handler. You need to put that JavaScript in the document ready (or onload) function, which means it will be executed after the button (and everything else on the page) has loaded, and/or put it after the button in the source.
I'm guessing that the $('button').button(); throws an exception, and the rest of your code isn't executed. Comment out that line and see if it works.
Original reply:
Paste your code, or the relevant parts of it.
Add a debugger; statement to your handler function to see if you are entering it.
If not, then there is a problem with how you're registering the handler.
If you are entering it, maybe there is a problem with the handler itself.
your button may look like this
<input type="button" value="Click" />
for this you bind a click handler like
$(document).ready(function(){
$("input[type='button']").click(function(e){
alert("somebody clicked a button");
});
});
http://jsfiddle.net/6gCRF/5/
but the drawback of this approach is it will get called for every button click, to prevent that you might want to add an id to your button and select that specific button e.g.
<input type="button" value="Click" id="specific" />
attach a click handler to it like
$(document).ready(function(){
$("#specific").click(function(){
alert("specific button clicked");
});
});
http://jsfiddle.net/6gCRF/4/
EDIT
in your case select the button by id
$(document).ready(function(){
$("#start-lint").clcik(function(){
console.log("clicked");
});
});
you can also use the pseudo :button selector
$(document).ready(function(){
$(":button").click(function(e){
console.log("clicked");
});
});
have a look at jquery selectors

Categories

Resources