Do html validation without calling javascript function on submission of form. - javascript

I have a form which has a textarea:
<form id="hello">
<textarea id="Testarea" required></textarea>
</form>
<button id="myButton" type="submit" value="Submit">Click me!
</button>
When the user submits the form, I listen to it via a jquery handler:
$("#myButton").click(function () {
alert("blah");
});
However if the textarea is empty, I want an error to be thrown without calling my function. Right now, my function is called even if the textarea is empty.
https://jsfiddle.net/8dtsfqp0/

Use a submit handler on the form, not a click handler on the button.
Here is the order of execution when you click on a submit button:
Button's click handler is called. If it calls event.preventDefault(), the process stops.
The form is submitted, which performs the following steps:
Validate input fields. If any validation fails, the process stops.
Call the form's submit handler. If it calls event.preventDefault(), the process stops.
The form data is sent to the server.
So if you want to prevent your function from being called, it has to be after the "Validate input fields" step. So change your code to:
$("#hello").submit(function () {
//Throw error if textarea is empty
alert("Her");
});
Fiddle

you can try this:
$("#myButton").click(function () {
if($('#Testarea').val().trim().length > 0)
{
return true;
}
else
{
alert("empty text box");
return false;
}
});

<script type="text/javascript">
document.getElementById("myButton").addEventListener("click", myFunction);
var problem_desc = document.getElementById("Testarea");
function myFunction() {
if (problem_desc.value == '') {
alert("blank");
return false;
}
else{
alert("working");
}
}
</script>

Related

Form still submits, trying to use e.preventDefault();

So I have this form. I want to check if user has validaty the captcha, but have problems. Here is the form, that checks the function.
<form data-id="embedded_signup:form" id="myForm" class="ctct-custom-form Form" name="embedded_signup" method="POST" action="https://visitor2.constantcontact.com/api/signup" onsubmit="check_if_capcha_is_filled()">
Here is the function that determines whether doSubmit (the captcha) has been validated.
function check_if_capcha_is_filled(e){
if(doSubmit) return true;
e.preventDefault();
alert('Fill in the capcha!');
return false;
};
But I get an error
Uncaught TypeError: Cannot read property 'preventDefault' of undefined
at check_if_capcha_is_filled
Any pointers to what I am missing? Thank you.
Your e.preventDefault is being used incorrectly. It will do nothing because you're passing an event to a function, you want to attach it to the event handler like this:
$('form').on('submit', function(e)
{
e.preventDefault();
//rest of code
})
this will stop the submit action.
refs: http://api.jquery.com/event.preventDefault/
Is this what you want?
<form data-id="embedded_signup:form" id="myForm" class="ctct-custom-form Form" name="embedded_signup" method="POST" action="https://visitor2.constantcontact.com/api/signup">
Then in your js file:
function check_if_capcha_is_filled(){
if (doSubmit){
return true;
}else{
return false;
}
};
$('#myForm').on('submit', function(e){
if (!check_if_capcha_is_filled){
e.preventDefault();
}
});
You have two issues here. Firstly you need to return the function from the onsubmit event attriubute. Secondly, you're not passing the event in to the function - however this will only work where a global event is available, ie. not Firefox.
To fix the issue, and improve your logic, you can instead use addEventListener() to unobtrusively add the event handler to the element, and remove the outdated on* event attribute. Try this:
var doSubmit = false;
document.getElementById('myForm').addEventListener('submit', function(e) {
if (doSubmit)
return;
e.preventDefault();
alert('Fill in the capcha!');
});
<form data-id="embedded_signup:form" id="myForm" class="ctct-custom-form Form" name="embedded_signup" method="POST" action="https://visitor2.constantcontact.com/api/signup">
<button type="submit">Submit</button>
<form>
Use on event listener
change it to
<form data-id="embedded_signup:form" id="myForm" class="ctct-custom-form Form" name="embedded_signup" method="POST" action="https://visitor2.constantcontact.com/api/signup" >
$('form').on('submit', function(e){
// validation code here
if(!valid) {
e.preventDefault();
}
});
Using jQuery and if you want to confirm the submit.
<button name="delete" class="submitbutton">Delete</button>
$('.submitbutton').click(function() {
var buttonpressed;
buttonpressed = $(this).attr('name');
var r = confirm("Please confirm to " + buttonpressed );
if (r == true) {
$('#yourformid').submit();
} else {
return (false);
}
});

JavaScript function getting called twice on Enter key press

