PopUp after input validation and submit Javascript - javascript

I have the following simple form
<form action="#" method="POST" id="minimum" class="barrier">
<section class="col col-5">
<label class="label">Minimum Item</label>
<label class="input">
<i class="icon-append fa fa-minus-square"></i>
<input type="text" name="minimum" autocomplete="off">
</label>
</section>
<button type="submit" id="myBtn" name="create" class="btn btn-danger">Create</button>
<div id="myModal" class="modall">
<!-- Modal content -->
<center>
<div class="modall-content">
<span class="close">×</span>
<p>Please Wait while Processing.</p>
</div>
</center>
</div>
</form>
and the javascript :
// Get the modal
var modal = document.getElementById("myModal");
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
btn.onclick = function() {
var setok = document.getElementById("setok");
if (typeof setok !== "undefined" && element.value == '') {
modal.style.display = "block";
}
}
the validation form does work perfectly and cannot be submitted until user fill it with correct condition, however after i click the submit button, the popup doesn't show up
here is my validation script :
$(function()
{
// Validation
$("#form").validate(
{
// Rules for form validation
rules:
{
minimum:
{
required: true,
digits: true
}
},
messages:
{
minimum:
{
required: 'Please Enter only digits!',
digits: 'Please Enter only digits!'
}
},
errorPlacement: function(error, element)
{
error.insertAfter(element.parent());
}
});
});
the thing that i want to do is if i click the button the popup will show up after the validation

You could move the button click pop-up event to jQuery validate submitHandler method :
$(function() {
// Validation
$("#form").validate({
// Rules for form validation
rules: {
minimum: {
required: true,
digits: true
}
},
messages: {
minimum: {
required: 'Please Enter only digits!',
digits: 'Please Enter only digits!'
}
},
errorPlacement: function(error, element) {
error.insertAfter(element.parent());
},
submitHandler: function() {
var setok = document.getElementById("setok");
if (typeof setok !== "undefined" && element.value == '') {
modal.style.display = "block";
}
}
});
});
This way the pop-up will shows up after the validation is passed.

You can set the buttons type to button. Now the button will not submit the form. Instead you can run some JS to submit the form when you click the button. You can do that in vanilla JS, jQuery or whatever.
document.addEventListener('click', () => {
// Retreive the data from the form..
//NOTE: you can implement your popup instead of the alert
myFakeRequest()
.then( response => alert(response) )
.catch( error => alert( error ) )
});
// this just simulates a request delaythat fails half the time
function myFakeRequest() {
return new Promise( (resolve, reject ) => {
window.setTimeout( () => {
if( Math.random() > 0.5 )
resolve( 'YAY, successfull request' );
else
reject( 'Oh no... The request didn\'t work' );
}, 1000 )
});
}
<button type="submit" id="myBtn" name="create" class="btn btn-danger">Create</button>

Related

How to call form validity event if no input is entered

I have a simple form with bootstrap which I need to validate before submitting. It has auto support for invalid-feedback. It looks like this
let forms = document.querySelectorAll(".needs-validation");
var productNameField = document.getElementById("productName");
productNameField.addEventListener("input", function () {
var val = document.getElementById("productName").value;
console.log("not entering here if I don't enter an input", val);
if (!isValidString(val)) {
productNameField.setCustomValidity("invalid");
} else {
productNameField.setCustomValidity("");
}
});
Array.prototype.slice.call(forms).forEach(function (form) {
form.addEventListener(
"submit",
function (event) {
if (!form.checkValidity()) {
console.log("not valid");
event.preventDefault();
event.stopPropagation();
}
console.log("here validation");
form.classList.add("was-validated");
},
false
);
});
<form
action="/products/addProduct"
enctype="multipart/form-data"
class="needs-validation"
novalidate
method="post"
>
<div class="col-md-12 position-relative">
<label for="productName" class="form-label"
>Product Name</label
>
<input
type="text"
name="productName"
id="productName"
class="form-control"
/>
<div class="invalid-feedback">
Please provide a valid Product Name(at least two
characters, no special characters allowed).
</div>
</div>
<div>
<button type="submit" id="savebutton" name="Submit">
Create
</button>
</div>
</form>
Now when I type an input I immediately see an error if !validString (because of the input eventlistener). But if I just click on the submit button it is not calling the validString function.
What should I do ?
const productNameField = document.getElementById("productName");
const isInputValid = function() {
return productNameField.value.length > 1;
}
const updateValidity = function() {
if (isInputValid()) {
productNameField.classList.remove('invalid')
} else {
productNameField.classList.add('invalid')
}
}
productNameField.addEventListener("input", updateValidity);
const forms = document.querySelectorAll(".needs-validation");
Array.prototype.slice.call(forms).forEach(function (form) {
form.addEventListener(
"submit",
function (event) {
updateValidity();
if (isInputValid()) {
console.log("validation complete");
form.classList.add("was-validated");
} else {
console.log("validation failed");
event.preventDefault();
}
}
);
});

