How to display require popup manually? - javascript

I'm trying to display the require popup when a certain input is not filled or isn't filled correctly in my form. So, for doing this, I've created this form:
<form id="login">
<input class="form-control require" type="email" placeholder="username" ></input>
<button type="submit">
go
</button>
</form>
and I put the logic inside a js function:
$('#login').submit(function(event)
{
event.preventDefault();
$(event.target).find('.require').each(function()
{
if($(this).val().length == 0)
{
this.setCustomValidity("Field Required!");
}
else
{
this.setCustomValidity('');
}
});
console.log('ajax execution');
});
Now how you can see when the form is submitted I prevent the default event submit, and assign to each control a custom validation error. Now the problem's that if a field is not valorized correctly, for example is blank I get no popup displayed, instead, if I press again the submit button I can see the require popup appear on the UI.
Someone could help me to fix this?
I put an example JSFIDDLE here.
When you press the button for the first time no popup appear, the second time appear correctly but, this should appear the first time or anyway, each time that a particular field is not valid.

if($(this).val().length == 0) this code will not properly if the input field has only space . To avoid that u should use this:
if($.trim($(this).val()).length == 0)
OR
if($.trim($(this).val()) == "")

Your problem seems to be that the submit event is only firing once. I'm not familiar with bootstrap, so I haven't seen the setCustomValidity function before but I would guess that it is probably attaching its own listener, which is prevent the button click from triggering the submit at all.
I notice that if I type something into the text box, and fire setCustomValidity on it, it says "please enter an email address" - which I don't see in your code. If I then enter 'asdf#qwer.dfsgh', it gets validated and submits.
So it looks like you have not understood how setCustomValidity is supposed to be used. I would guess, you are probably supposed to attach it once, when the page first loads, and not repeatedly as you are doing.

Related

Submitting Form on Enter Press

