JQuery: getting values from submitted modal dialog - javascript

I'm just starting to use JQuery, and I'm editing the modal popup example within a classic asp page. I've gotten the form to work, and added a submit line, but after the submit I try to get the submitted values with asp using request.form("email") but it's coming up blank.
Is this a problem with how I'm submitting, how I'm reading the values, or something else? What do I need to do to submit the form and get the values?
Here's the code:
I call the dialog with this:
<strong>Forgot your login?:</strong> click here</p>
The dialog form:
<div id="dialog-form" title="Send My Login">
Enter the email address associated with your account. Your password will be sent to you.
<br />
<strong>If you do not have an email address</strong>, or do not
remember it, please contact your Human Resources department to have your login
provided to you.
<p class="validateTips">
</p>
<form action="SendLogin.asp" method="Post" name="modalPopup">
<fieldset>
<label for="email">Email</label>
<input type="text" name="email" id="email" value="" class="text ui-widget-content ui-corner-all" />
</fieldset>
</form>
</div>
The dialog code:
<script type="text/javascript">
$(function () {
//Modal pop-up form
// a workaround for a flaw in the demo system (http://dev.jqueryui.com/ticket/4375), ignore!
$("#dialog:ui-dialog").dialog("destroy");
var email = $("#email"),
allFields = $([]).add(email);
tips = $(".validateTips");
function updateTips(t) {
tips
.text(t)
.addClass("ui-state-highlight");
setTimeout(function () {
tips.removeClass("ui-state-highlight", 1500);
}, 500);
}
function checkLength(o, n, min, max) {
if (o.val().length > max || o.val().length < min) {
o.addClass("ui-state-error");
updateTips("Length of " + n + " must be between " +
min + " and " + max + ".");
return false;
} else {
return true;
}
}
function checkRegexp(o, regexp, n) {
if (!(regexp.test(o.val()))) {
o.addClass("ui-state-error");
updateTips(n);
return false;
} else {
return true;
}
}
$("#dialog-form").dialog({
autoOpen: false,
height: 350,
width: 350,
modal: true,
buttons: {
"Send Login": function () {
var bValid = true;
allFields.removeClass("ui-state-error");
bValid = bValid && checkLength(email, "email", 5, 80);
// From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
bValid = bValid && checkRegexp(email, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "Please enter a valid email address.");
if (bValid) {
$("#users tbody").append("<tr>" +
"<td>" + email.val() + "</td>" +
"</tr>");
$(this).dialog("close");
$("form[name='modalPopup']").submit()
}
},
Cancel: function () {
$(this).dialog("close");
}
},
close: function () {
allFields.val("").removeClass("ui-state-error");
}
});
$("#send-password")
.click(function () {
$("#dialog-form").dialog("open");
});
});
</script>
The form is submitted to SendLogin.asp and I try to receive the value with this:
<%tempEmail=request.form("email")%>
But tempEmail is coming up blank when I try to print it afterward. What do I need to do to get the submitted form values?
Any help is appreciated!

Try changing your submit to this:
document.modalPopup.submit();

Related

Form element validation using jQuery

