JavaScript/Jquery best practice - javascript

I've made a few functions to check form input for an ajax request. I am still getting use to JavaScript and some of these ajax requests. I am looking for any suggestions to better work with JavaScript functions, and passing variables through a function level scoping. Thank You in Advance!
Code Works as of now!
Edited!
//Form Handler
$("#form-submit").submit(function(e) {
e.preventDefault();
$.ajax({
beforeSend: function(){
return (checkAll());
return (passwordCheck());
},
complete: function(){
},
type: "POST",
url: '',
data: $("#form-submit").serialize(),
success: function(data)
{
// Set Session Php Etc
alert('php ran');
return true;
}
});
});
//Pushing all Input Values to an Array
function checkAll() {
var arr = [];
$('#form-submit :input').each(function() {
arr.push($(this).val());
});
return (checkArray(arr));
}
//Checks Array for empty strings
function checkArray(arr){
for(var i=0; i < arr.length; i++) {
console.log(arr[i]);
if (arr[i].trim() == '') {
alert('Please Enter All Fields');
return false;
} else {
return true;
}
}
}
//Matches Password
function passwordCheck() {
var pass1 = $('#password').val();
var pass2 = $('#password-check').val();
if(pass1 != pass2) {
$('#password').addClass('highlight');
$('#password-check').addClass('highlight');
alert("Passwords don't match");
return false;
} else {
$('#password').removeClass('highlight');
$('#password-check').removeClass('highlight');
return true;
}
}

Related

Validate the input I'm focus on, no matter what is the status of the others?

I'm having this issue I need to solve... What I want to do is to validate exactly the input user is filling in the moment, no matter if the first one or any other input are empty, and the other is not send the ajax post request if every single input has been validated.
This is the code i have so far:
function sendInfo() {
//variables
var name = $("input#name").val();
var surname = $("input#surname").val();
//inputs validation
if (name == "") {
$("input#name").focus();
$("input#name").parent().find('span').addClass('err').text('you have to fill the name');
return false;
}
if (surname == "") {
$("input#surname").focus();
$("input#surname").parent().find('span').addClass('err').text("you have to fill the surname");
return false;
}
//Manage server side
$.ajax({
type: 'POST',
url: '/path',
data: {name, surname},
success: function (result) {
//all ok, do something
},
error: function (err) {
//something wrong, do other stuff
}
});
}
Try this one.
function sendInfo() {
//variables
var name = $("input#name").val();
var surname = $("input#surname").val();
var error = false;
//inputs validation
if (name == "") {
$("input#name").focus();
$("input#name").parent().find('span').addClass('err').text('you have to fill the name');
error = true;
}
if (surname == "") {
$("input#surname").focus();
$("input#surname").parent().find('span').addClass('err').text("you have to fill the surname");
error = true;
}
if (error) return false;
//Manage server side
$.ajax({
type: 'POST',
url: '/path',
data: {name, surname},
success: function (result) {
//all ok, do something
},
error: function (err) {
//something wrong, do other stuff
}
});
}
You can do this by adding a bool variable isValid. Your code should be like this
function sendInfo() {
//variables
var isValid = true;
var name = $("input#name").val();
var surname = $("input#surname").val();
//inputs validation
if (name == "") {
$("input#name").focus();
$("input#name").parent().find('span').addClass('err').text('you have to fill the name');
isValid = false;
}
if (surname == "") {
$("input#surname").focus();
$("input#surname").parent().find('span').addClass('err').text("you have to fill the surname");
isValid = false;
}
//Manage server side
if(isValid){
$.ajax({
type: 'POST',
url: '/path',
data: {name, surname},
success: function (result) {
//all ok, do something
},
error: function (err) {
//something wrong, do other stuff
}
});
}
}
Try to validate the inputs onfocus() AND before the post.
var checkInput = function(input) {
if (input.val() == '') {
input.parent().find('span').addClass('err').text('you have to fill the name');
return false;
}
return true;
}
function sendInfo() {
var validForm = false;
$('input').each(function(){
validForm = checkInput($(this));
});
if (validForm) {
alert('ok - do the post');
} else {
alert('fill the fields');
}
}
$( document ).ready(function() {
$('input').on('focus',function() {
checkInput($(this));
});
});
Add a certain class to every field you want validated. Then bind an event on the elements with that class that will validate the fields upon change. If it's validated correctly store this info on the element.
For example you'd have your fields like this
<input type='text' id='some-text-1' class='validated-field'>
<input type='text' id='some-text-2' class='validated-field'>
<input type='text' id='some-text-3' class='validated-field'>
Then a script which binds the events
$('.validated-field').on('input', function(){
validate($(this));
});
Note: This will "fire" basically after each keypress, not only after you finish editing.
Note2: Depending on how you create the elements, if you want to call this after document.ready then you'll have to bind this to an element which is indeed ready at the time.
Your validate function should perform the necessary validations and then mark the element with in a certain way, for example
function validate($element){
var value = $element.val();
// var isValid = your validation here
$element.data("valid", isValid);
}
This will produce elements for example like these
<input type='text' id='some-text-1' class='validated-field' data-valid=true>
<input type='text' id='some-text-2' class='validated-field' data-valid=false>
<input type='text' id='some-text-3' class='validated-field'>
The first one validated correctly, the second one is incorrect and the third isn't validated yet, because user hasn't filled it out yet.
With this you can check if every one of these elements is validated
validateElements(className){
var elements = $('.' + className);
for(var i=0; i<elements.length; i++){
if(!$(elements[i]).data("valid") === true){
return false; //at least one isn't validated OK
}
}
return true; //all good
}
I hope I understood your question correctly. If you have any other questions, feel free to comment.

