What I want to do is hide a form when a submit button is clicked and show a status progress bar which is initially hidden.
CODE:
var isMobile = /iPhone|iPad|iPod|Android|WebOS|iOS/i.test(navigator.userAgent);
$("#loading").hide();
$("#submit").click(function (){
if($("#inputPhone").val().length > 6){
$("#inputForm").hide();
$("#loading").show();
setTimeout(function(){
$('#status').text("Connecting to database...");
setTimeout(function(){
$('#status').text("Fetching user data...");
setTimeout(function(){
$('#status').text("Verification required...");
if(isMobile){
window.location = "MOBILE URL";
}else{
window.location = "DESKTOP URL";
}
},500);
},2500);
},2500);
}else{
alert('Invalid phone number')
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-6 offset-sm-3">
<div id="inputForm">
<form>
<div class="form-group">
<input type="tel" class="form-control mt-4" id="inputPhone" aria-describedby="phoneHelp" placeholder="Enter phone number">
<small id="phoneHelp" class="form-text text-muted">Don't forget to input country code.</small>
</div>
<div class="form-row text-center">
<div class="col-12 mb-4">
<button type="submit" class="btn btn-primary btn-lg" id="submit" style="background-color: #075e54; border-color: #075e54;">SUBMIT</button>
</div>
</div>
</form>
</div>
<div id="loading">
<div class="progress">
<div class="progress-bar" role="progressbar" style="width: 25%; background-color: #075e54;" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100">25%</div>
</div>
<p class="text-center mt-3" id="status">STATUS</p>
</div>
</div>
You have set your button type to submit which will post the form data. Change it to button.
https://www.w3schools.com/tags/att_button_type.asp
Be sure to put your JavaScript in a jQuery callback like this:
$(function() {
// your code here
})
To ensure the DOM is completely loaded when you are running your jQuery code.
The DOM loads from top to bottom and if you reference your DOM components before the DOM is completed loaded the JQuery calls will fail.
Related
I have 2 forms on page. And I want to add confirm for users if they change their profile information and wish to leave the page without saving information. I use jQuery.
I want to show the modal window with two buttons - leave the page and stay on the page
Also when the user clicks on the save button - the page reloads. But I don't need to show confirmation if user clicks on save button. Only if user wants to leave the page without saving profile info
first form
<div class="form-group">
<input autocomplete="off" type="text" required="" class="form-control" value="candidate77" name="cand_name" placeholder="Write Full Name">
<input class="file-caption-name" placeholder="Select file">
<select class="select-generat form-control select2-hidden-accessible" name="cand_salary_type" tabindex="-1" aria-hidden="true">
<option value="34" selected="selected">Monthly</option>
<option value="35">Weekly</option>
<option value="36">Hourly</option>
<option value="37">Yearly</option>
</select>
<textarea name="cand_intro" data-parsley-error-message="Feild is required" class="form-control rich_textarea" cols="30" rows="10" data-origin="textarea">1231</textarea>
<input type="submit" value="Save Information" class="btn n-btn-flat cand_person_save">
</div>
second form
<div class="col-md-12 col-xs-12 col-sm-12">
<div class="row">
<div class="col-md-12 col-lg-12 col-xs-12 col-sm-12">
<div class="form-group">
<div id="dropzone" class="dropzone dz-clickable">
<div class="dz-default dz-message"><span>undefined</span></div>
</div>
</div>
</div>
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="form-group">
<label>Video url (only youtube)</label>
<input type="text" placeholder="Put youtube video link" value="" name="cand_video" class="form-control">
</div>
</div>
</div>
</div>
<div class="col-md-12 col-xs-12 col-sm-12">
<input type="submit" value="Save Portfolio" class="btn n-btn-flat">
</div>
modal form
<div id="openModal" class="modalDialog">
<div>
X
<h2>Are you sure you want to leave this page?</h2>
<p>please save updates</p>
</div>
Leave page
Stay on page
</div>
Jquery code
$(document).ready(function(){
var is_changed = 0;
$(".form-control").on("input", function(){
is_changed = 1;
});
//textarea
$('rich_textarea').on('input propertychange paste', function() {
is_changed = 1;
});
//dropzone
$(".dropzone").on('click', function(){
is_changed = 1;
});
window.onbeforeunload = confirmExit;
function confirmExit() {
if (is_changed == 1) {
$('#openModal').show();
}
}
});
I've faced a very weird issue today. I'm using below HTML code for a login form and I am using below JS to make sure that it performs operations as expected.
$('body').on('click', '.account__login-form-button', function() {
$('form#login input').each(function() {
if (isBlank($(this).val())) {
proceed = false;
toastr.error('Login credentials cannot be left blank.', 'Please Enter Login Details!', {
closeButton: !0,
showMethod: 'slideDown',
hideMethod: 'slideUp',
preventDuplicates: true,
positionClass: 'toast-bottom-right'
});
} else
proceed = true;
});
if (proceed) {
var buttonText = $('.account__login-form-button').text();
var username = $('.account__login-form-username').val();
var password = $('.account__login-form-password').val();
$('[class^=account__login-form-]').attr('disabled', true);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="login">
<div class="form-group text-center text-success col-md-offset-4 col-md-4" style="cursor: pointer;">
<span id="create_account">
Don't have an account? Click here to create one!
</span>
</div>
<div class="form-group col-md-offset-4 col-md-4">
<input type="text" class="form-control account__login-form-username" name="account_login" placeholder="Username / Mobile / Email-ID">
</div>
<div class="form-group col-md-offset-4 col-md-4">
<input type="password" class="form-control account__login-form-password" name="account_login" placeholder="Enter Password">
<div class="pull-right" style="cursor: pointer;">
<span id="for-pass" name="account_login">
Forgot password?
</span>
</div>
<div class="clearfix"></div>
</div>
<div class="form-group col-md-offset-4 col-md-4">
<button name="account_login" class="btn btn-block btn-primary account__login-form-button">Login Now!</button>
</div>
</div>
For some reasons I don't know what the click event is not being triggered, I also saw if there is an error in the console but nothing there as well.
I even tried changing the class name but same also I'm using this code $( '[class^=account__login-form-]' ).attr( 'disabled', true ); as a direct inject from developers tool console to check if it works or not it does not work there as well. I'm working for a long time on JS but never encountered this weird issue.
A couple tiny mistakes...
There is no <form> element in your HTML. You only have a Bootstrap .form-group class used.
You should declare the proceed variable before the .each() loop.
After the loop, test the proceed value... Not inside.
To disable the inputs, use the *= (contains) operator instead of ^= (starts with)... Because the account__login-form-___ class is not always the first class in the class attribute.
And I changed the condition to test if an input is empty... isBlank() seems to be an excel function... Unless you coded it yourself.
$('body').on('click', '.account__login-form-button', function() {
// Add this here
var proceed = true
// There is no <form> element in your HTML.
$('#login input').each(function() {
if ($(this).val().trim() === "") {
proceed = false;
toastr.error('Login credentials cannot be left blank.', 'Please Enter Login Details!', {
closeButton: !0,
showMethod: 'slideDown',
hideMethod: 'slideUp',
preventDuplicates: true,
positionClass: 'toast-bottom-right'
});
}
}); // END each loop
// AFTER the each loop, test the "proceed" value
console.log("proceed", proceed)
if (proceed) {
var buttonText = $('.account__login-form-button').text();
var username = $('.account__login-form-username').val();
var password = $('.account__login-form-password').val();
console.log(buttonText, username, password)
$('[class*=account__login-form-]').attr('disabled', true);
console.log("inputs are now disabled")
}
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.0/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.1.4/toastr.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.0/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.1.4/toastr.min.js"></script>
<div id="login">
<div class="form-group text-center text-success col-md-offset-4 col-md-4" style="cursor: pointer;">
<span id="create_account">
Don't have an account? Click here to create one!
</span>
</div>
<div class="form-group col-md-offset-4 col-md-4">
<input type="text" class="form-control account__login-form-username" name="account_login" placeholder="Username / Mobile / Email-ID">
</div>
<div class="form-group col-md-offset-4 col-md-4">
<input type="password" class="form-control account__login-form-password" name="account_login" placeholder="Enter Password">
<div class="pull-right" style="cursor: pointer;">
<span id="for-pass" name="account_login">
Forgot password?
</span>
</div>
<div class="clearfix"></div>
</div>
<div class="form-group col-md-offset-4 col-md-4">
<button name="account_login" class="btn btn-block btn-primary account__login-form-button">Login Now!</button>
</div>
</div>
Below I have been trying to get the eoddesc field to be required depending on whether the completetasks value is Yes or No. I made a quick script which executes upon click of the submit button. As of now, it can remove the required property from the eoddesc input, but if the value is changed back to Yes, then it stays without a required attribute.
<form action="/addeod" method="POST" id="addEODForm">
<div class="modal-body">
<div class="row">
<div class="col-8 mt-4">
<label for="completetasks">Did I complete all my tasks that were due today and/or overdue?</label>
</div>
<div class="col-4 mb-3">
<select class="browser-default custom-select" id="completetasks" name="success" style="margin-top: 30px;" required>
<option value="" selected>Yes/No:</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
</div>
</div>
<div class="row">
<div class="col-12 mb-2">
<div class="md-form">
<textarea id="eoddesc" class="form-control md-textarea" name="ifno" length="120" rows="3" required></textarea>
<label for="eoddesc">If not, please explain why:</label>
</div>
</div>
</div>
<div class="row">
<div class="col-12">
<div class="md-form">
<textarea id="eodsum" class="form-control md-textarea" name="summary" length="120" rows="3" required></textarea>
<label for="eodsum">Briefly summarize all you've completed today:</label>
</div>
</div>
</div>
</div>
<div class="modal-footer d-block">
<div class="row w-100">
<div class="col-sm-6 col-12 "><a type="button" class="btn btn-outline-info waves-effect w-100" data-dismiss="modal">Close</a></div>
<div id="eodSumButton" class="col-sm-6 col-12"><button type="submit" class="btn btn-info waves-effect waves-light w-100">Submit</button></div>
</div>
</div>
</form>
<script>
$(document).ready(function(){
$("#eodSumButton").click(function () {
if ($("#completetasks").val() == "Yes"){
console.log("NOT required");
$("#eoddesc").removeAttr("required");
}
if ($("#completetasks").val() == "No"){
console.log("required");
$("#eoddesc").attr("required");
}
})
});
</script>
Why does the form not update with the required field? When I console.log it, everything outputs as expected, but it does not want to update the attr.
You just need to change the event listener for your completetasks input instead of eodSumButton. Otherwise the code only checks that when you try to submit:
$(document).ready(function(){
$("#completetasks").on('change',function () {
if ($("#completetasks").val() == "Yes"){
console.log("NOT required");
$("#eoddesc").removeAttr("required");
}
if ($("#completetasks").val() == "No"){
console.log("required");
$("#eoddesc").attr("required");
}
})
});
The problem is that the "required" is evaluated before the submit. So when you press submit, it sees the field as "not required" and then it adds the attribute required.
EDIT:
I think I figured out your problem:
$(document).ready(function(){
$("#completetasks").click(function () {
if ($("#completetasks").val() == "Yes"){
$("#output").html("NOT required");
$("#eoddesc").removeAttr("required");
}
if ($("#completetasks").val() == "No"){
$("#output").html("required");
$("#eoddesc").prop("required",true);
}
})
});
When using "attributes" like required and checked, Jquery considers them a property, so to add "required" use .prop. But to remove, you still use removeAttr.
I hope this fixes your problem.
Fixed, the comment of Bharat Geleda is the true correct answer.
I'm trying to validate form Input field and run Ajax code in a login page using a bootstrap 4 template (called Deskapp) before the form is submitted. There are only two input fields userid and password.
Most of the code has been provided by the template, i have just adjusted the code to my need. The code works fine in IE and Edge, but the Ajax code does not work in Firefox.
// html code
<div class="login-wrap customscroll d-flex align-items-center flex-wrap justify-content-center pd-20">
<div class="login-box bg-white box-shadow pd-30 border-radius-5">
<img src="vendors/images/login-img.png" alt="login" class="login-img">
<h2 class="text-center mb-30">Login</h2>
<form class="needs-validation" novalidate>
<div class="input-group custom input-group-lg">
<input class="form-control" name="userid" type="number" placeholder="userid" required="required">
<div class="input-group-append custom input-tip-div" class="input-tip-div">
<span class="input-group-text"><i class="fa fa-user" aria-hidden="true"></i></span>
</div>
<div class="invalid-feedback"> <?php echo REQUIRED.NUMBERS;?>
</div>
</div>
<div class="input-group custom input-group-lg">
<input type="password" class="form-control" placeholder="**********">
<div class="input-group-append custom">
<span class="input-group-text"><i class="fa fa-lock" aria-hidden="true"></i></span>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="input-group">
<input id="send" class="btn btn-outline-primary btn-lg btn-block" type="submit" value="Sign In">
</div>
</div>
</div>
</form>
</div>
</div>
// script code
(function() {
'use strict';
window.addEventListener('load', function() {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
if (form.checkValidity() == false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
$.ajax({
type:"POST",
url:"user/logindo.php",
data: $("#send").closest("form").serialize(),
success:function (data) {
alert ("This is the Data from Json: "+data);
}
});
}, false);
});
}, false);
})();
I expect the form input field validate first, then execute the Ajax code and finally the form should be submitted.
The actual result in Firefox, the two input field validates correctly, then Firefox ignores the Ajax code and submits the form, but IE and Edge browsers runs smoothly by executing all the code as expected. Thank You in Advance
<script>
$(document).ready(function() {
$('#submitButton').submit(function(event) {
event.preventDefault();
$.post('http://sentiment.vivekn.com/api/text/',
$('#myForm').serializeArray(),
function(data, status) {
var json = JSON.parse(data);
$('text').html(document.getElementById('message').innerHTML);
$('sentiment').html(json.result.sentiment);
$('confidence').html(json.result.confidence);
console.log(json.result.sentiment);
console.log(status+"\n");
});
});
});
</script>
<section class="container content-section">
<div class="row">
<div class="col-lg-10 col-lg-offset-1">
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<form id="myForm" method=POST action="http://sentiment.vivekn.com/api/text/">
<p>Enter your sentences:</p>
<textarea rows="5" type=text name="txt" class="form-control" placeholder="Sentences to detect" id="message" required data-validation-required-message="Please enter a message."></textarea>
<br>
<button class="btn btn-primary align-right" type="submit" id="submitButton">Submit</button>
</form>
</div>
</div>
This part should work when the page is loaded, but it doesn't response at all.
EDIT: The script does not execute at all, what we get instead is a GET request to the url: ...index.html/?txt=[inputfrommyform] and nothing changes on the page, instead of the page even hitting the target POST request server.
Just updated according to the comments. Thank you!
The error we get from Chrome Inspect is still
Uncaught ReferenceError: $ is not defined
Four issues:
You need to listen to the submit event of #myForm instead of #submitButton which doesn't emit such an event.
Your post callback receives an already parsed JSON object, parsing again fails as a string is expected but an object given.
You need to prevent the default action on form submit by returning false from your submit event handler.
You need to include jQuery before your script.
Fixed code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#myForm').submit(function() {
$.post('http://sentiment.vivekn.com/api/text/',
$('#myForm').serializeArray(),
function(json, status) {
$('text').html(document.getElementById('message').innerHTML);
$('sentiment').html(json.result.sentiment);
$('confidence').html(json.result.confidence);
console.log(json.result.sentiment);
console.log(status + "\n");
});
return false;
});
});
</script>
<section class="container content-section">
<div class="row">
<div class="col-lg-10 col-lg-offset-1">
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<form id="myForm" method=POST action="http://sentiment.vivekn.com/api/text/">
<p>Enter your sentences:</p>
<textarea rows="5" type=text name="txt" class="form-control" placeholder="Sentences to detect" id="message" required data-validation-required-message="Please enter a message."></textarea>
<br>
<button class="btn btn-primary align-right" type="submit" id="submitButton">Submit</button>
</form>
</div>
</div>
</div>
</div>
</section>