Glitch in my autocomplete to show jquery validation error?

Hope this question is usefull.
In my autocomplete success I make my input hidden value 1 to avoid
jquery validation and append the current customer name to the
particular input field and all are working fine.
My glitch is if supposed user manually delete the value of input field
which have current customer name, I want to show jquery validation
error. But how can I show that??. Because In my autocomplete success I
made the hidden value 1. So its failed to show the error and I cant check that in keyup or keydown function, Beacuse using that input id I already written the autocomplete.
$(document).ready(function() {
$("#apendexistingCustomer").autocomplete({
autoFocus: true,
source: '{{ url("/getexistingcustomer") }}',
minLength: 2,
select: function(event, ui) {
event.preventDefault();
if (ui.item.label == 'This customer is not in our records.') {
$('#apendexistingCustomer').val('');
$('#existcustomers').val('');
$('#create').valid();
swal("This customer is not in our records.", "", "warning");
} else {
$('#apendexistingCustomer').val(ui.item.label);
$('#existcustomers').val(ui.item.key);
$('#create').valid();
getCustomerDet(ui.item.key);
}
},
focus: function(event, ui) {
selectFirst: true;
event.preventDefault();
},
open: function(event, ui) {
$(this).autocomplete("widget")
.appendTo("#results").css({
'position': 'static',
'width': '100%'
});
$('.ui-autocomplete').css('z-index', '9999999');
$('.ui-autocomplete').addClass('srchuser-dropdown');
}
}).data("ui-autocomplete")._renderItem = function(ul, item) {
return $("<li style='height:60px;'><span class='srchuser-downname'>" + item.label + "</span></li>").data("ui-autocomplete-item", item).appendTo(ul);
};
});
this is my function to fetch customer details using autocomplete
protected function getexistingcustomer() {
if (Request::ajax()) {
$data = Request::all();
$searchVal = $data['term'];
if ($searchVal != '') {
$searchResult = customers::searchCustomerAutoComplete(trim($searchVal));
}
$finalArr = array();
if (!empty($searchResult)) {
foreach($searchResult as $vk => $sf) {
$finalArr[$vk]['label'] = $sf['firstname'].
''.$sf['lastname'];
$finalArr[$vk]['key'] = 1;
}
} else {
$finalArr[0]['label'] = 'This customer is not in our records.';
}
print json_encode($finalArr);
exit;
}
}
customer Input field
<div class="row" id="selectcusDiv">
<div class="col-12 col-sm-6 col-md-4">
<div class="form-group">
<label><sub>*</sub>Customers</label>
<div class="select-container">
<input type="text" id="apendexistingCustomer" name="apendexistingCustomer" class="form-control fieldcls">
<input type="hidden" id="existcustomers" name="existcustomers" value="" class="form-control fieldcls">
</div>
</div>
</div>
</div>
Jquery Validation
$('#create').validate({
ignore: [],
rules: {
existcustomers: 'required'
},
messages: {
existcustomers: 'please enter'
}
});
In your javascript add a change listener to the autocomplete element, and check for an empty value. If the value is empty, set the "avoid validation" flag hidden input to 0, then use a required validation rule on that element.
$("#apendexistingCustomer").on("change", function(){
if($(this).val() == ""){
$("#validateFlag").val(0)
}
});

Problems with validate jquery function

