Validate Drop Down Selection, Alert err, Navigate back to dialog - javascript

If user does not select a valid option form drop down ("Please Select") I need to alert user to "Select Valid Rejection Reason" and return them to the dialog box from whence they came and not commit the update.
Original code written with try - catch - throw and I tried to add a condition and throw "Please select a valid Reason"
Tried to remove try - catch - throw and add a var valid = true and a conditional check
<table class="button">
<tr>
<td>
<input type="submit" onclick="Save();return false;" value="Save" class="sButton">
<input type="button" onclick="Cancel();" value="Cancel" class="sButton">
</td>
</tr>
</table>
function getReasons(ddlReason)
{
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('Reason for Rejection')/Items?$orderby=Title",
type: "GET",
async: false,
headers: {"accept": "application/json;odata=verbose"},
success: function (data) {
if (data != undefined && data.d != undefined && data.d.results != undefined && data.d.results.length > 0) {
/////////////
var option = document.createElement("option");
option.text = "Please Select";
option.value = "-1";
ddlReason.appendChild(option);
$.each(data.d.results, function( index, value )
{
var option = document.createElement("option");
option.text = value.Title;
option.value = value.Id;
ddlReason.appendChild(option);
});
}
},
error: function (xhr) {
alert(xhr.status + ': ' + xhr.statusText);
}
});
}
function Save()
{
var valid = true;
SP.SOD.executeFunc("sp.js", 'SP.ClientContext', function()
{
// try
{
var clientContext = SP.ClientContext.get_current();
var web = clientContext.get_web();
var oList = clientContext.get_web().get_lists().getByTitle('Invoice History');
var itemCreateInfo = new SP.ListItemCreationInformation();
var oListItem = oList.addItem(itemCreateInfo);
oListItem.set_item('InvoiceID', window.frameElement.dialogArgs.InvoiceID);
oListItem.set_item('Title',window.frameElement.dialogArgs.InvoiceNo);
oListItem.set_item('RejectionReason',$("#ddlRejection option:selected").text());
oListItem.set_item('Description', $("#rejectionComment").val());
oListItem.update();
clientContext.executeQueryAsync(onQuerySucceeded, onQueryFailed);
{
if(RejectionReason == "Please Select")
valid = false
}
}
if(valid == false)
{
alert("Please select a valid Reason for Rejection");
// catch(err)
}
{
// alert(err.message);
}
});
}
I think part of the problem I am having is the order I need to create this.

Related

Why validation message is shown even after correcting values

I have html contact form in which i have handled validations in JS.
If there is any incorrect data/value in any field for e.g emailid, validation works correctly, but even after correcting the data it keeps popping.
Attaching the code and the screenshot for the same.
Please help.
function askfordemo() {
var path = document.URL;
var url = "";
url = new URL(path);
var frm = $(document.forms);
var formData = JSON.stringify(frm.serialize());
var name = $("#name").val();
var emailID = $("#emailID").val();
var phone = $("#phone").val();
var companyname = $("#companyname").val();
var filter = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (filter.test(emailID)) {
return true;
} else {
$("#emailID")[0].setCustomValidity('Invalid Email Address');
return false;
}
if ($('#date1') != null && $('#date1').is(':visible')) {
var contactdate = new Date($('#date1').val());
var dateNow = new Date();
var msg = "Date cannot be less than todays date";
if (contactdate < dateNow) {
$("#date1")[0].setCustomValidity('Date cannot be less than todays date');
return;
} else if (contactdate == 'Invalid Date') {
$("#date1")[0].setCustomValidity('Please fill out this field with Date and Time');
return
} else {
$("#date1")[0].setCustomValidity("");
}
}
if (name === '' || emailID === '' || phone === '' || companyname === '' || noofemployees === null || message === '' ||
radioValue === '' || (typeof radioValue === 'undefined')) {
return false;
}
var param = new Object();
param.name = encodeURIComponent(name);
param.emailID = encodeURIComponent(emailID);
param.phone = encodeURIComponent(phone);
param.companyname = encodeURIComponent(companyname);
param.noofemployees = encodeURIComponent(noofemployees);
param.message = encodeURIComponent(message);
param.radioValue = encodeURIComponent(radioValue);
param.date1 = encodeURIComponent(date1);
param.timezone = encodeURIComponent(timezone);
var paramjson = JSON.stringify(param);
path = path.substring(0, path.lastIndexOf("/"));
$.ajax({
url: path + '/ms/askForDemo/sendMail',
type: 'POST',
data: paramjson,
dataType: "json",
contentType: "application/json",
crossDomain: 'true',
success: function(formData) {
JSON.stringify(formData)
},
error: function(x, y, z) {
alert("Internet connection is lost. Please try again later.");
}
});
}

