How to manually trigger bootstrap "required" tooltip alert? - javascript

When you submit a form via <input type="submit">
and some input with required attribute was empty, a little box appears near to the missing input box saying "Please fill out this field" or something similar (I use it in Italian so I don't know the exact wording used in English).
I need to manually trigger this tooltip alert using JavaScript, any idea how to achieve this?

The form validation is provided by HTML5, it's not related with Bootstrap, to disable the default form validation provided by the browser you have to work with the form containing the input, for example using the attribute novalidate will disable the default form validation provided by the browser. If then you want to use a custom form validation function you can use the onsubmit event on the form, so for example you will have something like:
<form onsubmit='return submitForm(this);' novalidate='novalidate'>
<input type='text' required>
<input type='submit'>
</form>
By doing this when the form is submitted you are passing the function submitForm the submitted form, so that this function is able to iterate through the elements of the form to check them.
Something like:
function submitForm(formToValidate){
var formValid=true;
var inputs = formToValidate.getElementsByTagName("input");
var errorDescription;
for(var i=0; i<inputs.length; i++)
{
var inputValid=true;
switch(inputs[i].type)
{
case "number":
if(inputs[i].hasAttribute("required")&&inputs[i].value=="")
{
inputValid=false;
errorDescription="Required field";
}
/*Check other attributes here (max, min, step, etc.)*/
break;
/*Check other types of input here*/
}
if(!inputValid)
{
markInputAsNotValid(inputs[i],errorDescription);
formValid=false;
break;
}
}
return formValid;
}
Note that the value returned by the function submitForm is used by the browser to determine if the submission was successful.
For more information: https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Form_validation

Related

Why is a form's onsubmit function only called once?

Pretty much what it says on the tin. This snippet demonstrates the problem:
function check(e) {
console.log($('input[name="myinput"]').val());
if ($('input[name="myinput"]').val() == "123") {
return true;
} else {
$('input[name="myinput"]')[0].setCustomValidity("Invalid");
return false;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<form onsubmit="return check()">
<input name="myinput">
<input type="submit">
</form>
</div>
When the form loads, enter 1 into the input field and submit the form. Submission fails because the input field's value was not 123, and the value "1" is logged in the console. Now change the value to anything else and resubmit the form; there is no extra line in the console and the "Invalid" form validity remains even if the value entered is 123.
Why is the onsubmit handler only called once?
Because a form in an "invalid" state (because an input inside the form is in "invalid" state) won't submit.
Form validity is created not to be changed on submit events because, as you noticed, you won't get any new submit. You must change the form validity before submitting it. Usually, form validity is checked individually on each input. From here is on your own taste. I would recommend checking the validity of each input on blur:
$('input[name="myinput"]').on("blur", () => {
// Do your checks and setCustomValidity depending on if is valid or not
});
This way, you only will receive a submit event if all inputs are valid. By the way, for this to work, you must set all inputs to an invalid state on startup, to avoid empty submits without touching any input.
Another way could be to disable the submit button if all inputs are empty. For this, you will also need JavaScript and check the change or input events on all inputs.

Check form with onclick() function not working properly

This is my third night working on the same code... can`t get it right after days of google and tutorials and I am so tired of it... I am beeing desperate right now...
On short, I have a form and I use a button type="button" to generate a second button type="submit".
Before the second button appears, I need to check all required inputs if empty and after completion, show the second button.
I created a mixed code which now verify if inputs are empty, and highlights them one by one, not all inputs empty at the same time as I wanted.
I wanted to show highlighted all empty inputs not one by one and if one input is filled it should remove highlight class.
My work so far can be found here: here
Most important of all, I have a calculator which is calculating from inputs values. This is the reason I am using first button type="button".
How to get this to an end? I am so tired of this. Thank you.
LE: Partially fixed it by removing some return false; code from function. It has some errors although. For example, if you complete the last three inputs without completing and the ones on top, will submit anyway.
You could use the required attribute. It won't have any effects as you're not submitting the form, but then you could select all required fields with document.querySelectorAll(":required") or with jQuery $(":required") and loop through all of them validating each one.
You are returning false when a value is empty, so it's stopping the function, that's why they highlight one by one.
You can look this basic validation using JS and get idea what to do
<script type="text/javascript">
function validateMe(){
var name = document.getElementById('name').value;
var phone = document.getElementById('phone').value;
if(name==""){
//do something
alert("name can not be null");
return false;
//this will not submit your form
}
else if(phone==""){
//do something
alert("phone can not be null");
return false;
//this will not submit your form
}
else{
return true;
//This will submit your form.
}
}
</script>
<form action="somewhere.php" method="post" onsubmit="return validateMe();" >
<input type="text" name="name" id="name" />
<input type="text" name="phone" id="phone" />
<input type="submit" value="check and submit" />
</form>
NOTE: This is very basic validation using Javascript. What you want is to click one button and if valid then show submit button. But why you want do that if you want only validation. Why two buttons one to check values and show submit button and another button is submit itself. Why?
I created another short loop function BUT after inputs are filled, newButton button does not show. All Inputs are turning green from empty red. Please see the positioning of the return false;
function validateForm() {
var elements = document.getElementsByClassName("form-calc");
for (var i = 0; i < elements.length; i++) {
if(elements[i].value == "") {
elements[i].style.borderColor = "red";
} else {
elements[i].style.borderColor = "green";
return false; // IF PUT THIS HERE, ONLY ONE INPUT AT A TIME IS HIGHLIGHTED BUT IN THE END THE newButton WILL POP UP.
}
}
return false; // iF I PUT THIS HERE IT STOPS HERE, NO NEWBUTTON NEXT.
var newButton = "<input type='submit' name='submit' value='Trimite-mi oferta pe mail' class='buton-calc'/>";
document.getElementById("a").innerHTML= "<span style='margin-left: 17%;'>Oferta personalizată a fost generată</span>"+newButton;
//SOME CODES HERE
});
What am I missing?

Disabling "save" button until at least one input field has changed

There are around 20 input fields and a save and a register buttons in a page. How can I enable a "save" button only when something changed in at least one field?
You can use Angularjs form validation:
I suppose you created a form with text inputs.
You can conditionally disable your save button (If the form is prisitine, disable the button):
<input type="submit" ng-disabled="myForm.$pristine" />
Working plunker here.
If you don't need to compare values you can just attach an event handler on key event to all text boxes and enable the save button once the event in any of them is triggered.
If you need to more "sophisticated" feature to allow saving only when some data has really changed (you may for example change "aaa" to "aa" - but then realize you want it back to "aaa") then you need to maintain the original data and compare them against any new changes and then determine whether you enable save button or keep it disabled. In such case you can for example add some sort of "original-data" attribute to your input textboxes which will hold the original value when the page is generated/loaded and on every key change event run the comparer.
Assuming your HTML looks like this:
<input>
<input>
<input>
<button class=save disabled>Save</button>
You can do something like this:
var inputs = document.getElementsByTagName("input");
var enableSave = function() {
document.querySelector("button.save").disabled = false;
for (var i = 0; i < inputs.length; i++) {
inputs[i].removeEventListener("input", enableSave);
}
};
for (var i = 0; i < inputs.length; i++) {
inputs[i].addEventListener("input", enableSave);
}
Disabling a button for a form can be done using ng-disabled
<form name="myForm">
Name :
<input type="text" name="Name" required><br>
Age:
<input type="number" name="Age" required><br>
<input type="submit" value="Save" ng-disabled="myForm.$error.required">
here the save button is enabled only when the required fields in the form is satisfied

How can i show a validationMessage (for an input element) programmatically without a Form?

Im not sure if this is possible without using a form.
But I would like the browser to render the validation errors.
Again, I am doing this programmatically without a form.
i.e. No Form tag, and no submitting. Just straight-up scripting.
Updated
I would like to validate input fields, such as:
<input value="123" maxlength="5"/>
<input value="hllo wrld" spellcheck="true"/>
If you wan't to validate that fields on page load without any additional submit/click event this can be possible solution :
$( document ).ready(function() {
$("#fieldDiv input").each(function() {
if(!isNaN(this.value)) {
alert(this.value + " is a valid number");
}
});
});
Idea is to traverse all input fields and perfom validation. You can use custom attributes to know what validation to use.

Ajax form submit after validating input elements

I have a form which collects some information using text boxes. Some text boxes have a strick pattern, e.g. few input boxes take only numbers.
I was able to add validation using pattern attribute of input field. http://www.w3schools.com/tags/att_input_pattern.asp
However, when user submits the form I need to do a ajax post request to a different end point. So, I think I have to make a call to preventDefault() method to prevent default form submit.
But when I call preventDefault(), it also disables validating input fields.
How can I achieve validating fields and make a ajax request, only if the input fields pass the validation.
You can either way use this:
First change the input[type="submit"] to this:
<button onclick="submitThis()">Save</button>
function submitThis() {
var firstInput = $("#idoffirstinput).val(); // basic validation
if(firstInput == "correctinput") {
$.ajax({
// send the ajax form
})
}
}
You can seperately validate each input using the technique provided there, or the one I provided. The jQuery error will be same; I mean the validation.
Use this:
if(firstInput == "correctinput") {
// ajax form
} else {
// show the error popup!
}
The plus point for this one is that you can style the error dialouge popup too. Like
$("#errordiv").css("border", "1px solid #hexcode");
And everything else is same!
HTML and jQuery:
<form id="details">
Phone no: <input type="text" id="phone_no" pattern="[A-Za-z]{3}">
<input type="submit" id="submit">
</form>
var input = $('#phone_no').val();
if(input != '')
{
var YOUR_URL = 'www.example.com';
var formData = $('#details').serialize();// If you want to pass that data to that URL
$.post(YOUR_URL,formData,function(result){
});
}
else
{
return false;
}

Categories