I know that this question has been asked before but I'm having particular trouble submitting my form when I press the enter key. I've tried multiple solutions but none have worked. When I try to press enter, the page refreshes and my typing is gone.
This is my HTML:
form class="nput">
<h1 class= "header">Member Login</h1>
<label class="text" for="pswd">Enter your password: </label>
<input class="form" type="password" id="pswd">
<input id="yeet" class="bttn" type="button" value="Submit" onclick="checkPswd();" />
</form>
And this is my Javascript:
<script type="text/javascript">
function checkPswd() {
var confirmPassword = "password";
var password = document.getElementById("pswd").value;
if (password == confirmPassword) {
window.location="members.html";
}
else{
alert("Password incorrect. Please try again.");
}
}
// Get the input field
var input = document.getElementById("pswd");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
alert("hi there");
event.preventDefault();
document.getElementById("yeet").click();
}
});
</script>
I cannot figure out this small issue and I would appreciate any help! Thanks!
EDIT: I just wanted to let everyone know that I do in fact know that there is little security that comes with this method but I mostly want the password for looks not function.
You got something backwards there - you are submitting the form with Enter. This is exactly the problem though, it seems as if you don't want to submit it, instead you want to run your client-side handler checkPswd. (You do know that everyone can read the correct password in their browser console though, right? So it's no protection.)
What you want to do is change the onclick on the button to an onsubmit on the form itself! Then your code will run no matter in what way (keyboard or mouse) the form is submitted.
You can delete the whole keyup stuff then.
(The reason your attempt to "click" the button in JavaScript wasn't working is because unlike jQuery's click method, the vanilla click will only execute the default action and not any attached click event handlers like yours. Also, it is kinda backwards because you should react on the common ground of both clicking the button and pressing Enter, which is submitting the form.)
To echo a comment above - you want to use the onsubmit handler on the <form> element - this will allow users to submit the form both by clicking the <button type="submit> button, and by hitting the enter key in one of the forms <input> elements.
You can probably ditch the input.addEventListener("keyup", function(event) {...} altogether by just using the obsubmit handler.
You can learn more about the HTML <form> element's onsubmit behavior here:
https://www.w3schools.com/tags/ev_onsubmit.asp
No need to put handlers on button element. You should use either input type as submit or button type as submit. onsubmit handler can be given to form element where you can actually prevent default event and go ahead with password validation .
Hope this gives you an idea.
If I were you, I would do two things:
1) I would check the Chrome debugger to see if there are any issues with your code
2) Instead of input.addEventListener("keyup", function(event) {, I would try input.onkeyup = function(event) { and see if that works.
Hope this helps.

Narrow Down BeforeUnload To Only Fire If Field Is Changed or Updated

I am trying to figure out how to limit the beforeunload command on my form. I have been able to figure out how to unbind the beforeunload command and then when I go to navigate away from the form this works. However, the unload happens every time regardless of whether or not the form was changed. I'm trying to figure out how to get the beforeunload to only fire if the form was actually updated or changed. If the user clicks the back button on the browser, the beforeunload does not fire. This is perfect. However, if the user clicks on a link on the "form" it pops up the beforeunload prompt. Is this as designed? Perhaps I should be approaching this differently? I'm a newbie..so I'm open to suggestions.
I have read through the MDN link that explains beforeunload...https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload
and can't seem to figure out how to narrow down the beforeunload to only if a field on the form has been changed.
$('form').submit(function() {
$(window).unbind('beforeunload');
});
$(window).on('beforeunload',function(){
return '';
});
I am trying to figure out how to alter the code above so that the beforeunload only fires if a field on my form changes when the user goes to navigate away from this page. It's confusing for the user if there is a pop up asking if they want to navigate away from the page if nothing has been clicked or changed.
Something like this.
We check out simple form and only prompt user if there is a value.
Added variable set when submitting, this allows us to bypass our onunload tests.
var submitting = false;
window.addEventListener("beforeunload", function (event) {
console.log('checking form');
let inputValue = document.querySelector('#myInput').value;
if(inputValue.length > 0 && submitting === false) {
console.log(inputValue);
event.returnValue = 'Are you sure you wish to leave?';
}
event.preventDefault();
});
document.addEventListener("submit", function(event) {
submitting = true;
});
<form submit="somewhere.htm">
<input id="myInput" type="text" />
<input type="submit" value="Submit">
</form>
Test navigate away

Bootstrap form input: prevent submit, but allow for input checking

I've got the following problem:
I use bootstrap form to take input from users, and I use jQuery preventDefault() to disable the submit button from sending the form (I use AJAX instead). However, that function also prevents input checking that is done by bootstrap. For example, if someone enters an e-mail without '#' into
<input type="email" class="form-control">
bootstrap would, upon clicking submit, check that input and return a popup with an error.
My question is: how to prevent the request being sent while keeping the bootstrap form checking mechanism intact?
What I have tried: using preventDefault() and writing my own checking script, however this seems like reinventing the wheel and having extra code when it's not needed.
Thank you!
I believe you are talking about the native HTML5 form validation and not validation by bootstrap its self, I have never come across bootstrap validation before. (i may be wrong though).
Most new browsers will validate <input type='email'/> as an email address and <input type='text' required='required'/> as required on form submission.
If for example you are using e.preventDefault(); on the click event on the submit button the form will never attempt to submit and hence the native validation will never happen.
If you want to keep the validation you need to use e.preventDefault(); on the submit event of the form not the click event on the button.
The html...
<form action='' method='post'>
<input type='email' name='email' required='required' placeholder='email'/>
<button type='submit'>Submit</button>
</form>
The jQuery...
//this will stop the click on the button and will not trigger validation as the submit event will never be triggered
$("button").on('click',function(e){
e.preventDefault();
//ajax code here
});
//this will stop the submit of the form but allow the native HTML5 validation (which is what i believe you are after)
$("form").on('submit',function(e){
e.preventDefault();
//ajax code here
});
Anyway hope this helps. If I have misunderstood in any way let me know and ill try to assist further.
I had the same issue, I came to use "stopPropagation" as the way to stop the form submission. But after a little reading on jQuery 3, I realized that "preventDefault" was enough to what I wanted.
This caused the form validation to happen and the submit event didn't proceed.
(This example is of an attempt i had on my own).
$('form').on("submit",function( event ) {
if ( $('#id_inputBox_username').val().length == 0 &&
$('#id_inputBox_password').val().length == 0 ) {
event.preventDefault();
$('#id_inputBox_username').tooltip('show');
$('#id_inputBox_password').tooltip('show');
} else if ( $('#id_inputBox_username').val().length == 0 ) {
event.stopPropagation();
$('#id_inputBox_username').tooltip('show');
} else if ( $('#id_inputBox_password').val().length == 0 ) {
event.stopPropagation();
$('#id_inputBox_password').tooltip('show');
}
});
I had the same problem and I find this solution:
$('#formulario').on('submit', function (e) {
if (e.isDefaultPrevented()) {
// handle the invalid form...
} else {
// everything looks good!
e.preventDefault(); //prevent submit
$(".imprimir").show();
$(".informacao").fadeOut();
carregardados();
}
})

Jquery: one call triggered by multiple events

I have a simple search page with a single input box.
I want to be able to trigger the search action either by clicking "Go" or by pressing Enter in the input box. I did it like this:
$("input[name='entry']").keyup(function (event) {
if (event.keyCode == 13) {
search_phone();
}
});
$('a#go').click(function () {
search_phone();
});
Is there a more elegant way to do this? Like with bind and trigger, or fling. If so, how?
Not much can you improve here. Your code is pretty good.
You could skip the anonymous function for the click event.
$('a#go').click(search_phone);
I would just make your "go" link the submit button
<input type="submit" name="submit" value="go"/>
And then just bind your function to the submit (which would happen either from pressing enter while in the text box or by clicking the go button.
$('#my_form').submit(search_phone);

When editing a text input, how do I do a specific JavaScript action on hitting "Enter" key without the form's onSubmit handler?

I have an HTML input text field.
How can I perform a specific JavaScript call when hitting "Enter" button while editing that field? Currently, hitting "Enter" reloads the entire page, presumably due to submitting the entire form.
NOTE: This HTML/JS code is merely included as a portlet into a large HTML page for a portal, which has one large master form wrapped all the way around my code. Therefore I can not control the form - can't change onSubmit event or action or wrap my INPUT field into a smaller form - otherwise the solution would be obvious :)
Also, a solution that does not involve adding a visible button to the form is strongly preferable (I don't mind adding a button with display:hidden if that's what it takes, but my attempt to do so didn't seem to work).
This needs to be straight up JS - no Query/Prototype/YUI is available.
P.S. it's a search field and the action will be a call to an existing in-page JavaScript search method, if someone's curious.
Thanks!
Assuming you have a text input something like
<input id="myTextBox" name="foo" value="bar">
... you could do something like this, after the document has loaded, and it will work in all mainstream browsers:
document.getElementById("myTextBox").onkeypress = function(evt) {
evt = evt || window.event;
var charCode = evt.keyCode || evt.which;
if (charCode == 13) {
// Suppress default action of the keypress
if (evt.preventDefault) {
evt.preventDefault();
}
evt.returnValue = false;
// Do stuff here
}
};
Include the following javascript
<script type="text/javascript">
function noenter() {
return !(window.event && window.event.keyCode == 13);
}
</script>
Add the following attribute into the input element that you wish to prevent the submit
onkeypress="return noenter()"
Of course you can perform some other event if you wish...
Would you be better off using the document object to detect the Enter action? That way you need make no changes to the HTML form tags. You can assign the search function to the button, although if it's hidden I am not sure how the user would click on it, or you could use something like onblur to capture the user tabbing out of the input control.
Try adding an attribute "action=javascript:void(0)" as in the example below.
Enter will trigger the same action as clicking on the submit button, but won't reload the page automatically.
<html>
<head></head>
<body>
<div id="status"></div>
<form action="javascript:void(0)">
<input type="text" />
<input type="submit" value="submit" onclick="document.getElementById('status').innerHTML = 'submitted';"/>
</form>
<script>document.getElementById('status').innerHTML = 'page loaded';</script>
</body>
</html>

Categories