setCustomValidity Bootstrap keep error popup - javascript

I've implement localization in my application, all this stuff is saved inside a php file. So I can easy do this:
<input class="form-control" type="text" required="" placeholder="username" oninvalid="this.setCustomValidity('<?php echo $this->lang->line('field_required'); ?>')"></input>
Now if I doesn't enter any text I can see the custom message, but if I fill the input I see again the popup as the form can't get the text inside.
It's a bug of Bootstrap?
EXAMPLE
https://jsfiddle.net/DTcHh/23662/

Using the onvalid won't work in some browsers like Safari or IE below 10. Use a custom event notifier for attaching the function.
Note: As you mentioned in the comment you can print the message from the data-invalid-message attribute from php and catch it using jQuery by .data('invalidMessage').
SEE WORKING EXAMPLE:
var myobj = jQuery('input.form-control');
myobj.on('keyup keypress blur change input', function() {
var messg = ($(this).data('invalidMessage'));
if (this.validity.typeMismatch) {
this.setCustomValidity(messg);
} else {
this.setCustomValidity('');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<form>
<input class="form-control" type="email" required placeholder="username" data-invalid-message="custom message from php here">
<button type="submit">
go
</button>
</form>

a workaround that I've found is:
onkeyup="this.setCustomValidity('');
the bug will be gone now.

TL&DR
Check element.validity.typeMismatch and then element.setCustomValidity('custom error msg') or element.setCustomValidity('') if there's no mismatch. You should listen on both keyup and blur events.
Explanation in Mozilla Developer documentation about setCustomValidity: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Forms/Data_form_validation#Customized_error_messages.
But just keyup won't work properly if focus is not inside the input box we're modyfing.
Our previous example won't transfer the current state of the input box
if the user mouses away and clicks elsewhere on the page. We update
the component's values property only when the user presses Enter while
the focus is inside the input box.
Let's fix that by listening to the input box's blur event as well.
Above is from Angular 2 docs: User Input, paragraph "On blur" https://angular.io/docs/ts/latest/guide/user-input.html.
Simplified example
Below is example from Mozilla documentation with added blur keyEvent listener. Yup, refactoring needed, but mine version in Angular 2 looks vastly different and so probably will yours.
<form>
<label for="mail">I would like you to provide me an e-mail</label>
<input type="email" id="mail" name="mail">
<button>Submit</button>
</form>
And then
var email = document.getElementById("mail");
email.addEventListener("keyup", function (event) {
if (email.validity.typeMismatch) {
email.setCustomValidity("I expect an e-mail, darling!");
} else {
email.setCustomValidity("");
}
});
email.addEventListener("blur", function (event) {
if (email.validity.typeMismatch) {
email.setCustomValidity("I expect an e-mail, darling!");
} else {
email.setCustomValidity("");
}
});

Related

If the text-box value in HTML5 form is x, then y: Is that possible?

So basically, I want to enter a certain string into a text-box, and check what it is. It's basically for a command system that I'm trying to implement. There's a little Terminal pop-up and there is a text-box in it waiting for a command. This is the HTML I used to make the text-box inside a form:
<form id="command-input">
<input type="text" placeholder="Enter Command" id="command-box">
<input type="submit" style="display: none">
</form>
I made the submit invisible so you could press enter and it would submit the form. Here is the JavaScript I'm using:
function changeStyle(sheet) {
document.getElementById('specific-sheet').setAttribute('href', sheet);
}
var command = document.getElementById('command-input');
if(command.value=="windows"){
changeStyle('../css/windows-xp.css');
}
I want to make it to where if I type "windows" into the command box and hit enter, it will change my stylesheet. The people on this website are smart, so I once again am asking for help. Thanks for contributing!
You will need to check with an event. Assuming this is in the plain tags; you can use the following:
var inputbox = document.getElementById('command-input');
function changeStyle(sheet) {
document.getElementById('specific-sheet').setAttribute('href', sheet);
}
inputbox.addEventListener('input', function (evt) {
if (this.value == 'windows'){
changeStyle('../css/windows-xp.css');
}
});
Edit:
you can do this as well. Change the event to "onsubmit" if you want enter key to trigger.
function changeStyle(sheet) {
document.getElementById('specific-sheet').setAttribute('href', sheet);
}
document.getElementById('command-input').addEventListener(
'keyup',
function(eve){
if (eve.target.value == 'windows'){
changeStyle('../css/windows-xp.css');
}
},
false
);
If you want to keep the changes even after the page refresh you might have to keep the file path in the localstorage and use that in dom load event.
Also, you really dont need to wrap this in a form tag. You can use a simple div and this is not triggered by a form submit.
You could create a function that you can call on form submission as explained here at https://www.w3schools.com/jsref/event_onsubmit.asp.
<form onsubmit="myFunction()">
Enter name: <input type="text">
<input type="submit">
</form>
<script>
function myFunction() {
var command = document.getElementById('command-input');
if(command.value=="windows"){
changeStyle('../css/windows-xp.css');
}
}
</script>

Deactivating Smarty Streets functionality

I have a form with which I am using Smarty Streets Live Address validation. In general it works well. In the case where a user has begun entering address information, though, the Live Address validation can get in the way. The most specific problem encountered is in the case where address information has been entered but the user chooses to cancel the form. The Live Address validation takes precedence of operation and blocks attempts to deactivate the validation and clear the form.
A fiddle example of the issue can be found here.
<form>
<input type="text" id="street" name="street" placeholder="street"><br>
<input type="text" id="city" name="city" placeholder="city"><br>
<input type="text" id="state" name="state" placeholder="city"><br>
<input type="text" id="ZIP" name="ZIP" placeholder="ZIP"><br>
<button id="btnCancel">Cancel</button>
</form>
<script>
var ss = jQuery.LiveAddress({ key: '5640108848289556771', debug: true })
$(function () {
$("#btnCancel").click(function (e) {
e.preventDefault();
alert("click");
ss.deactivate();
});
});
</script>
When no data has been entered the click event works as desired, but once address information has been entered the Live Address validation prevents the event handler from firing.
On the click of the cancel button the form should be cleared or returned to the previous page, but instead the Live Address validation takes over and blocks all other actions.
How can the Live Address validation be deactivated on the button click event?
Your cancel button is mapped as the "submit" button on the plugin side. This means that the plugin recognizes that button to invoke verification when clicked. Verification will happen before actually performing any other actions which is what you are seeing. There are two solutions to working around this.
Add another button to your form. The plugin looks for the submit button with this selector "[type=submit], [type=image], [type=button]:last, button:last"
Line 48. If you add another button then your cancel button will be free and verification will not be invoked when clicked.
When you configure the plugin, set submitVerify to false. See the documentation here. This will disable verification for all buttons on your form. Verification will only happen when you click the plugin checkmark bubble.
Note: I work for SmartyStreets
It wasn't working if the last element was a button (even if I used event.stopPropagation();, so I used an A link.
To do this, I mapped the address fields, assigned an address ID and then used the activate() & deactivate() functions. This enabled me to allow an admin user to bypass the validation and post the form without entering anything. It checks for the visibility of the .smarty-tag checkmark to determine if it should activate or deactivate the validation.
<script type="text/javascript">
var liveaddress = jQuery.LiveAddress({
key: "key",
debug: true,
addresses: [{
id: 'AddressID',
street: '#Address',
street2: '#Address2',
city: '#City',
state: '#State',
zipcode: '#Zip',
country: '#Country'
}]
});
$(function(){
/* If re-editing and address is pre-populated, don't revalidate */
liveaddress.on("MapInitialized", function(event, data, previousHandler){
if ($('#Address').val().length !== 0){
liveaddress.deactivate('AddressID');
}
});
$('#toggleSS').click(function(e){
e.preventDefault();
if ($('.smarty-tag:visible').length){
liveaddress.deactivate('AddressID');
} else {
liveaddress.activate('AddressID');
}
});
/* If editing address, auto-enable verification */
$('#Address').keyup(function(){
if (!$('.smarty-tag:visible').length){
liveaddress.activate('AddressID');
}
});
});
</script>
<input type="submit" value="Save"> Toggle Verification

alert when user attempts to enter key into textbox

So I've been searching for a bit now for code that will alert a user with a message (I know how to do an alert) when they try to enter any sort of text into a blank textbox.
Here is my code. What do I add to cause the sendMsg() function to be called?
<script>
function sendMsg()
{
alert ("change msg content here");
}
</script>
here is the HTML:
<body>
<input type="text" name="">
</body>
This might work:
<input type="text" name="foo" onKeyUp="sendMsg()" />
i.e. if I understood your question.
Cheers.
Use the onchange event.
<input type="text" name="" onchange="inputChanged();">
Have you tried giving your input an ID:
<input id="testing" type="text" name="" />
And then your javascript would be:
document.getElementById('testing').onfocus = function() {
// alert("change msg content here");
}
The first thing you'll need to do is attach an event listener to the focus event of the text box (which is triggered when you "focus" on a text box), to do that you'll need some way of locating it in the DOM. The simplest way to do that would be to add an id attribute like so:
<body>
<input type="text" name="" id="msgContent">
</body>
Now you can use the document.getElementById method to find the element:
var textBox = document.getElementById('msgContent');
Then you can attach an event listener:
textBox.addEventListener('focus', function () {
alert('change msg content here');
});
Keep in mind that the addEventListener method isn't available in some older versions of IE, instead there are other fallbacks which are detailed here.
Finally if you're using a library like jQuery, YUI, etc you normalize the browser differences for attaching event handlers:
//jQuery example
$('#msgContent').on('focus', function () {
alert('change msg content here');
});

Getting inputs to auto-complete/suggest when preventing default form behavior

Interesting bug here that seems to be limited to IE and Webkit.
I have a basic form setup:
<div id="output">Form output is displayed here</div>
<form id="myForm" action="#" method="post">
<input type="text" name="username" id="usernameInput" />
<input type="submit" value="Submit" />
</form>
Now if I just submit the form through a normal page refresh, the next time I go to type text into the input field, I will get the browser's default auto-suggest dropdown (this is the intended behavior). However, if I highjack the form submission behavior in order to do an AJAX submit:
$('#myForm').submit(function () {
$('#output').text($('usernameInput').val());
return false;
});
Now when I submit the form, the output div updates, but the previous values that I input into the form aren't stored and no suggestions will be made when you type.
Does anyone have any creative solutions to this problem? Maybe an (gulp) iframe?
IE and WebKit only remember values that were submitted normally, and since you are submitting it through AJAX, those engines do not remember the values. Instead of an iframe, I would use a jQuery plugin for the autocomplete, like this one. Of course, with that solution, you will need to maintain a listing of what a user has typed in the past, which shouldn't be too hard.
test with these modifications in controlling submit:
$('#myForm').submit(function (e) {
e.stopPropagation();
$('#output').html($("#usernameInput").val() + "<br />");
});

Prevent form redirect OR refresh on submit?

I've searched through a bunch of pages, but can't find my problem, so I had to make a post.
I have a form that has a submit button, and when submitted I want it to NOT refresh OR redirect. I just want jQuery to perform a function.
Here's the form:
<form id="contactForm">
<fieldset>
<label for="Name">Name</label>
<input id="contactName" type="text" />
</fieldset>
<fieldset>
<label for="Email">Email</label>
<input id="contactEmail" type="text" />
</fieldset>
<fieldset class="noHeight">
<textarea id="contactMessage" cols="20"></textarea>
<input id="contactSend" class="submit" type="submit" onclick="sendContactForm()" />
</fieldset>
</form>
<small id="messageSent">Your message has been sent.</small>
And here is the jQuery:
function sendContactForm(){
$("#messageSent").slideDown("slow");
setTimeout('$("#messageSent").slideUp();$("#contactForm").slideUp("slow")', 2000);
}
I've tried with and without an action element on the form, but don't know what I'm doing wrong. What has annoyed me more is that I have an example that does it perfectly:
Example Page
If you want to see my problem live, goto stormink.net (my site) and check out the sidebar where it says "Send me and email" and "RSS Subscription". Both are forms that I'm trying to get this to work on.
Just handle the form submission on the submit event, and return false:
$('#contactForm').submit(function () {
sendContactForm();
return false;
});
You don't need any more the onclick event on the submit button:
<input class="submit" type="submit" value="Send" />
Here:
function submitClick(e)
{
e.preventDefault();
$("#messageSent").slideDown("slow");
setTimeout('$("#messageSent").slideUp();
$("#contactForm").slideUp("slow")', 2000);
}
$(document).ready(function() {
$('#contactSend').click(submitClick);
});
Instead of using the onClick event, you'll use bind an 'click' event handler using jQuery to the submit button (or whatever button), which will take submitClick as a callback. We pass the event to the callback to call preventDefault, which is what will prevent the click from submitting the form.
In the opening tag of your form, set an action attribute like so:
<form id="contactForm" action="#">
It looks like you're missing a return false.
If you want to see the default browser errors being displayed, for example, those triggered by HTML attributes (showing up before any client-code JS treatment):
<input name="o" required="required" aria-required="true" type="text">
You should use the submit event instead of the click event. In this case a popup will be automatically displayed requesting "Please fill out this field". Even with preventDefault:
$('form').on('submit', function(event) {
event.preventDefault();
my_form_treatment(this, event);
}); // -> this will show up a "Please fill out this field" pop-up before my_form_treatment
As someone mentioned previously, return false would stop propagation (i.e. if there are more handlers attached to the form submission, they would not be executed), but, in this case, the action triggered by the browser will always execute first. Even with a return false at the end.
So if you want to get rid of these default pop-ups, use the click event on the submit button:
$('form input[type=submit]').on('click', function(event) {
event.preventDefault();
my_form_treatment(this, event);
}); // -> this will NOT show any popups related to HTML attributes
An alternative solution would be to not use form tag and handle click event on submit button through jquery. This way there wont be any page refresh but at the same time there is a downside that "enter" button for submission wont work and also on mobiles you wont get a go button( a style in some mobiles). So stick to use of form tag and use the accepted answer.
Unlike most of the previous answers, the solution that is described here demonstrates how to prevent a page from refreshing/redirecting on <form> submission using pure Javascript, instead of JQuery.
The HTML form
Below is the HTML <form>. There is no need to use the onclick event (which fires when the user uses the mouse to click on a button) or the onsubmit event (which fires when the user hits the enter key) on the submit button. These events are taken care of by the JS code described in the following section.
<form id="myForm">
<input type="text" name="contactName" id="contactName">
<input class="submit" type="submit" value="Submit">
</form>
The JavaScript code
Below is the JavaScript code to handle the <form> submission on the submit event. The preventDefault() method of the Event interface tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be.
Note: Make sure to register the event handler after the HTML element is added to the DOM tree (when loading the webpage); otherwise, a runtime error will be caused, as you'll be trying to set a property (an event handler) of a non-existent object. One way to ensure this is to simply place the script after the element in question (i.e., <form>), but as this might be a bit dangerous—since you are relying on how you assume a browser works—you can assign the event handler after the initial HTML document has been completely loaded and parsed, using the DOMContentLoaded event. Example:
document.addEventListener('DOMContentLoaded', (event) => {
document.getElementById("myForm").addEventListener("submit", function(e) {
e.preventDefault() // Cancel the default action
sendContactForm();
});
});
All together
<!DOCTYPE html>
<html>
<head>
<script>
document.addEventListener('DOMContentLoaded', (event) => {
document.getElementById("myForm").addEventListener("submit", function(e) {
e.preventDefault() // Cancel the default action
sendContactForm();
});
});
</script>
</head>
<body>
<form id="myForm">
<input type="text" name="contactName" id="contactName">
<input class="submit" type="submit" value="Submit">
</form>
</body>
</html>

Categories

Resources