I was trying to make a validation in my form with jquery, but it does not work the way it was supposed to and I have no idea why.
I have this function to make the validation:
function newLogin () {
var username = $("#popup-login-email").val();
var password = $("#popup-login-password").val();
if (username == "" || password.length<5){
$(document).ready(function () {
$("#popup-login-form").validate({ // initialize the plugin
rules: {
email: {
required: true,
email: true
},
password: {
required: true,
minlength: 5
}
},
});
});
return false;
}
else{
Parse.User.logIn(username, password, {
success:function(user){
console.log("login successfull");
if(checkEmail()){
console.log(checkEmail());
document.location.href = "Temas.html";
}
},
error: function(user, error){
console.log(error.message);
displayErrorDiv();
}
})
}
}
And i got this form
<form id = "popup-login-form">
<input type="email" name="email" placeholder="Email" id = "popup-login-email" class="popup-input first"/>
<div id="error-message-email" class="error">
</div>
<input type="password" name="password" placeholder = "Password" id="popup-login-password" class="popup-input"/>
<div id="error-message-password" class="error">
</div>
<button class="popup-button" id="popup-cancel">Cancel</button>
<button type="submit" class="popup-button" id="popup-submit">Login</button>
<div class="error-message-login" class="error">
</div>
</form>
And the weird part is that just does not work in my page. Here it works, for example: http://jsfiddle.net/xs5vrrso/
There is no problem with the code which you shared in jsfiddle but the above code you are using $(document).ready({function()}) inside a function which is of no use. Now the problem is that the method newLogin is not called on dom ready and thus this issue occurs.
Better keep the function call inside $(document).ready({function() newLogin() }) . Now you can also use submitHandler in validate to merge the if else conditions.
i make one example to you
jsfiddler example
$(document).ready(function () {
$("#popup-login-form").validate({ // initialize the plugin
rules: {
email: {
required: true,
email: true
},
password: {
required: true,
minlength: 5
}
},
});
//event listening onSubmit
$('form').submit(function(event){
var returnForm = true;
var username = $("#popup-login-email").val();
var password = $("#popup-login-password").val();
//Make your validation here
if (username == "" || password.length<5){
returnForm = false;
}
return returnForm; //Submit if variable is true
});
});
With jQuery when i get the
"TypeError: $(...).validate is not a function"
I change
$(..).validate
for
jQuery(..).validate
You have to include this validate file after jquery file.
<script src="http://cdn.jsdelivr.net/jquery.validation/1.14.0/jquery.validate.js"></script>
Do not wrap the code under the if condition with $(document).ready(). Change the code to :
if (username == "" || password.length < 5){
$("#popup-login-form").validate({ // initialize the plugin
/*remaining code here*/
});
}
Also it is a good habit to trim the spaces around any input that you accept from the users. For e.g in your case please do the following:
var username = $.trim($("#popup-login-email").val());
var password = $.trim($("#popup-login-password").val());
/* $.trim() would remove the whitespace from the beginning and end of a string.*/

Perform validation based on the visibility of radio buttons