Save values of dynamic generated HTML using javascript

I m generating dynamic html with its id. You can see the below link for the dynamic generated HTML.
Dymanic Generated HTML
So for saving this, I need some suggestion on how to save it in javascript. I tried the other fields of the HTML..
function SaveNPEDetails() {
var DashboardFields = {};
if ($('#ddlFiberised').val() == '--Select--' || $('#ddlFiberised').val() == null) {
alert('Please select FIBERISED');
return false;
}
else {
DashboardFields.NPEFiberised = $('#ddlFiberised').val();
}
if ($('#txtNoFDPSite').val() == '' || $('#txtNoFDPSite').val() == null) {
alert('Please add NO. OF FDP AT SITE');
return false;
}
else {
DashboardFields.NoOfFDPatSite = $('#txtNoFDPSite').val();
}
if ($('#txtNoOfRoutesTerAtFDP').val() == '' || $('#txtNoOfRoutesTerAtFDP').val() == null) {
alert('Please add NO. OF ROUTES TERMINATED AT FDP');
return false;
}
else {
DashboardFields.NoOfRoutesTermAtFDP = $('#txtNoOfRoutesTerAtFDP').val();
}
// Need to write saving logic for dynamic generated html here.
$.ajax({
type: "POST",
url: "DashboardData.aspx/UpdateNPEData",
data: JSON.stringify({ DashboardFields: DashboardFields }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d);
},
error: function (response) {
alert('Something went wrong..!!');
}
});
}
As per our discussion you can try something like
function SaveNPEDetails() {
var data = [];
var DashboardFields = {};
if ($('#ddlFiberised').val() == '--Select--' || $('#ddlFiberised').val() == null) {
alert('Please select FIBERISED');
return false;
}
else {
DashboardFields.NPEFiberised = $('#ddlFiberised').val();
}
if ($('#txtNoFDPSite').val() == '' || $('#txtNoFDPSite').val() == null) {
alert('Please add NO. OF FDP AT SITE');
return false;
}
else {
DashboardFields.NoOfFDPatSite = $('#txtNoFDPSite').val();
}
if ($('#txtNoOfRoutesTerAtFDP').val() == '' || $('#txtNoOfRoutesTerAtFDP').val() == null) {
alert('Please add NO. OF ROUTES TERMINATED AT FDP');
return false;
}
else {
DashboardFields.NoOfRoutesTermAtFDP = $('#txtNoOfRoutesTerAtFDP').val();
}
var chs = $("#dvNPEAddData").children(".addNPEData")
for (var i = 0; i < chs.length; i++) {
var d = {};
var ch = chs[i];
var val = $(ch).find("input[name='TerRouteName']").val();
d[$(ch).find("input[name='TerRouteName']").attr("name")] = val;
val = $(ch).find("select[name='CableType']").val();
d[$(ch).find("select[name='CableType']").attr("name")] = val;
val = $(ch).find("select[name='CableSize']").val();
d[$(ch).find("select[name='CableSize']").attr("name")] = val;
val = $(ch).find("input[name='NoLiveFibre']").val();
d[$(ch).find("input[name='NoLiveFibre']").attr("name")] = val;
data.push(d);
}
var d = JSON.stringify(data);
$.ajax({
type: "POST",
url: "DashboardData.aspx/UpdateNPEData",
data: JSON.stringify({ DashboardFields: DashboardFields , myJsonXML : d}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d);
},
error: function (response) {
alert('Something went wrong..!!');
}
});
}
Using your example in the fiddle I've done the following
$('#submit').click(function() {
var DashboardFields = {},
status = true;
$.each($('input[type="text"]'), function(i, v) {
var id = $(v).attr('id');
if ($(v).val() == '') {
alert(id + ' field is empty');
status = false;
} else {
DashboardFields[id] = $(v).val();
}
});
$.each($('select'), function(i, v) {
var id = $(v).attr('id');
if ($(v).val() == '--Select--' || $(v).val() == null) {
alert(id + ' select is empty');
status = false;
} else {
DashboardFields[id] = $(v).val();
}
});
if(!status){
alert('you have empty fields');
} else {
console.log(DashboardFields); //Here should be your Ajax Call
}
});
JsFiddle
I've used your example with ID's and created a filter in order to take dynamically the fields not by ID's, I used the ID's to map the DashboardFields object but I strongly encourage to use name or other data- param and change the jQuery code after (the line with var id=$(v).attr('id'))
Hope this helps you

