Something's not working this morning and I'm pretty sure it's my brain. I've got a form that tracks changes to a field under certain conditions:
-If the status = Draft, do nothing.
-If the status = Approved, prompt user to ask if they are sure they want to make the change.
-If they click 'OK', it should call the process that records the change.
-If they click 'Cancel' it should do nothing.
-If the status is anything other than draft or Approved, don't prompt but call the process that records the change.
I had the code recording changes in non-draft status, but after I added the ==true to the end of the confirm statement, everything stopped working.
var stat = $('#status').text();
var parms = just a bunch of parameters i'm passing to the url below;
if (stat=='(Draft)'){
//do nothing
}
else if (stat !== 'Approved' && stat!== '(Draft)'){
var url = webDbName + '/(CreateOTChangeRecordOnChange)?OpenAgent' + parms;
$.get(url, function(data) {
$('#tableBodyChanges').html(data);
});
}
}
else if (stat == 'Approved' && confirm('You are changing the hours on a request that has already been approved. This will send a notification to the department director. Proceed?')==true) {
var url = webDbName + '/(CreateOTChangeRecordOnChange)?OpenAgent' + parms;
$.get(url, function(data) {
$('#tableBodyChanges').html(data);
});
} else {
//do nothing });
}
It is working, but you could just ommit the == true because it already is a "if-able boolean"
if(confirm("test?")){
console.log("confirmed1");
}else {
console.log("notconfirmed1");
}
<!-- or the other way arround -->
if(!confirm("test?")){
console.log("notconfirmed2");
}else {
console.log("confirmed2");
}
<!-- it should also work the way you posted as well -->
if("foo" == "foo" && confirm("test?") == true){
console.log("confirmed3");
}else {
console.log("notconfirmed3");
}
Related
hello i have a login validation form which uses a mix of jquery and ajax to do validations... if the values are ok the form should submit, if the values are not ok then the form should not submit... however in my case the form is submitting even when the values are incorrect ( i am using the mousedown function ) please see below my code..
<form method="post" name="loginform" action="models/login.php">
<input type="email" class="homepage" name="user_email2" id="user_email2" placeholder="Email" maxlength="50" />
<div class="errormsg" id="errormsg6"></div>
<input type="password" class="homepage" name="user_password2" id="user_password2" placeholder="Password" maxlength="20" />
<div class="errormsg" id="errormsg7"></div>
<input type="submit" name="login" id="login" value="Submit">
<div class="errormsglast" id="errormsg8"></div>
</form>
jquery and ajax
$(document).ready(function()
{
/* ----------------- Login Validations Global Variables ----------------- */
var user_email2 = "";
var user_emailajax2 = "";
var user_password2 = "";
var user_passwordajax2 = "";
var emailformat = new RegExp(/^[+a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i);
/* ----------------- Define Validate Email */
var validate_email_login = function()
{
var item5 = $("#user_email2").val().toLowerCase();
if (item5.length < 6 || item5.length > 50)
{
$("#errormsg6").html("Email : 6 - 50 Characters");
user_email2 = "";
}
else
{
$("#errormsg6").html("");
user_email2 = item5;
if (!emailformat.test(item5))
{
$("#errormsg6").html("Wrong Email Format");
user_email2 = "";
}
else
{
$("#errormsg6").html("");
user_email2 = item5;
$.ajax(
{
type: 'POST',
url: 'classes/validatelogin.php?f=1',
data: "user_email2=" + item5,
success: function(msg)
{
if (msg == "ok")
{
user_emailajax2 = "";
$("#errormsg6").html("Email Does Not Exist");
}
else if (msg == "exists")
{
user_emailajax2 = item5;
$("#errormsg6").html("");
}
}
});
}
}
}
/* ----------------- Define Validate Password */
var validate_password_login = function()
{
var item5 = $("#user_email2").val().toLowerCase();
var item6 = $("#user_password2").val();
if (item6.length < 8 || item6.length > 20)
{
$("#errormsg7").html("Password : 8-20 Characters");
user_password2 = "";
}
else
{
$("#errormsg7").html("");
user_password2 = item6;
if (user_email2 != "" && user_emailajax2 != "")
{
$.ajax(
{
method: "POST",
url: "classes/validatelogin.php?f=2",
data: "user_email2=" + item5 + "&user_password2=" + item6,
success: function(msg)
{
if (msg == "WrongPw")
{
user_passwordajax2 = "";
$("#errormsg7").html("Wrong Password - See Forgot Password");
}
else if (msg == "CorrectPw")
{
user_passwordajax2 = item6;
$("#errormsg7").html("");
/* window.location.href="manage-properties"; */
}
}
});
}
}
}
/* ----------------- Run Functions */
$("#user_email2").on('focusout', validate_email_login);
$("#user_password2").on('focusout', validate_password_login);
/* ----------------- Stop on Submit */
$( "#login" ).mousedown(function()
{
validate_email_login();
validate_password_login();
if (user_email2 == "" || user_emailajax2 == "" || user_password2 == "" || user_passwordajax2 == "")
{
$("#errormsg8").html("Please Fill All Fields (Correctly)");
console.log("submit false");
return false;
}
else
{
$("#errormsg8").html("");
console.log("submit true");
return true;
}
});
});
Solution Tried - problem is that when user puts the wrong event that is fine, but if user then puts the correct values, the submit returns false on first time, then second time it returns true... it should return true in first go
<input type="button" name="login" id="login" value="Submit">
$( "#login" ).mousedown(function()
{
validate_email_login();
validate_password_login();
if (user_email2 == "" || user_emailajax2 == "" || user_password2 == "" || user_passwordajax2 == "")
{
$("#errormsg8").html("Please Fill All Fields (Correctly)");
console.log("submit false");
return false;
}
else
{
$("#errormsg8").html("");
console.log("submit true");
$('[name=loginform]').submit();
}
});
});
Instead of having a type="submit" button just have a normal button e.g<input type="button" name="login" id="login" value="Submit">. Then when you finished checking the values and happy that it should send then just call:
$('[name=loginform]').submit();
Because what is happening currently is that the form submits when you click on the button, because you are not stopping that event from happening.
If you want to prevent the form from submitting I would suggest either not using that button and initiating the submit yourself like I mentioned above, or alternatively you can use the onsubmit="someFunction()" on the form element way and just return false if it should not submit and return true if it should.
I would say your code suffers from a few issues and some bad practices.
I see you are trying to learn JS so forgive me for not directly solving your issue but to give you some pointers and point you to some best practices.
Logic -
It seems like you are doing a login form. I would say most of this checks should not happen in the client but on the server.
When user signups it might be wise to check user name length on the client as well and prompt the user that he can't use the user name he wants to register with, but during login all the client care is can I login or not.
Security -
You seem to have two serious security issues with your code
You allow to test if an e-mail/user exist or not using 'classes/validatelogin.php?f=1'. in general you should always test the user and password together if they exist and match the user should be able to login, if not the login should fail. you shouldn't notify the user why it fails (if the user name does not exist or if it exist but the password is wrong).
You don't seem to hash passwords in the database. I assume it by limiting the password max length. let the user choose as long password as he wants and hash it using a secure hashing algorithm (I'd suggest bcrypt but google around and find a suitable one). I know you are only learning but this is highly important I think hashing is the first thing you need to learn when handling user logins
Working with the DOM.
You should cache your DOM elements
so instead of calling $('#id') all the time in the main function scope set
var emailInput = $("#user_email2");
function submitForm() {
var email = emailInput.val().toLowerCase();
...
}
You should also probably set the text value of the element and not the html doesn't matter much now but since you are setting text value its good practice and will help you avoid unexpected injections and errors.
Since your using ajax you should not let the form to submit itself even when validation is successful.
Common logic should be packed into functions and reused.
There are many places where your original code can be split into shorter and reusable functions
handle async code better
jQuery supports the Promise API when using ajax requests, I would rather use it. Your original code had a few async calls if you needed to sync between them it would have been painful using plain callbacks (and it is probably what caused you issues in the first place)
Here is a simplified solution using my suggestions -
$(document).ready(function() {
"use strict";
var emailInput = $("#user_email2"),
emailError = $("#errormsg6"),
passwordInput = $("#user_password2"),
passwordError = $("#errormsg7");
function required (value) {
if (value) {
return true;
} else {
return false;
}
//this is just to make the code clear you could use
//`return value ? true : false` or `return !!value`
}
$('form:eq(0)').on('submit', function (e) {
var valid = true,
email = emailInput.val(),
password = passwordInput.val();
e.preventDefault();
if ( !required(email) ) {
emailError.text('Email is required');
valid = false;
}
if ( !required(password) ) {
passwordError.text('Password is required');
valid = false;
}
if ( valid ) {
$.ajax({
method: "POST",
url: "login.php",
data: {
email: email,
password: password
}
}).done(function (data, textStatus, jqXHR) {
//redirect user to main page
}).fail(function (jqXHR, textStatus, errorThrown) {
//show the user the error
})
}
});
});
I have the code below and I would like it to perform multiple field validation and give alert on each field when it is incomplete. Scenario: If I use the code without the validation and associated alerts it works 100%, when I include the validation the code goes through each step and alert and ultimately fails on the last bit to execute and flag a field as 'true' and gives error of 'Invalid or unexpected token'. Any help would be welcome
{
!REQUIRESCRIPT("/soap/ajax/32.0/connection.js")
}
var x;
if ('{!Case.Trigger_Submit_Spark__c}' == true || '{!Case.Spark_Service_Desk_Ref__c}' != "") {
alert('You are unable to submit request, as this request has already been submitted to Spark')
} else {
if ('{!Case.Spark_Service_Request_Type__c}' == "" && '{!Case.Spark_Request_Note__c}' == "") {
alert('You are unable to submit request, as Spark Service Request Type and Request note are blank')
} else {
if ('{!Case.Spark_Service_Request_Type__c}' == "" && '{!Case.Spark_Request_Note__c}' != "") {
alert('You are unable to submit request, as Spark Service Request Type is blank')
} else {
if ('{!Case.Spark_Service_Request_Type__c}' != "" && '{!Case.Spark_Request_Note__c}' == "") {
alert('You are unable to submit request, as the Spark Request Note is blank')
} else {
if ('{!Case.Trigger_Submit_Spark__c}' == false && confirm('Do you want to submit this request?\n\nBy submitting this request the following will occur:\n 1. Case Status changed to Escalated to Tier2\n 2. Escalation Group = Spark\n 3. Email sent to Spark (Remedy)\n 4. Note placed in SalesForce chatter feed\n\nPlease check chatter feed to confirm that request has been sent') == true) {
x = "OK";
var c = new sforce.SObject("Case");
c.id = '{!Case.Id}'
c.Trigger_Submit_Spark__c = true;
result = sforce.connection.update([c]);
if (result[0].success === "true") {
window.location.reload();
} else {
alert("An Error has occured. Error: " + result[0].errors.message);
}
}
}
}
}
}
Question as stated above. I am using older browsers (IE8 and FF8) due to corporate policy. I can't fix this but my research says this isn't the issue...(yeah right;)
I'm using PHP 5.5.12 on Apache 2.4.9 with a MySQL (5.6.17) back end. The site is a CMS that has grown organically over several years.
I have a user admin page that adds, updates, and deletes accounts. However, no matter what I have done the form submits. The worst example is if the admin chooses to delete an account and when asked 'Do you really wish to DELETE...?' and cancels, it is still deleted! I've copied my JavaScript and an excerpt from the PHP/HTML below.
I have tried a few changes to my JavaScript like returning after setting the window.event.returnValue but I've always gotten the same results. I've been reading for several days now and keep coming up blank! I've tried onSubmit instead of onClick but it really doesn't suit the site, besides it didn't work either.
I'm beginning to think the age of the browsers is the issue. I run this with Safari on my home development box fine. Any help would be appreciated.
JavaScript
<script language="JavaScript">
function frmVerify(check, loginid, login) {
if (check == 'add') {
Uname=add_user.login_name.value;
Pass1=add_user.password.value;
Pass2=add_user.password2.value;
if(Uname=='') {
alert('A user name must be assigned to an account.');
window.event.returnValue=false;
}
if(Uname == login) {
alert('You cannot create an account with your own username (' + login + ')');
window.event.returnValue=false;
}
if(Pass1 != Pass2) {
alert('Entered passwords are not the same! Make sure the password and verification fields match.');
window.event.returnValue=false;
}
if(Pass == '') {
alert('Assigning a password is required when creating an account!');
window.even.returnValue=false;
}
} else if(check == 'update') {
Uname=eval('edU_'+loginid+'.login_name.value');
Pass1=eval('edU_'+loginid+'.password.value');
Pass2=eval('edU_'+loginid+'.password2.value');
if(Uname == '') {
alert('A user name must be assigned to an account.');
window.event.returnValue=false;
}
if(Pass1 != Pass2) {
alert('Entered passwords do not match! Make sure the passowrd and verification fields match.');
window.event.returnValue=false;
}
} else if(check == 'del') {
Uname=eval('edU_'+loginid+'.login_name.value');
if(Uname == '') {
request = 'Do you really wish to DELETE this user account?';
} else {
request = 'Do you really wish to DELETE user: ' + Uname + '?';
}
var answer = confirm(request);
if(answer) {
window.event.returnValue=true;
} else {
window.event.returnValu=false;
}
}
}
</script>
In the PHP/HTML I have
echo "<form name=\"delU_$login_id\" id=\"delU_$login_id\" mehtod=\"POST\">";
echo "<input type=\"image\" src=\"./images/delete.png\" value=\"Delete\" onClick=\"return frmVerify('del', '$login_id', '$username');\">";
echo "</form>";
window.event.returnValue (which you don't always spell correctly anyway) is non-standard and shouldn't be used.
You're using 1990s style intrinsic event attributes instead of addEventListener, so just:
return false;
If you were using addEventListener then you would:
event_object.preventDefault();
where event_object is the first argument to your event handler function.
I'm trying to show errors in real time on my registration form, instead of being redirected to another page (register.php).
The index page on my site has a sign-up link which opens a popup registration form (registration.HTML) in a new window. When a user submits this form
it calls on register.PHP as an action. Inside register.php there is a line of code:
js_include('js/register.js');
This javascript checks that certain data is submitted correctly within registration.html. I'd like this check to be performed before submitting the form
and causing it to redirect to register.php. I only need it to direct to register.php if javascript says everything is good.
You can test this yourself here If you click "sign up" in the top-right corner, and type in gibberish as the email and press Enter, it will redirect to register.php and show the error at the bottom (if you scroll down). I'd like this error to be displayed on the registration form.
I tried including the js below within some script tags on my html page, but it still redirects me.
Here is register.js, all feedback is welcome! Thank you
$(document).ready(function() {
$('.formFieldWarning').hide();})
function checkRegisterFormSubmit() {
$('.formFieldWarning').hide();
var errors = 0;
// Check the user name
if($('#username').val() == '') {
$('#username_warning1').show();
errors++;
} else {
if ($('#username').val().length < 2 ) {
$('#username_warning2').show();
errors++;
}
}
// Check the password
if ($('#password').val().length < 2 ) {
$('#password_warning1').show();
errors++;
} else {
if ($('#password').val() == $('#username').val() ) {
$('#password_warning2').show();
errors++;
}
}
// Check the password_verification
if ($('#password_verification').val() != $('#password').val() ) {
$('#password_verification_warning1').show();
errors++;
}
// Check the email address
if($('#email').val() == '') {
$('#email_warning1').show();
errors++;
} else {
if ($('#email').val().search(/^\w+((-|\.|\+)\w+)*\#[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z]{2,63}$/) == -1) {
$('#email_warning2').show();
errors++;
}
}
if (errors != 0) {
$('#form_not_submit_top').show();
$('#form_not_submit_bottom').show();
return false;
} else {
return true;
}
}
Here is an example of how to test a form field using jQuery's blur() function -
$('input[name="foo"]').blur(function() {
var currentValue = $(this).val();
var testValue = 'crumple';
if(currentValue != testValue) {
$(this).next('span').html('FAIL');
} else {
$(this).next('span').html('');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input name="foo" type="text" /><span></span>
I'm making a simple form where a user submits a video, alongside their email address. I'd like to make it so that the person can not submit the form until they have filled in the email and saved the video.
The video part is working, but when I test with an empty email, it still seems to submit. The code is below, and the live version is at http://www.atlas-china.com/record-your-multi-lingual-abilties/
Help much appreciated!
// Global variable to hold player's reference.
var _Nimbb;
// Global variable to hold the guid of the recorded video.
var _Guid = "";
// Event: Nimbb Player has been initialized and is ready.
function Nimbb_initCompleted(idPlayer) {
// Get a reference to the player since it was successfully created.
_Nimbb = document[idPlayer];
}
// Event: the video was saved.
function Nimbb_videoSaved(idPlayer) {
_Guid = _Nimbb.getGuid();
}
jQuery(document).ready(function ($) {
// Get the data from the form. Check that everything is completed.
$('#video_submit').click(function (e) {
var email = document.getElementById("email").value;
var video_title = document.getElementById("video_title").value;
var form = document.myForm;
// Make sure the email is specified.
if (email.value == "") {
alert("Please enter your email to proceed.");
return;
}
// Verify that the video is not currently recording.
if (_Nimbb.getState() == "recording") {
alert("The video is being recorded. Please wait.");
return;
}
// Check that video has been recorded.
if (_Guid == "") {
alert("You did not save the video. Click save.");
return;
}
// Set the guid as hidden parameter.
form.guid.value = _Guid;
var dataString = 'email=' + email + '&guid=' + _Guid + '&video_title=' + video_title;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "<?php echo get_template_directory_uri();?>/send.php",
data: dataString,
success: function () {
$('#contact_form').html("<div id='message'></div>");
$('#message').html("<h2>Contact Form Submitted!</h2>")
.append("<p>We will be in touch soon.</p>")
.hide()
}
});
document.forms["myForm"].submit();
});
});
After viewing your live site...
email = "" // Empty string
Whereas
email.value = undefined
Try changing your code to
if (email === "") {
alert("Please enter your email to proceed.");
return;
}
I assume you are doing .value twice by mistake as you have the following line earlier in your code
var email = document.getElementById("email").value;
When you return from that handler function, the browser will proceed to carry out the normal behavior of the "submit" event, which is to submit the form.
You can change your "abort" return statements to
return false;