I have a button in my html page
<input id="btnLogin" class="loginBtn" type="button" value="Login" title="Login" />
I have binded a jquery click event to this button like
$('#btnLogin').click(function () {
ValidateLogin();
});
I'm also checking the enter key press to call the same function ValidateLogin(); like below
$(document).keypress(function (e) {
if (e.which == 13) {
ValidateLogin();
}
});
The issue that i'm facing is when the user presses the tab key to get in focus over the Login button and then press Enter Key the ValidateLogin() is called twice.How to deal with this situation.
Note : i can't use type="submit" to do a form submit ..since i'm using ajax call on button click
You should use the submit event instead. Your browser is probably firing the click event when pressing enter and that is effectively the same as pressing the submit button:
$("form").submit(function(e) {
// Stop the form submitting
e.preventDefault();
ValidateLogin();
});
function ValidateLogin() {
$.ajax({
// ...
}).done(function(e) {
if(!e.valid) {
alert("Invalid Login");
}
});
}
Second reason, even if your keypress was to work correctly, I can press a button by pressing spacebar too.
Here is a full Fiddle to demonstrate.
Since it's a form I would prefer to attach event on form elements instead on document.
Use form element like text, textarea etc. on click of enter should submit the form.
$('input:text, textarea').keypress(function (e) {
if (e.which == 13) {
ValidateLogin();
}
});
In your case event is bubbled from the button to document hence it is called twice.
Its working fine check this fiddler DEMO
<input id="btnLogin" class="loginBtn" type="button" value="Login" title="Login" />
$('#btnLogin').click(function () {
//ValidateLogin();
alert('click');
});
$(document).keypress(function (e) {
if (e.which == 13) {
//ValidateLogin();
alert('enter');
}
e.preventDefault();
});

How to run a function just before the form post happens?

I have a form which posts some data to the server
<form action="action.html" method="post" id="formComments">
// controls, etc
</form>
<script>
function validateFormJustBeforePost()
{
//
return true;
}
</script>
Just before the form is posted, I'd like to run a script which returns true or false.
If true it should continue with the post, otherwise not (an error message will be shown)
The form post can happen on clicking a button inside or outside (page menu) the form above.
How to achieve that?
I ran the below but it never alerts:
$(document).ready(function(){
$('form').submit( function()
{
alert("Something");
});
});
onsubmit event handler, for example
<form onsubmit="return validateFormJustBeforePost()" ... >
or in <script>:
document.getElementById('formComments').onsubmit = validateFormJustBeforePost;
or, the most proper way
function validateFormJustBeforePost(e){
if( invalid ){
e.preventDefault()
return false;
}
}
document.getElementById('formComments').addEventListener( 'submit', validateFormJustBeforePost);

problems in checking the form input values before submitting using JQUERY

my code is as follows
$(document).ready(function() {
// this is a button to add the form to the DOM tree.
$("#submitPara").click(function() {
$("body").append('<form id = "dimensionAndObjects" action = "#"></form>');
some code to add some input fields, omitted...
$('#dimensionAndObjects').append('<p><input id = "submitDO" type = "submit" value = "submit"></input></p>');
return true;
});
$('#dimensionAndObjects').submit(function() {
alert("haahhhahhaha");
return false;
});
});
it seems that the submit function doesn't work because the alert info doesn't appear.
if i put the submit function inside the click function, it doesn't work either.
what's wrong? I am a totally freshman to jQuery, thanks in Advance!
since the form is created dynamically you need to use event delegation
$(document).on('submit', '#dimensionAndObjects', function() {
alert("haahhhahhaha");
return false;
});
$('#dimensionAndObjects').live('click',function(e) {
e.preventdefault();
alert("haahhhahhaha");
return false;// for not submit the form
return true ;// for submit the form
});

JavaScript button function swap

What I am trying to do is following:
I have an input type button and I want to replace it's function on first click.
<input type="submit" class="submit-button" value="Submit" name="boom" />
So a [button] that serves for submit, I wanna show alert with some jquery plugins but lets do it here with normal javascript alert (default window).
So on first click it will be
alert('Something');
And on second click it will be default function (submit).
How can I achieve something like this?
Of course if button is clicked once, and then page reloaded, it will show same alert again on first button click.
Use one().
Attach a handler to an event for the elements. The handler is executed at most once per element.
Example:
$(".submit-button").one("click", function(e) {
// will only run on first click of element
e.preventDefault();
alert("Something");
});
Try this:
<script type="text/javascript">
var clicked = false;
function btnClick(e) {
if(clicked === false) {
alert('Something');
clicked = true;
e.preventDefault();
return true;
} else {
return false;
}
}
</script>
<input type="submit" onclick="btnClick(event)" class="submit-button" value="Submit" name="boom" />

Categories