Using jquery validate during form submission

I'm really new at this and I'm encountering an issue where the alert for a ddl is popping up, but in the background the form is still submitting with a blank from the value "" on the 'Select' option
The ddl:
Type
My scripts:
<script type="text/javascript">
function saveCallReport() {
var selectedFranchises = "";
var selectedGroups = "";
var selectedContacts = "";
var selectedTopics = "";
var ID = $('#<%=txtID.ClientID %>').val();
if (ID == '') ID = '0';
var Created = $('#<%=txtCreated.ClientID %>').val();
var Confidential = document.getElementById('<%=chkConfidential.ClientID %>').checked;
var Description = $('#<%=txtDescription.ClientID %>').val();
var Employee = $('#<%=ddlEmployee.ClientID %>').val();
var Priority = $('#<%=ddlPriority.ClientID %>').val();
var Type = $('#<%=ddlType.ClientID %>').val();
// Get Selected Franchises
var LstRight = document.getElementById("<%=lstSelectedFranchises.ClientID %>");
for (i = 0; i < LstRight.length; i++) {
selectedFranchises = selectedFranchises + LstRight.options[i].value + ',';
}
if (selectedFranchises == null)
selectedFranchises = "";
// Get Selected Groups
LstRight = document.getElementById("<%=lstSelectedGroups.ClientID %>");
for (i = 0; i < LstRight.length; i++) {
selectedGroups = selectedGroups + LstRight.options[i].value + ',';
}
if (selectedGroups == null)
selectedGroups = "";
// Get Selected Contacts
LstRight = document.getElementById("<%=lstSelectedContacts.ClientID %>");
for (i = 0; i < LstRight.length; i++) {
selectedContacts = selectedContacts + LstRight.options[i].value + ',';
}
if (selectedContacts == null)
selectedContacts = "";
// Get Selected Topics
LstRight = document.getElementById("<%=lstSelectedTopics.ClientID %>");
for (i = 0; i < LstRight.length; i++) {
selectedTopics = selectedTopics + LstRight.options[i].value + ',';
}
if (selectedTopics == null)
selectedTopics = "";
var obj = {
id: ID,
created: Created,
hqemployee: Employee,
type: Type,
priority: Priority,
confidential: Confidential,
description: Description,
franchises: selectedFranchises,
groups: selectedGroups,
contacts: selectedContacts,
topics: selectedTopics,
};
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '<%= ResolveUrl("~/CallReportDetail.aspx/saveCallReport") %>',
data: JSON.stringify(obj),
dataType: "json",
success: function (result) {
$('#txtID').val(result.d);
window.location.replace("/CallReports/Details?Id=" + result.d);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("There was a problem saving the Call Report: " + thrownError);
}
});
return false;
}
var submit = 0;
function CheckDouble() {
if (++submit > 1) {
alert('Saving...');
return false;
}
}
$(function formValid() {
$("[id*=btnSave]").click(function() {
var ddlType = $("[id*=ddlType]");
if (ddlType.val() == "") {
alert("Please select a type!");
return false;
}
});
});
</script>
My submit button:
<td style="padding-left: 720px;">
<asp:LinkButton ID="btnSave" Type="submit" runat="server" Text="Save" OnClientClick="CheckDouble(); return saveCallReport();" UseSubmitBehavior="false" CssClass="btn btn-primary btn-sm"/>
</td>
Can anybody tell me where I may be going wrong? I had a notion that I need a submitHandler, but don't have a clue how to write that into this code.
Ok there's a few issues here.
You should avoid adding OnClientClick and JQuery .click() events on the same button. It's just bad style, and a bit confusing.
You're submitting the data via JQuery ajax, so there's no need for a LinkButton. Just use a normal html button.
Your saveCallReport() function handles the success and failure outcomes all by itself, there's no need to return anything.
The CheckDouble() method will increment the submit value even if the validation fails, so then a subsequent click on the button after you select from the ddl will alert the Saving... message, which is not the intended behavior. You should just add/remove a disabled attribute on the button while it's submitting.
So anyway, here's what I would suggest. The html button:
<button id="btnSave" class="btn btn-primary btn-sm">Save</button>
Wire up the button:
$(document).ready(function() {
$('#btnSave').click(function () {
var ddlType = $("#ddlType");
if (ddlType.val() == "") {
alert("Please select a type!");
return false;
}
$(this).attr("disabled", "disabled");
saveCallReport();
$(this).removeAttr("disabled");
});
});