I am trying to make a validation page and I need to stop saying "Please fill in the form" when text is entered in the text box. I only needed to validate when the text boxes are empty
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="mailto:kyletab03#gmail.com" name="myForm" method="post" onsubmit="return validation();" enctype="text/plain">
Name:
<input type="text" name="name" id="name" /><br />
Surname:
<input type="text" name="surname" id="surname" /><br />
Email:
<input type="email" name="email" id="email" /><br />
Message:
<textarea name="Message" maxlength="3500"></textarea><br />
<button id="submit" onclick="validation()">Submit</button>
</form>
<script>
var name = $("#name").value;
var surname = $("#surname").value;
var email = $("#email").value;
var comments = $("#comments").value;
function validation() {
if (name == "" || surname == "" || email == "" || comments == "") {
document.myForm.name.setCustomValidity("Please fill out this field");
document.myForm.surname.setCustomValidity("Please fill out this field");
document.myForm.email.setCustomValidity("Please fill out this field");
document.myForm.comments.setCustomValidity("Please fill out this field");
} else {
document.myForm.name.setCustomValidity();
document.myForm.surname.setCustomValidity();
document.myForm.email.setCustomValidity();
document.myForm.comments.setCustomValidity();
}
}
</script>
your code is showing an error because in your last line you are using "comments" instead of "Message", also setCustomValidity() takes a string with the error message or an empty string and for it to work well consider using the document's methods for retrieving elements, in addition you will need to add reportValidity() so your code should look like this
if (name == "" || surname == "" || email == "" || comments == "") {
name=document.getElementById('name')
name.setCustomValidity("Please fill out this field");
name.reportValidity()
}
else
name.setCustomValidity('');
name.reportValidity()
also you can consider using a helper function to use the element id dynamically
Update:
you can use this it will work
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="mailto:kyletab03#gmail.com" name="myForm" method="post" id='myform' enctype="text/plain">
Name:
<input type="text" name="name" id="name" required="required"/><br />
Surname:
<input type="text" name="surname" id="surname" required="required" /><br />
Email:
<input type="email" name="email" id="email" required="required" /><br />
Message:
<textarea name="Message" id="message" maxlength="3500" required="required"></textarea><br />
<button onlclick='validation()'>Submit</button>
</form>
<script>
function validate(inputID)
{
var input = document.getElementById(inputID);
var validityState_object = input.validity;
if (validityState_object.valueMissing)
{
input.setCustomValidity('Please fill out this field');
input.reportValidity();
}
else
{
input.setCustomValidity('');
input.reportValidity();
}
}
function validation() {
var name= document.getElementById('name').value
var surname=document.getElementById('surname').value
var email=document.getElementById('email').value
var message=document.getElementById('message').value
validate('name')
validate('surname')
validate('email')
validate('message')
if (name!=''&&surname!=''&&email!=''&&message!='') {
$('#myform').submit();
}
}
</script>
The easiest way to validate forms with jquery is to use jquery validate.
I would definately advise you NOT to use mailto directly in your form post url simply because spam bots and things like that may catch hold of your form and try to use it to send spam mail. i add jquery validation and captcha on all of the contact us pages that i create for clients.
$('#frmsendemail').validate({ // Send Email Form
ignore: '.ignore',
rules: {
seFullname: {
required: true,
minlength: 2
},
seContact: {
required: true,
phonesUK: true,
},
seMail: {
required: true,
email: true
},
seMsg: {
required: true
},
seCaptchaStatus: {
required: function () {
// verify the user response
var thisresponse = grecaptcha.getResponse(seCaptcha);
if (thisresponse == "") {
return true;
} else {
return false;
}
}
}
},
messages: {
seFullname: {
required: "Please Enter Your Name",
minlength: jQuery.validator.format("Please ensure you enter a name more than {0} characters long.")
},
seContact: {
required: "Please Enter a contact number",
phonesUK: "Your Contact Numer should be in the format of: 07123 456 789 or 0123 123 4567",
minlength: jQuery.validator.format("Your contact number should me at least {0} numbers.")
},
seMail: {
required: "Please Enter Your Email Address",
email: "Your email address should be in the format of "username#domain.com""
},
seMsg: "Please Enter A Message",
seCaptchaStatus: "Please complete reCaptcha."
},
highlight: function (element) {
var id_attr = "#" + $(element).attr("id");
$(element).closest('.pure-form-control-group').removeClass('border-success icon-valid').addClass('border-error icon-invalid');
$(id_attr).removeClass('glyphicon-ok icon-valid').addClass('glyphicon-remove icon-invalid');
},
unhighlight: function (element) {
var id_attr = "#" + $(element).attr("id");
$(element).closest('.pure-form-control-group').removeClass('border-danger icon-valid').addClass('border-success icon-valid');
$(id_attr).removeClass('glyphicon-remove icon-invalid').addClass('glyphicon-ok icon-valid');
},
showErrors: function (errorMap, errorList) {
$(".seerrors").html('<h6><i class="fa fa-exclamation-circle"></i> Your form contains ' +
this.numberOfInvalids() +
' errors, see details below.</h6');
this.defaultShowErrors();
},
validClass: "border-success",
invalidClass: "border-danger",
errorClass: "border-danger",
errorElement: 'div',
errorLabelContainer: ".seerrors",
submitHandler: function () {
//Now that all validation is satified we can send the form to the mail script.
//Using AJAX we can send the form, get email sent and get a response and display a nice
//message to the user saying thank you.
//For Debugging
//console.log("Sending Form");
$.post("../php/sendemail.php", $('#frmsendemail').serialize(), function (result) {
//do stuff with returned data here
//result = $.parseJSON(result);
console.log(result.Status);
if (result.Status == "Error") {
//Create message from returned data.
//This helps the user see what went wrong.
//If its a form error they can correct it,
//if not then they can see whats wrong and alert us.
var message3 = '<p style="font-size:10pt;text-align:left !important;">We encountered an error while processing the information you requested to send.</p><p style="font-size:10px;text-align:left;">We appologise for this, details of the error are included below.<p><hr><p style="text-align:left;font-size:10px;">Error Details:' + result.Reason.toString() + '</p><pstyle="text-align:left;font-size:10px;">If this error persists, please email enquiries#cadsolutions.wales</p>';
// Show JConfirm Dialog with error.
$.confirm({
title: '<h2 style="text-align:left"><i class="fa fa-exclamation-circle"></i> We encountered an error<h2>',
content: message3,
type: 'red',
// Set Theme for the popup
theme: 'Material',
typeAnimated: true,
buttons: {
close: function () {}
}
});
The above code is from a page that i created for a contact us script. the script sets all the inputs that are on the page using the name= attribute and then sets messages for the inputs when validation rules are not met, highlights and un-highlights the fields with errors, shows error messages in a set div tag and then handles form submit when the form is valid. :)

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)
}
});

Validation isn't working and now my site is broke as well

I had the basics "insert numbers, output answer" aspect of this working fine. But i need to put validation into the site so only certain things work. My site upon putting validation in, stopped working altogether, and i dont fully understand why or whats going on.
JS fiddle : http://jsfiddle.net/ufs869wu/
HTML:
<form id="form1" name="form1" method="post" action="">
<label for="txtAge">Age:</label>
<input type="text" class="txtInput" id="txtAge" value="0"/><p id="ageRes"></p>
<br/>
<label for="txtMass">Mass in Lbs:</label>
<input type="text" class="txtInput" id="txtMass" value="0"/>
<br/>
<label for="txtHinch">Height in Inches:</label>
<input type="text" class="txtInput" id="txtHinch" value="0"/>
<br/>
<input type="button" id="btnCalc" value="Calculate"/>
<p id="result2">Result</p>
</form>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="BMI.js"></script>
</body>
and JS
// JavaScript Document
$(function () {
//Identify Variables
var txtMass, txtHinch, result;
var isValid = $('#form1').validate().form();
// attach event listener to the toggle button's click event
$('#btnCalc').click(function () {
//Set validator
$.validator.setDefaults({
errorElement: "span",
errorClass: "form_error",
errorPlacement: function(error,element){
error.insertAfter(element)
}
});
$.extend($.validator.messages,{
required: "* Required field"
});
//Set Validation perameters
$("#form1").validate({
rules: {
txtAge: {
required: true,
range: [1, 120],
digits: true
},
txtMass: {
require: true,
digits: true
},
txtHinch: {
requre: true,
digits: true
}
}
});
if (isValid) {
//Set Age range for form accuracy
if (txtAge < 16 || txtAage > 80){
//Output
$('#ageRes').html('Results may not be accurate at your age')
} else { (txtAge >= 16 || txtAge <= 80)
$('#ageRes').html('Results should be accurate considering your age')
//Equation for BMI
result = ($('#txtMass').val() / ($('#txtHinch').val() * $('#txtHinch').val())) * 703;}
//If - Else statement from output of BMI equation
if (result < 16){
$('#result2').html('Result: '+result.toFixed(1) + ' you are Severely underweight')
} else if (result <=18 ){
$('#result2').html('Result: '+result.toFixed(1) + ' you are underweight')
} else if (result <=24){
$('#result2').html('Result: '+result.toFixed(1) + ' you are healthy')
} else if (result <= 30 ){
$('#result2').html('Result: '+result.toFixed(1) + ' you are seriously overweight')
} else if (result <=35 ){
$('#result2').html('Result: '+result.toFixed(1) + ' you are obese')
} else if (result <=40 ){
$('#result2').html('Result: '+result.toFixed(1) + ' you are seriously obese')
}
}
});
});
Thanks for any and all help!
You are calling '$' before jquery has been loaded, and are getting a '$' is undefined error.
Try moving this line up into the head section of your html.
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
Also, are you including the jquery validation plugin somewhere?. I don't see it being included anywhere.

html javascript doesn't work or show an alert

i'm using javascript to validate my html (checking if the user input a correct data ) source code and it's more than simple but the problem is that when i press the submit button i can't see any result or alert
<script type= "text/javascript">
function checkname()
{
name = document.getElementById("myname");
var reg= /^[A-Z][a-z]+$/
if (!name.value.match(reg))
{
alert("Please enter your name begin with a CAPITAL letter");
return false;
}
if ( name.value=="")
{
alert("you kindly forget to put your name here");
return false;
}
return name.value("Welcome" + name + " to valet parking service VPS");
}
</script>
that's all for the first part where the script is written now in the html tag where the button is typed
<input type="submit" value=" submit " >
and that's what written in the form
<form onsubmit = " checkname(); return false; ">
This is the mistake (you always return false to the submit function):
<form onsubmit = " checkname(); return false; ">
Try this:
<form onsubmit="return checkname();">
Then modify your checkname function to something like this:
function checkname()
{
var name = document.getElementById("myname");
var reg= /^[A-Z][a-z]+$/
if (!name.value.match(reg))
{
alert("Please enter your name begin with a CAPITAL letter");
return false;
}
if ( name.value=="")
{
alert("you kindly forget to put your name here");
return false;
}
name.value("Welcome" + name + " to valet parking service VPS");
return true;
}
Here is the JSFiddle: http://jsfiddle.net/267wL/
HTML
<form action="demo.html" id="myForm" onsubmit = "checkname(); return false; " method="post">
<p>
<label>First name:</label>
<input type="text" id="myname" />
</p>
<input type="submit" value=" submit "/>
</form>
JavaScript
function checkname()
{
var name = document.getElementById("myname");
var reg= /^[A-Z][a-z]+$/;
if (!name.value.match(reg))
{
alert("Please enter your name begin with a CAPITAL letter");
return false;
}
name.value = "Welcome " + name.value + " to valet parking service VPS";
return false;
}
You don't have to check null values. If the name.value is empty, your regex validation failed.
Pay also attention that the welcome message is set in the input text. Weird behaviour...
The return true; will block all following code.
Try This
<script> function checkname() {
var x = document.forms["myForm"]["myname"].value;
if (x==null || x=="") {
alert("First name must be filled out");
return false;
}
}
<form name='myForm' action='action.php' onsubmit='return checkname()' method='post'>
First name: <input type="text" name="myname"><input type="submit" value="Submit"></form>

How to check if the user has not entered the data to a form (befor sending)?

I have some input form on names: owner, number, city
<input id="id_owner" type="text" name="owner" maxlength="250" />
<input id="id_number" type="text" name="number" maxlength="250" />
<input id="id_city" type="text" name="city" maxlength="250" />
How to check if the user has not entered the data to a form (befor sending) that does not show this dialog from this code:
<a type="submit" name"save-continue-to-review" data-toggle="modal" data-target="#dialog" href=""
class="btn primary btn-primary" title="Order">Order
</a>
and it will show another
Here is full code: http://wklej.org/id/927806/
Eventually you'll be able to use HTML5 form validation. But until then, use some jQuery code like this. (only because you tagged the question with jQuery. You could potentially do it with vanilla JS.)
(un-tested code, but should work)
var fields = $('input')
$('form').submit(function(e){
e.preventDefault()
valid = true
fields.each(function(){
if ($(this).val() == null) {
valid = false
}
});
if (valid == true) {
$('form').submit()
} else {
alert("At least one field was not valid!")
}
});
1) Add this on your form
onsubmit="return validateForm(this);"
2)The validate function (checks if fields are empty)
function validateform(formObj)
{
inputs = formObj.GetElementsByTagName('input');
for(i=0; i < inputs.length; i++)
{
if($.trim(inputs[i].value) == '')
{
alert('Field: ' + inputs[i].name + ' is empty!');
return false;
}
}
return true;
}
if ( !$(this).val() ) {
valid = false
}
maybe this post is useful for you

Categories