Using jquery validate during form submission - javascript

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

Related

JavaScript/JQuery: Stop script until modal form submitted

Okay, this is probably an easy one, but I just can't wrap my head around how to do it from the examples online.
Background: My code displays a modal form $("#multi_med_modal_form") asking for user input. The input from the modal form is used to finish populating some html $('#med_output') before moving on to the next line from an AJAX response.
Problem: After the modal displays, the code continues to execute subsequent lines from the AJAX response so that by the time the user submits the modal form, the variables have changed and the program (understandably) throws an error.
Question: How do I make JavaScript/JQuery wait for stop the code at $("#multi-submit-btn").click() below?
$("#med_input_form").submit(function(event){
console.log('Med Input Form Submitted');
event.preventDefault();
var serializedData = $(this).serialize();
$.ajax({
type: "POST",
url: '{% url "medrec_v2:post_medrec" %}',
data: serializedData,
success: function(response) {
$('#med_output').html("");
var med_ajax = JSON.parse(response["med_output"]);
med_ajax.line.forEach(line => {
console.log(line)
input_text = line[0]
med_list = line[1]
dose = line[2]
if (med_list.length == 0) {
// <!---Need new Modal!-->
} else if (med_list.length > 1){
input_name = modal_option_builder("multi", line);
$("#multi_med_modal").modal('show');
//!!!---------- WAIT FOR USER TO SUBMIT MODAL FORM HERE!! ------------------!!!//
$("#multi-submit-btn").click( () => {
radio_id = $("input[name='" + input_name + "']:checked").val()
for (i = 1; i < med_list.length; i++) {
if (med_list[i].id == radio_id) {
radio_med = med_list[i];
break;
}
};
radio_html_name = html_builder(radio_med)
$('#med_output').append("<tr><th scope='row'>"+radio_html_name+"</th><td>"+dose+"</td><td>"+ radio_med.med_commonuses+ "</td></tr>");
$("#multi_med_modal").modal('hide');
})
} else {
html_name = html_builder(med_list[0]);
$('#med_output').append("<tr><th scope='row'>"+html_name+"</th><td>"+dose+"</td><td>"+ med_list[0].med_commonuses+ "</td></tr>");
}
})
}
})
});
/*<------------Build title and body for Modal form----------->
send to form to select correct medicaiton*/
function modal_option_builder(modal_type, line) {
if (modal_type =="multi") {
$("#multi_med_modal_form").empty()
input_text = line[0]
med_list = line[1]
$("#modaltitle").html('Multiple medications found for "'+input_text+'"!'); //set modal title to line string where multiple medications found
form_lines=[]
for (i = 0; i < med_list.length; i++) {
input_type = "radio";
input_id = input_type +"_"+med_list[i].id;
input_name = input_type+'-'+ input_text.replace(' ', '-');
$("#multi_med_modal_form").append(`
<div class="form-check">
<input class="form-check-input" type="`+input_type+`" name="`+input_name+`" id="`+input_id+`" value="`+med_list[i].id+`">
<label class="form-check-label" for="`+input_id+`">`+med_list[i].display_name+`</label>
</div>`);
};
return input_name;
} else if (modal_type = "no_match") {
$("#modaltitle").html('No matches found for"'+med_list[0]+'"!');
$("#multi_med_modal_form").html("");
}
};```
Like I said, this is probably easy, I just can't figure out how to do it. Thank you!
I figured it out. There's no way to "stop" the code from executing like I was describing (as far as I know). I just had to assign an id to the html element I was creating to populate with user feedback afterwards.
Here's the code:
/*------------AJAX FUNCTION---------------------*/
$("#med_input_form").submit(function(event){
console.log('Med Input Form Submitted');
event.preventDefault();
var serializedData = $(this).serialize();
$.ajax({
type: "POST",
url: '{% url "medrec_v2:post_medrec" %}',
data: serializedData,
success: function(response) {
$('#med_output').empty();
prevMedList = []
var med_ajax = JSON.parse(response["med_output"]);
line_no = 0
med_ajax.line.forEach(line => {
console.log(line)
line_no += 1
input_text = line[0]
med_list = line[1]
dose = line[2]
sig = line[3]
$('#med_output').append("<tr id='output_"+line_no+"'></tr>");
if (med_list.length == 0) {
$("#no-med-modal").modal("show");
console.log("no-med-modal shown")
$("#multi-submit-btn").click( () => {
});
} else if (med_list.length > 1){
input_name = multi_modal_builder(line);
$("#multi-med-modal").modal('show');
//---------- WAIT FOR $("#multi-submit-btn").click() HERE!! -----------//
$("#multi-submit-btn").click( () => {
radio_id = $("input[name='" + input_name + "']:checked").val()
for (i = 1; i < med_list.length; i++) {
if (med_list[i].id == radio_id) {
radio_med = med_list[i];
break;
}
};
radio_html_name = html_builder(radio_med)
$('#output_'+line_no).append("<tr><th scope='row'>"+radio_html_name+"</th><td>"+dose+"</td><td>"+ sig+ "</td><td>"+radio_med.med_commonuses+ "</td></tr>");
$("#multi-med-modal").modal('hide');
prevMedList.append([radio_id,dose]);
})
} else {
for (i in prevMedList) {
if (med_list[0].id == prevMedList[0]){
prev="true";
break;
}};
if (prev=="true"){continue};
html_name = html_builder(med_list[0]);
// console.log(html_name);
$('#output_'+line_no+'').append("<th scope='row'>"+html_name+"</th> <td>"+dose+"</td> <td>"+ sig+ "</td> <td>"+med_list[0].med_commonuses+ "</td>");
prevMedList.append([radio_id,dose]);
}
})
}
})
});

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

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.

JS insertHtml without focus?

I have some code written in PHP with textarea input field. I also have a JS code that inserts html code into field:
$('form textarea#response').ready(function() {
function populateGet() {
var obj = {}, params = location.search.slice(1).split('&');
for(var i=0, len=params.length;i<len;i++) {
var keyVal = params[i].split('=');
obj[decodeURIComponent(keyVal[0])] = decodeURIComponent(keyVal[1]);
}
return obj;
}
var test = populateGet();
var ticid;
for(var key in test) {
if(Object.prototype.hasOwnProperty.call(test, key)) {
var val = test[key];
ticid = val;
}
}
$('form select#cannedResp').val('original');
var fObj = $(this).closest('form');
var $url = 'ajax.php/tickets/'+ticid+'/canned-resp/original.json';
$.ajax({
type: "GET",
url: $url,
dataType: 'json',
cache: false,
success: function(canned){
console.log('dupa');
//Canned response.
var box = $('form textarea#response'),
redactor = box.data('redactor');
if(canned.response) {
if (redactor){
redactor.insertHtml(canned.response);
}else{
box.val(box.val() + canned.response);
box.blur();
}
//if (redactor)
//redactor.observeStart();
}
//Canned attachments.
var ca = $('.attachments', fObj);
if(canned.files && ca.length) {
var fdb = ca.find('.dropzone').data('dropbox');
$.each(canned.files,function(i, j) {
fdb.addNode(j);
});
}
document.getElementById('focustest').focus();
}
})
.done(function() { })
.fail(function() { });
});
The problem is that execution of above code (redactor.insertHtml(canned.response);) causes focus on the textarea. The code is executed on page load.
Is there any way I can insert the content into field without causing the focus to placed on this field?
Thank you in advance and best regards
Tom

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.

post data using ajax and js

Every time i try to use my classes below to post the array i made (also below) the ajax request doesn't pass the input as $_POST values but as $_REQUEST values seen in the web address bar at the top of the screen. I'm very new to Ajax and javascript (only been working with it about a month) so any tips and trick to fix anything below is greatly appreciated.
var formErrors=["Passage","FirstName","Zip"];
var formInput=["EventID","Passage","FirstName","LastName","Email","Organization","Location","Zip"];
Head of HTML
$(function () {
$("#signUp").click(function() {
if(formArrayValidation(formErrors) != false) {
formPostAjax(formInput, 'join-event.php');
}
return false;
});
});
Basics.js
formArrayValidation = function(errorArray) {
for(var i = 0; i < errorArray.length; i++) {
$('.error').hide();
var name = $("input#" + errorArray[i]).val();
if (name == "") {
$("label#" + errorArray[i] + "_error").show();
$("input#" + errorArray[i]).focus();
return false;
}
}
}
formPostAjax = function(inputArray, form) {
var dataString = "";
for(var i = 0; i < inputArray.length; i++)
{
var data = inputArray[i];
var dataInput = $("input#" + data).val();
if(i = 0) {
dataString = dataString + data + '=' + dataInput;
}
else {
dataString = dataString + '&' + data + '=' + dataInput;
}
}
$.ajax ({
type: "POST",
url: form,
data: dataString,
success: function() {
}
});
}
Your event listener should be on the form and it should be:
$('#form_identifier').submit(...);
Additionally, jQuery provides a nice shortcut method for serializing form data:
$('#form_identifier').submit(function(){
var post_data = $(this).serialize()
// ....
return false;
});

Categories

Resources