Change text using javascript not working in chrome

I want to change text to "saving ... " when a link clicked, then I use ajax, query resets to save the form. one i receive the request i need to change the text back to normal.
In Firefox the work fine, but in chrome the text get change once response received. There is a delay in changing the text.
See my code:
function submitForm(frm, action) {
var performAction = true;
var isChange = false;
document.getElementById('saveButton').innerHTML = 'processing....';
freezeWindow();
if ((document.getElementById("primaryIframe") != null) && (action == "Save")) {
var frameId = 0;
functionSaveIframes(frameId, isChange);
} else {
if (performAction == true) {
sessionStorage.setItem('singlePage', 'false');
window.open('www.google.com', '_self');
}
}
}
function functionSaveIframes (frameId,isChange) {
var iframes = {"0":"frame1","1":"frame2"};
var url = {"0":"/test/testPrimaryPostAction.do",
"1":"/test/test2PrimaryPostAction.do"};
var iframe = document.getElementById(iframes[frameId]);
var doc = iframe.contentWindow.document;
var form = doc.forms[0];
var isEdited = doc.forms[0].isEdited.value;
var formData = $(form).serializeArray();
formData.push({name: 'fwdval', value: 'Save'});
var myUrl = url[frameId];
if(isEdited == 'true'){
isChange=true;
$.ajax({
type: "POST",
async: false,
cache: false,
url: myUrl,
data: formData,
success: function(data) {
doc.forms[0].isEdited.value = "false";
frameId = frameId + 1 ;
if (frameId < 9) {
functionSaveIframes(frameId,isChange);
}else if (frameId == 9){
reloadErrors(isChange);
}
},
error: function(e){
$("#freezeFrame").css("display","none");
alert("error Saving Data in " + iframes[frameId] + "Please try again");
}
});
}
else{
frameId = frameId + 1 ;
if (frameId < 9) {
functionSaveIframes(frameId,isChange);
}
else if (frameId == 9){
reloadErrors(isChange);
}
}
}
<li><a id="saveButton" href="javascript:submitForm( document.forms[0], 'Save' );"><i class="fa fa-floppy-o" aria-hidden="true"></i> Save</a>
</li>
**In Success Function you need to change text by using .html() **
Please check the below example.

How to display alert after AJAX post success.alert?