I have a Form which has 2 fields to validate, Radio buttons and Textarea.
The rules for validation are
At least 1 radio must be checked
The textarea should not be empty.
Here is the DEMO of my code.
The issue is that the visibility of "Radio" buttons are conditional and they might be hidden in some scenario.
So. currently if the Radio buttons are hidden I'm not able to submit the <form>.
Should I do the Form validation twice as shown below? Or is there a better and shorter way of doing this validation?
if (Radio is : visible){
Here goes the validation for both form fields
} else{
Do the Validation again only for Textarea
}
Following is my code:
HTML
<input class="redButton" id="openDialogButton" type="button" value="Open Dialog">
<div id="sessionReason" title="End Transaction">
<p class="validation-summary-errors marginBottom10">Provide the following information to proceed:</p>
<div class="marginBottom" id="sessionDocumentMessage">
<label class="marginBottom5 marginTop10">Return the document?</label>
<br>
<label>
<input type="radio" name="sessionDocuments" />Return</label>
<br>
<label>
<input type="radio" name="sessionDocuments" />Keep</label>
<br>
</div>
<p class="marginBottom5" id="sessionReasonMessage">Reason for ending the transaction:</p>
<textarea id="sessionReasonBox" class="reasonBox"></textarea>
</div>
JQuery
function showValidationError() {
$('#sessionReason .validation-summary-errors').show();
}
function hideValidationError() {
$('#sessionReason .validation-summary-errors').hide();
}
function addRadioError() {
$("#sessionDocumentMessage label").addClass("redtext");
}
function removeRadioError() {
$("#sessionDocumentMessage label").removeClass("redtext");
}
function addReasonBoxError() {
$("#sessionReasonMessage").addClass("redtext");
}
function removeReasonBoxError() {
$("#sessionReasonMessage").removeClass("redtext");
}
$('#sessionReason .validation-summary-errors').hide();
$("#sessionReason").dialog({
autoOpen: false,
buttons: {
"Submit": function () {
var enteredReason = $('#sessionReasonBox').val();
var radioChecked = $("#sessionReason input:radio[name='sessionDocuments']:checked");
if ((enteredReason.length <= 0) && (radioChecked.length == 0)) {
//Show Error
showValidationError();
addReasonBoxError();
addRadioError();
//Hide Validation Error
} else if ((enteredReason.length > 0) && (radioChecked.length == 0)) {
//Show Validation Error
showValidationError();
addRadioError();
//Hide Validation Error
removeReasonBoxError();
} else if ((enteredReason.length <= 0) && (radioChecked.length > 0)) {
//Show Validation Error
showValidationError();
addReasonBoxError();
//Hide Validation Error
removeRadioError();
} else {
$(this).dialog("close");
//Hide Validation Error
hideValidationError();
removeRadioError();
removeReasonBoxError();
}
},
"Cancel": function () {
$(this).dialog("close");
}
}
});
$("#openDialogButton").click(function () {
$('#sessionReasonBox').val("");
$('#sessionDocumentMessage input:radio').removeAttr('checked');
$("#sessionReason").dialog("open");
//Hide Validation Error
hideValidationError();
removeRadioError();
removeReasonBoxError();
});
Let me know if you need any other information.
Please suggest.
Try something like the following, this should give you an idea.
"Submit": function () {
var enteredReason = $('#sessionReasonBox').val();
var radioVisible = $("#sessionReason input:radio[name='sessionDocuments']:visible");
var radioChecked = $("#sessionReason input:radio[name='sessionDocuments']:checked");
var validationError = false;
if(enteredReason.length <= 0) {
validationError = true; // validation failure
addReasonBoxError(); //add validation error for textarea
}
else
removeReasonBoxError(); //remove validation error for textarea
if(radioVisible.length){
if (radioChecked.length == 0) {
validationError = true; // validation failure
addRadioError(); //add validation error for radio
}
else
removeRadioError(); //remove validation error for radio
}
if(validationError)
showValidationError(); //add validation error
else
hideValidationError() //remove validation error
}
Yes, you can check the css-property.
if (!($('button').css('display') === "hidden"))
The css-function, if given a single argument, just returns the value rather than setting it. Also, you would of course have to refine the selector to select the correct button.
Read more: http://api.jquery.com/css/

How do I add a confirmation message to Happy.js upon submit?

I am using Happy.js and would like to show a message in a span/p element which will appear below the submit button when the user successfully fills out the form. I have the validation working, But can't seem to hook in the showing of the message. I tried my hand at it below, in the unhappy function! Thanks in advance...
<p>
<input type="submit" class="submit myButtons submitButton specificLink button button-block button-rounded button-large" name="submit" value="Submit" placeholder="">
</p>
<div id="results" class="results" style="text-align:center;">
<span>
<p class="success">Your message was sent succssfully!<br> I will be in touch as soon as I can.
</p>
</span>
</div>
var dd= $.noConflict();
dd(document).ready(function () {
dd('.success').hide();
dd('#frmContact').isHappy({
fields: {
// reference the field you're talking about, probably by `id`
// but you could certainly do $('[name=name]') as well.
'#yourName': {
required: true,
message: 'Might we inquire your name'
},
'#email': {
required: true,
message: 'How are we to reach you sans email??',
test: happy.email // this can be *any* function that returns true or false
},
'#comments': {
required: true,
message: 'Please leave a message!',
}
},
unHappy: function () {
var yourName = dd('#yourName').val();
var email = dd('#email').val();
var comments = dd('#comments').val();
if (yourName && email && comments == true){
dd('.success').show();
}
},
});
});
Give this a try
function () {
var yourName = dd('#yourName').val();
var email = dd('#email').val();
var comments = dd('#comments').val();
if (yourName && email && comments == true){
dd('#results').show();
dd('.success').show();
}

Categories