return when duplicate html table

I have a function that can remove the duplicate in my html table.
var seen = {};
$('#tblSerial tr').each(function() {
var txt = $(this).text();
txt = txt.trim();
if (seen[txt]) {
isExist = true;
alertify.error("This serial is already on contract.");
$(this).remove();
return; //this should return
} else
seen[txt] = true;
});
But the problem now is that, below that code there's an AJAX call which always call even I return in the duplicate error.
$.ajax({
type: "GET",
url: siteURL + '#Url.Action("valcontract", "contract")',
data: data_model,
success: function (response) {
if (response.success) {
} else {
$('#serial').val("");
alertify
.error(response.responseText);
return;
}
},
error: function (response) {
alertify
.error(response.responseText);
return;
}
});
I want to block the AJAX call if there's a duplicate in my serial table.

Form Validation with Jquery and AJAX

I am using AJAX with JQUERY to call a PHP script to validate a user email. But, for some reason, the form submits even when it shouldn't. What am I doing wrong? I know the error is for sure not in my PHP.
My Code:
$("#signup").submit(function() {
var error= false;
var dataString = $(this).serialize();
var email= $("#email").val().trim();
if (email != 0) {
// Run AJAX email validation and check to see if the email is already taken
$.ajax({
type: "POST",
url: "checkemail.php",
data: dataString,
async: false,
success: function(data) {
var error= false;
if (data == 'invalid') {
var invalid= 1;
}
else if (data == 'taken') {
var taken= 1;
}
if (invalid == 1) {
alert('invalid email');
error = true;
}
if (taken == 1) {
alert('email taken');
error = true;
}
if (error == true) {
return false;
}
}
});
}
});
Try updating these:
$("#signup").submit(function(e) { //<----pass the event here as "e"
e.preventDefault(); //<----stops the form submission
var error= false;
var dataString = $(this).serialize();
var email= $.trim($("#email").val()); //<----use trim this way
If you absolutely have to use AJAX for form submission, this might be a better way to do it:
$('form').submit({
$.ajax({
type:'post',
url: 'someurl.php',
data: dataString,
context: this, // this here refers to the form object
success:function(data)
{
// perform your operations here
if(something_is_wrong)
{
// show message to user
}
else
{
this.submit(); // put this code in the block where all is ok
}
}
});
return false; // makes sure the form doesn't submit
});

javascript mutually exclusive CheckBox issue

I have a radio button that displays a list of records in a telerik grid. When the radio button is checked, it displays complete and incomplete records. However, the user wants a way of displaying only complete or incomplete records. I added two mutually exclusive checkboxes. The user can either check the complete or incomplete checkbox to display the data. It works fine on my local, but it does not work well on the server. The first time, the user has to click the checkbox two or three times before it can keeps the state. In addition, if complete is checked and the user checked incomplete next, the checkmark will go back to complete. The user has to do it a second times. What I am doing wrong here?
Here is the html for the checkbox
#Html.CheckBox("complete", SessionWrapper.currentEncounter.complete, new { id = "chkComplete", onclick = "chkInCompleteOption(1);this.form.submit();" }) <strong>Complete</strong>
#Html.CheckBox("Incomplete", SessionWrapper.currentEncounter.incomple, new { id = "chkInComplete", onclick = "chkInCompleteOption(2);this.form.submit();" }) <strong>Incomplete</strong>
//Here is the javascript
var completeCheck = '#SessionWrapper.currentEncounter.complete';
var inCompleteCheck = '#SessionWrapper.currentEncounter.incomplete';
function chkInCompleteOption(e) {
if (e == 1) {
var cc = $('#chkComplete').is(':checked');
var data = { "complete": cc, "inComplete": false };
var url = '#Url.Action("CompletedOption", "Orders")';
$.ajax({
url: url,
type: 'post',
dataType: 'text',
data: data,
success: function (data) {
testComplete();
return true;
},
error: function (error) {
alert("An error has occured.");
return false;
}
});
}
else if (e == 2) {
var inc = $('#chkInComplete').is(':checked')
var data = { "complete": false, "inComplete": inc };
var url = '#Url.Action("CompletedOption", "Orders")';
$.ajax({
url: url,
type: 'post',
dataType: 'text',
data: data,
success: function (data) {
testInComplete();
return true;
// $('#chkComplete').removeAttr("checked", "checked");
// $('#chkInComplete').attr("checked", "checked");
},
error: function (error) {
alert("An error has occured.");
return false;
}
});
}
}
function testInComplete() {
if (inCompleteCheck == true) {
inCompleteCheck = $('#chkInComplete').attr("checked", "checked");
document.getElementById('chkInComplete').checked = true;
} else {
$('#chkInComplete').removeAttr("checked");
}
}
function testComplete() {
if (inCompleteCheck == true) {
completed = $('#chkComplete').attr("checked", "checked");
document.getElementById('chkComplete').checked == true;
} else {
$('#chkComplete').removeAttr("checked");
}
}
//Setting the mutually exclusive value on the server side
public bool CompletedOption(bool complete, bool inComplete)
if (inComplete == true && complete == true)
{
return false;
}
if (complete == true)
{
SessionWrapper.currentEncounter.complete = true;
}
else if (SessionWrapper.currentEncounter.complete == true && (complete == null || inComplete == null))
{
SessionWrapper.currentEncounter.complete = true;
}
else
{
SessionWrapper.currentEncounter.complete = false;
}
if (inComplete == true)
{
SessionWrapper.currentEncounter.incomplete = true;
}
else if (SessionWrapper.currentEncounter.incomplete == true && (complete == null || inComplete == null))
{
SessionWrapper.currentEncounter.incomplete = true;
}
else
{
SessionWrapper.currentEncounter.incomplete = false;
}
return true;
}
I found the issue. The server side was being updated properly; however, the ajax was returning an error message every time it executed. The method on the server side was returning a Boolean when a string was expected. I've also set async and cache to false. I ran the application again, and it works.
//Change Method Signature from boolean to string
public string CompletedOption(bool complete, bool inComplete)
{
return "true";
}
ajax post
$.ajax({
url: url,
type: 'post',
dataType: 'text',
async: false, //Added
cache: false, //Added
data: data,
success: function (data) {
return data;
},
error: function (error) {
alert("An error has occured.");
return false;
}
});

Is there a way to prevent submitting a form with this javascript/jquery?

I have searched the net, i´ve tried implementing "preventdefaults" and "return false" statements all over the place, but I can´t seem to find a way to prevent this form submitting and reloading the page. It only reloads when the form has been validated. I´m kind of a beginner, but I really tried hard achieving the script to validate a form (which has "post"-method and "#" as action), and make an ajax-call. It´s a school assignment and would be graceful towards any pointers you guys could give.
$(document).ready(function()
{
$("#submit").click(function()
{
var gbname = $("#gbname")[0];
var gbmessage = $("#gbmessage")[0];
formFields = [gbname, gbmessage]
var warning = false;
for (i=0; i<formFields.length; i++)
{
formFields[i].style.backgroundColor = "white";
if (formFields[i].value == "")
{
formFields[i].style.backgroundColor = "red"
$(formFields[i]).bind("keyup", resetBgColor);
$(formFields[i]).bind("change", resetBgColor);
warning = true;
}
}
if (warning == true)
{
alert("Vänligen fyll i fälten korrekt!");
return false;
}
else
{
$.post('ajax.php', {gbname: gbname, gbmessage: gbmessage},
function(data)
{
$("#successmessage").html(data);
$("#successmessage").hide();
$("#successmessage").fadeIn(1500); //Fade in error/success-meddelande
var comment = $("<div class='film2'><p class='names'><b>Namn:</b>" +gbname+ "</p> <p class='messages'><b>Meddelande:</b>" +gbmessage+ "</p></div>");
$("#kommentarer").prepend(comment);
clearForm();
});
return false;
}
return false;
});
});
Your references to the input elements as objects and the data returned from your AJAX call were a bit muddled.
Also incorporated the suggestion of binding to the form's submit event. DEMO
$(document).ready(function () {
function clearForm(){
$('input.reset').each(function(){
$(this).val('');
});
}
$("form").on('submit', function () {
alert('submitted!');
var gbname = $("#gbname");
var gbmessage = $("#gbmessage");
formFields = [gbname[0], gbmessage[0]]
var warning = false;
for (i = 0; i < formFields.length; i++) {
formFields[i].style.backgroundColor = "white";
if (formFields[i].value == "") {
formFields[i].style.backgroundColor = "red"
$(formFields[i]).bind("keyup", resetBgColor);
$(formFields[i]).bind("change", resetBgColor);
warning = true;
}
}
if (warning == true) {
alert("Vänligen fyll i fälten korrekt!");
return false;
} else {
var J = JSON.stringify({
"gbname": gbname.val(),
"gbmessage": gbmessage.val()
});
console.log(J);
$.ajax({
type: "POST",
url: '/echo/json/',
datatype: 'json',
data: {
json: J,
delay: 3
},
success: function (data) {
$("#successmessage").html(data);
$("#successmessage").hide();
$("#successmessage").fadeIn(1500); //Fade in error/success-meddelande
var comment = $("<div class='film2'><p class='names'><b>Namn:</b>" + data.gbname + "</p> <p class='messages'><b>Meddelande:</b>" + data.gbmessage + "</p></div>");
$("#kommentarer").prepend(comment);
clearForm();
} // end success
}); // end ajax
return false;
} // end else
return false;
});
});
I suggest using
$("form").on('submit', function (e) {
[...]
if(validationErrors) {
alert(Errormessage);
e.preventDefault();
}
[...]
instead of returning false.
https://developer.mozilla.org/en-US/docs/DOM/event.preventDefault
In order to get it to work, you have to use the event as a parameter of your callback function.

Categories

Resources