In my Node application I have used get and post request. Using get just renders the page and using post insert data into MySQL database. Data is inserted properly but after post gets called and alert fade away very quickly.
This is my code from app.js:
app.get('/Associate', routes.Associate);
app.get('/addAssociate',routes.addAssociate);
app.post('/addAssociate',routes.postAssociate);
This is my code from routes.js:
Associate: function(req, res) {
sess = req.session;
var name = req.session.user;
var username = 'SELECT first_name from user_info where email_id=?';
if (sess.user) {
console.log('\n--------------------- Associate ----------------------');
var db = req.app.get('db')();
var id = req.query['id'];
// var newsquery='SELECT * from associate_info';
var assoquery = 'SELECT associate_id,doctor_id,CONCAT(initial," ",first_name," ",middle_name," ",last_name) As Name,qualification,address_line1,city,state,pincode,email_id,contact_no from associate_info ';
var redirect = 'Associate_Listing';
async.parallel({
one: function(callback) {
db.query(assoquery, function(error, rows, fields, next) {
console.log("length-\t", rows.length);
callback(error, rows);
});
},
two: function(callback) {
db.query(username, [name], function(error, rows, fields, next) {
// console.log(rows.length);
console.log(rows);
callback(error, rows);
});
}
},
function(error, results) {
var totalNews = results.one.length;
for (var i = 0; i < results.one.length; i++) {
if (!(results.one[i].views > 0) || results.one[i].views == null)
results.one[i].views = 0;
results.one[i].ids = i + 1;
// if(!(results.one[i].views>0))
// results.one[i].views=0;
}
// console.log("--------",results.one[0].id);
res.render(redirect, {
error: JSON.stringify(1),
from_period: 0,
to_period: 0,
state: JSON.stringify("All States"),
user2: "Dr" + " " + JSON.parse(JSON.stringify(results.two[0]["first_name"])),
user: JSON.parse(JSON.stringify(req.session.user)),
Associate: results.one,
str_journal: JSON.stringify(results.one),
user_type_id: req.session.user_type_id,
totalJournals: JSON.stringify(totalNews)
});
});
} else {
res.redirect('/login');
}
},
// addJournal:function(req,res){
addAssociate: function(req, res) {
console.log('\n-------------------- addAssociate ----------------------\n');
var name = req.session.user;
var db = req.app.get('db')();
var username = 'SELECT first_name from user_info where email_id=?';
if (req.session.user) {
async.parallel({
one: function(callback) {
db.query(username, [name], function(error, rows, fields, next) {
console.log("length-\t", rows.length);
callback(error, rows);
});
}
},
function(error, results) {
res.render('addAssociate', {
user: JSON.parse(JSON.stringify(req.session.user)),
// cases : results.one,
user2: "Dr" + " " + JSON.parse(JSON.stringify(results.one[0]["first_name"])),
user_type_id: req.session.user_type_id,
// totalNews :JSON.stringify(totalNews)
})
});
} else {
res.redirect('/login');
// res.redirect('addAssociate');
}
},
postAssociate: function(req, res) {
console.log('\n-------------------- postAssociate ----------------------\n');
var db = req.app.get('db')();
// res.send('Username: ' + req.body.doctorName);
// var title = req.body.title;
// var created =req.body.created;
// initial : req.body.doctorName,
// var id=1;
// var dateArray=created.split('/');
// var finalDate=""+dateArray[2]+"/"+dateArray[1]+"/"+dateArray[0];
// var date1=new Date(finalDate);
var initial;
var first_name;
var middle_name;
var last_name;
var qualification;
var address_line1;
var address_line2;
var city;
var state;
var pincode;
var email_id;
var contact_no;
var Uname = req.session.user;
var post = {
initial: req.body.initial,
first_name: req.body.first_name,
middle_name: req.body.middle_name,
last_name: req.body.last_name,
qualification: req.body.qualification,
address_line1: req.body.address_line1,
address_line2: req.body.address_line2,
city: req.body.city,
state: req.body.state,
pincode: req.body.pincode,
email_id: req.body.email_id,
contact_no: req.body.contact_no,
status: 1,
};
console.log('--------------------' + initial)
console.log(initial);
console.log(post);
db.query('SELECT * from user_info where email_id= ? ', [Uname], function(error, rows, fields) {
if (error) {
console.log(error);
} else {
console.log('name------------' + Uname);
console.log('rows---------' + rows.length);
for (var i in rows) {
console.log('----------hhh---' + rows[i].doctor_id);
}
db.query('INSERT INTO associate_info SET doctor_id=' + rows[i].doctor_id + ', creation_date=CURRENT_TIMESTAMP(), ? ', post, function(error, result) {
console.log('inside if');
if (error) {
console.log(error);
res.status(200).send({
success: 3,
error: error
});
return;
}
console.log('Associate added successfully.');
});
}
});
},
this is jquery ajax code
$(document).ready(function() {
$("#save").click(function() {
var initial = $("#doctorName").val();
var first_name = $("#firstName").val();
var middle_name = $("#middleName").val();
var last_name = $("#lastName").val();
var qualification = $("#qualification").val();
var address_line1 = $("#address1").val();
var address_line2 = $("#address2").val();
var city = $("#city").val();
var state = $("#state").val();
var pincode = $("#pincode").val();
var email_id = $("#email").val();
var contact_no = $("#mobile").val();
var dr = /^[a-zA-Z]+\.$/;
var alphaExp = /^[a-zA-Z]+$/;
var zipexp = /^[0-9]{1,6}$/;
var mobileexp = /^(\+91-|\+91|0)?\d{10}$/;
var emailexp = /^[A-Z0-9_'%=+!`#~$*?^{}&|-]+([\.][A-Z0-9_'%=+!`#~$*?^{}&|-]+)*#[A-Z0-9-]+(\.[A-Z0-9-]+)+$/i;
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'initial=' + initial + '&first_name=' + first_name + '&middle_name=' + middle_name + '&last_name=' + last_name + '&qualification=' + qualification + '&address_line1=' + address_line1 + '&address_line2=' + address_line2 + '&city=' + city + '&state=' + state + '&pincode=' + pincode + '&email_id=' + email_id + '&contact_no=' + contact_no;
if (initial == '' || first_name == '' || middle_name == '' || last_name == '' || qualification == '' || address_line1 == '' || address_line2 == '' || city == '' || state == '' || pincode == '' || email_id == '' || contact_no == '') {
alert("Please Fill All Mandatory Fields");
return false;
} else if (!initial.match(alphaExp) && !initial.match(dr)) {
alert("please insert valid initial");
$("#doctorName").val('');
document.getElementById('doctorName').focus();
return false;
} else if (!first_name.match(alphaExp)) {
alert("please insert valid first name");
$("#firstName").val('');
document.getElementById('firstName').focus();
return false;
} else if (!middle_name.match(alphaExp)) {
alert("please insert valid middle name");
$("#middleName").val('');
document.getElementById('middleName').focus();
return false;
} else if (!last_name.match(alphaExp)) {
alert("please insert valid last name");
$("#lastName").val('');
document.getElementById('lastName').focus();
return false;
} else if (!pincode.match(zipexp) || pincode.length != 6) {
alert("please insert valid pincode");
$("#pincode").val('');
document.getElementById('pincode').focus();
return false;
} else if (!email_id.match(emailexp)) {
alert("please insert email id");
$("#email").val('');
document.getElementById('email').focus();
return false;
} else if (!contact_no.match(mobileexp)) {
alert("please insert valid contact no");
$("#mobile").val('');
document.getElementById('mobile').focus();
return false;
} else {
// AJAX Code To Submit Form.
$.ajax({
type: "post",
url: "/addAssociate",
// contentType: 'application/json',
data: dataString,
cache: false,
success: function(data) {
console.log("data-----------" + data);
alert("hi");
}
});
}
// return;
// return false;
});
});
I want to display an alert after data inserted successfully into database.
Just Try the Following to make some delay.
jQuery :
$.ajax({
url:'path-to-process',
type:'POST',
data:{},
success:function(){
// Content to Display on Success.
setTimeout(function () {
// Content to Display on Success with delay.
}, 800);
}
});
Here, the "setTimeout()" will provide some specified time delay for display your content.
Have a Nice Day !
http://jsbin.com/jatuju/edit?js,output
If you are using the plan old JavaScript,you can using the XMLHttpRequest status code to determine whether is success or not

Categories

Resources