Synchronous calls - javascript

I want to delete the file after i downloaded it from the server, but the delete method in service executes first even if i place it below the line of download file this is my code:
generateClearanceExcel(): void {
if (this.selectedIds.length > 0) {
var departureDate = prompt("Please enter departure date.", "");
if (departureDate !== null && departureDate !== "") {
this.generating = true;
this.clearanceService.generateClearanceExcel(this.selectedIds, departureDate).subscribe(
result => {
this.generating = false;
window.location.href = "clearance/downloadreport/?fileName=" + result.fileName;
this.clearanceService.deleteFile(result.fileName).subscribe();
if (result.success == true) {
if (result.infos.length > 0) {
this.alertService.info(result.infos);
}
}
else {
this.alertService.error(result.errors);
}
}
);
}
}
}
TIA.

Lets try with timeout
generateClearanceExcel(): void {
if (this.selectedIds.length > 0) {
var departureDate = prompt("Please enter departure date.", "");
if (departureDate !== null && departureDate !== "") {
this.generating = true;
this.clearanceService.generateClearanceExcel(this.selectedIds, departureDate).subscribe(
result => {
this.generating = false;
window.location.href = "clearance/downloadreport/?fileName=" + result.fileName;
setTimeout(() => {
this.clearanceService.deleteFile(result.fileName).subscribe();
}, 3000);
setTimeout(function(){ }, 3000);
if (result.success == true) {
if (result.infos.length > 0) {
this.alertService.info(result.infos);
}
}
else {
this.alertService.error(result.errors);
}
}
);
}
}
}

You should place the delete method inside the condition of success of download.
generateClearanceExcel(): void {
if (this.selectedIds.length > 0) {
var departureDate = prompt("Please enter departure date.", "");
if (departureDate !== null && departureDate !== "") {
this.generating = true;
this.clearanceService.generateClearanceExcel(this.selectedIds, departureDate).subscribe(
result => {
this.generating = false;
window.location.href = "clearance/downloadreport/?fileName=" + result.fileName;
if (result.success == true) {
this.clearanceService.deleteFile(result.fileName).subscribe();
if (result.infos.length > 0) {
this.alertService.info(result.infos);
}
}
else {
this.alertService.error(result.errors);
}
}
);
}
}
}

Related

How to prevent two JavaScript files from executing simultaneously

I have two JavaScript files. One is running validation, and other have ajax plugin that sends form after validation.
When I attached these files in the header section, then they simultaneously run, but if I attach these two files in the body, then validation runs as it should but ajax call not working.
There is no any error on the console as well.
..
What you people suggests?
AjaxCall.js
$(document).ready(function() {
var options = {
beforeSubmit: showRequest, // pre-submit callback
success: showResponse, // post-submit callback
url: 'quoteProcess.php', // override for form's 'action' attribute
type: 'post', // 'get' or 'post', override for form's 'method' attribute
clearForm: true // clear all form fields after successful submit
};
// bind 'myForm' and provide a simple callback function
$('#testform').ajaxForm(options);
});
// pre-submit callback
function showRequest(formData, jqForm, options) {
$('.modal').show();
return true;
}
function showResponse(responseText, statusText, xhr, $form) {
$('.modal').hide();
alert( '\n\nYour Quote has been Recieved ! \n' + responseText +
'\n');
window.location.replace("http://localhost/lamozine/quote.php");
}
validation.js
(function($){
var functions = {
reset: resetValidation
};
var settings;
var _reqForm;
var _indicatorTemplate = '<span class="error-indicator" role="alert" aria-live="assertive" aria-hidden="true"></span>';
var _summaryTemplate = '<div id="errorSummary" class="alert alert-danger" role="alert" aria-live="assertive" tabindex="-1"><p>{0}</p></div>';
var _validationTypes = {
required: {msg: ' is required' },
tel: {msg: ' is not a valid phone number' },
email: {msg: ' is not a valid email address' },
date: {msg: ' is not a valid date'},
number: {msg: ' is not a valid number'}
};
$.fn.attrvalidate = function() {
if (!this.is('form')) {
return this;
}
if (typeof arguments[0] === 'string') {
var property = arguments[1];
var newArgs = Array.prototype.slice.call(arguments);
newArgs.splice(0, 1);
functions[arguments[0]].apply(this, newArgs);
} else {
setupFormValidation.apply(this, arguments);
}
return this;
};
function resetValidation(){
$(_reqForm).find('input, select, textarea, fieldset').removeClass('invalid');
$(_reqForm).find('.error-indicator').attr('aria-hidden', true);
$(_reqForm).find('#errorSummary').remove();
}
function setupFormValidation(options){
settings = $.extend({
showFieldIndicator: true,
showErrorSummary: true,
errorSummaryMsg: 'Please fix the following issues before continuing:',
validateTel: true,
telRegex: /^\+*[\d-()]{7,20}$/,
validateEmail: true,
emailRegex: /^(\S+#\S+)*$/,
validateDate: true,
validateNumber: true
}, options);
_reqForm = this;
initialiseValidation();
$(_reqForm).bind('submit', handleSubmit);
}
function initialiseValidation(){
var _groupsInitialised = [];
$(_reqForm).find('input, select[required], textarea[required]').each(function(){
if (isRadioGroup($(this)) && $(this).is('[required]')) {
var groupName = $(this).attr('name');
if ($.inArray(groupName, _groupsInitialised) === -1) {
$(this).attr('data-do-validate', true);
setFieldName($(this));
if (settings.showFieldIndicator){
$(this).parents('fieldset').first().append($(_indicatorTemplate));
}
$(_reqForm).find('input[name="' + $(this).attr('name') + '"]').each(function(){
$(this).change(function(){
handleFieldChanged($(this));
});
});
_groupsInitialised.push(groupName);
}
} else {
if ($(this).is('[required]') ||
(settings.validateTel && $(this).is('input[type="tel"]')) ||
(settings.validateEmail && $(this).is('input[type="email"]')) ||
(settings.validateDate && $(this).is('input[type="date"]')) ||
(settings.validateNumber && $(this).is('input[type="number"]'))){
$(this).attr('data-do-validate', true);
setFieldName($(this));
if (settings.showFieldIndicator){
if (($(this).is('input[type="radio"]') || $(this).is('input[type="checkbox"]')) && $(this).next('label').length > 0) {
$(this).next('label').after($(_indicatorTemplate));
} else {
$(this).after($(_indicatorTemplate));
}
}
$(this).change(function(){
handleFieldChanged($(this));
});
}
}
});
}
function handleFieldChanged(elem){
var validationResult = validateField(elem);
if (validationResult.isValid) {
clearFieldError(elem);
} else {
var fieldMsg = getFieldMessage(elem, validationResult.type);
showFieldError(elem, fieldMsg);
}
}
function handleSubmit(e){
e.preventDefault();
var formValid = true;
var errorMessages = [];
$(_reqForm).find('#errorSummary').remove();
$(_reqForm).find('[data-do-validate="true"]').each(function(){
var validationResult = validateField($(this));
if (!validationResult.isValid) {
var fieldMsg = getFieldMessage($(this), validationResult.type);
errorMessages.push({ elem: $(this).prop('id'), msg: fieldMsg });
showFieldError($(this), fieldMsg);
formValid = false;
} else {
clearFieldError($(this));
}
});
if (!formValid) {
if (settings.showErrorSummary) {
showErrorSummary(errorMessages);
}
return false;
} else {
if (typeof(settings.submitFunction) !== 'undefined') {
settings.submitFunction();
} else {
_reqForm[0].submit();
}
}
}
function validateField(elem){
if (!elem.is(':visible') || elem.parents('[aria-hidden="true"]').length > 0){
return { isValid: true };
}
if (elem.is('input[type="radio"]')) {
if (elem.is('[required]')){
if (isRadioGroup(elem)) {
return { isValid: ($(_reqForm).find('input[name="' + elem.attr('name') + '"]:checked').length > 0), type: _validationTypes.required };
} else {
return { isValid: elem.is(':checked'), type: _validationTypes.required };
}
} else {
return { isValid: true };
}
} else if (elem.is('input[type="checkbox"]')) {
return { isValid: (!elem.is('[required]') || elem.is(':checked')), type: _validationTypes.required };
} else {
if (elem.is('[required]') && (elem.val() === '')) {
return { isValid: false, type: _validationTypes.required };
} else if (settings.validateTel && elem.is('input[type="tel"]')) {
return { isValid: settings.telRegex.test(elem.val().replace(/ /g, '')), type: _validationTypes.tel };
} else if (settings.validateEmail && elem.is('input[type="email"]')) {
return { isValid: settings.emailRegex.test(elem.val().trim()), type: _validationTypes.email };
} else if (settings.validateDate && elem.is('input[type="date"]')) {
var doesPass;
if (elem.val().trim() === '') {
doesPass = true;
} else if (isNaN(Date.parse(elem.val()))) {
doesPass = false;
} else if (elem.prop('max') && !isNaN(Date.parse(elem.prop('max'))) && Date.parse(elem.val()) > Date.parse(elem.prop('max'))) {
doesPass = false;
} else if (elem.prop('min') && !isNaN(Date.parse(elem.prop('min'))) && Date.parse(elem.val()) < Date.parse(elem.prop('min'))) {
doesPass = false;
} else {
doesPass = true;
}
return { isValid: doesPass, type: _validationTypes.date };
} else if (settings.validateNumber && elem.is('input[type="number"]')) {
var doesPass;
if (elem.val().trim() === '') {
doesPass = true;
} else if (isNaN(parseFloat(elem.val()))) {
doesPass = false;
} else if (elem.prop('max') && !isNaN(parseFloat(elem.prop('max'))) && parseFloat(elem.val()) > parseFloat(elem.prop('max'))) {
doesPass = false;
} else if (elem.prop('min') && !isNaN(parseFloat(elem.prop('min'))) && parseFloat(elem.val()) < parseFloat(elem.prop('min'))) {
doesPass = false;
} else {
doesPass = true;
}
return { isValid: doesPass, type: _validationTypes.number };
} else {
return { isValid: true };
}
}
}
function setFieldName(elem){
if (typeof(elem.data('error-msg')) !== 'undefined' && elem.data('error-msg') !== '') {
return;
}
var elemName;
var forLabel = $(_reqForm).find('label[for="' + elem.attr('id') + '"]');
if (forLabel.length > 0 && $(forLabel[0]).text() !== '') {
elemName = $(forLabel[0]).text();
} else {
elemName = elem.attr('name');
}
elem.data('error-name', elemName);
}
function getFieldMessage(elem, resultType){
var elemMsg;
if (typeof(elem.data('error-msg')) !== 'undefined' && elem.data('error-msg') !== '') {
elemMsg = elem.data('error-msg');
} else {
elemMsg = elem.data('error-name') + resultType.msg;
}
return elemMsg;
}
function showFieldError(elem, fieldMsg){
if (isRadioGroup(elem)) {
elem.parents('fieldset').first().addClass('invalid');
if (settings.showFieldIndicator){
elem.parents('fieldset').first().find('.error-indicator').first().text(fieldMsg).attr('aria-hidden', false);
}
} else {
elem.addClass('invalid');
if (settings.showFieldIndicator){
elem.nextAll('.error-indicator').first().text(fieldMsg).attr('aria-hidden', false);
}
}
}
function clearFieldError(elem){
if (isRadioGroup(elem)) {
elem.parents('fieldset').removeClass('invalid');
if (settings.showFieldIndicator){
elem.parents('fieldset').first().find('.error-indicator').first().attr('aria-hidden', true);
}
var firstInGroup = $(_reqForm).find('input[name="' + elem.attr('name') + '"]').first();
var summaryItem = $('#errorSummary li a[data-field="' + firstInGroup.attr('id') + '"]');
if (summaryItem.length > 0) {
summaryItem.parent('li').remove();
if ($('#errorSummary ul li').length === 0) {
$('#errorSummary').remove();
}
}
} else {
elem.removeClass('invalid');
if (settings.showFieldIndicator){
elem.nextAll('.error-indicator').first().attr('aria-hidden', true);
}
var summaryItem = $('#errorSummary li a[data-field="' + elem.attr('id') + '"]');
if (summaryItem.length > 0) {
summaryItem.parent('li').remove();
if ($('#errorSummary ul li').length === 0) {
$('#errorSummary').remove();
}
}
}
}
function showErrorSummary(errorMsgList){
var errorSummary = $(_summaryTemplate.replace('{0}', settings.errorSummaryMsg));
var errorList = $('<ul></ul>');
for (var i=0; i < errorMsgList.length; i++) {
var errorLink = $('' + errorMsgList[i].msg + '');
errorLink.click(function(){ jumpToElem($(this).data('field')); return false; });
var errorItm = $('<li></li>');
errorItm.append(errorLink);
errorList.append(errorItm);
}
errorSummary.append(errorList).prependTo($(_reqForm));
errorSummary.focus();
}
function isRadioGroup(elem){
return (elem.is('input[type="radio"]') && typeof(elem.attr('name')) !== 'undefined' && elem.attr('name') !== '');
}
function jumpToElem(fieldId){
$(_reqForm).find('#' + fieldId).focus();
}
}(jQuery));
I am not clear with your question very well but if you want to load one script file after loading an another script file. You can simple load using $.when() and $.getScript() jquery functions like this.
$.getScript() will load javascript file asynchronously and .done() call back of $.when() method will continue after the loading script done.
This is a very simple sample.
<html>
<head>
<script src="/jquery.min.js"></script>
</head>
<body>
<script>
$.when(
$.getScript("/mypath/validation.js")
).done(function(){
$.getScript("/mypath/AjaxCall.js")
});
</script>
</body>
Hope it might help.

Bootstrap light box, with next arrows not aligned

for one of the web sites that i am developing i have used the bootstrap light box, along with the next and back buttons. so from the slider when an video or image is clicked it will be displayed in the light box, and there the next buttons will help to navigates. while navigating the arrow that is suppose to be in the middle suddenly moves to the top. how can this be prevented from moving?
the java script code for the light box
EkkoLightbox.prototype = {
modal_shown: function() {
var video_id,
_this = this;
if (!this.options.remote) {
return this.error('No remote target given');
} else {
this.gallery = this.$element.data('gallery');
if (this.gallery) {
if (this.options.gallery_parent_selector === 'document.body' || this.options.gallery_parent_selector === '') {
this.gallery_items = $(document.body).find('*[data-toggle="lightbox"][data-gallery="' + this.gallery + '"]');
} else {
this.gallery_items = this.$element.parents(this.options.gallery_parent_selector).first().find('*[data-toggle="lightbox"][data-gallery="' + this.gallery + '"]');
}
this.gallery_index = this.gallery_items.index(this.$element);
$(document).on('keydown.ekkoLightbox', this.navigate.bind(this));
if (this.options.directional_arrows && this.gallery_items.length > 1) {
this.lightbox_container.append('<div class="ekko-lightbox-nav-overlay"></div>');
this.modal_arrows = this.lightbox_container.find('div.ekko-lightbox-nav-overlay').first();
this.lightbox_container.find('a' + this.strip_spaces(this.options.left_arrow_class)).on('click', function(event) {
event.preventDefault();
return _this.navigate_left();
});
this.lightbox_container.find('a' + this.strip_spaces(this.options.right_arrow_class)).on('click', function(event) {
event.preventDefault();
return _this.navigate_right();
});
}
}
if (this.options.type) {
if (this.options.type === 'image') {
return this.preloadImage(this.options.remote, true);
} else if (this.options.type === 'youtube' && (video_id = this.getYoutubeId(this.options.remote))) {
return this.showYoutubeVideo(video_id);
} else if (this.options.type === 'vimeo') {
return this.showVimeoVideo(this.options.remote);
} else if (this.options.type === 'instagram') {
return this.showInstagramVideo(this.options.remote);
} else if (this.options.type === 'url') {
return this.loadRemoteContent(this.options.remote);
} else if (this.options.type === 'video') {
return this.showVideoIframe(this.options.remote);
} else {
return this.error("Could not detect remote target type. Force the type using data-type=\"image|youtube|vimeo|instagram|url|video\"");
}
} else {
return this.detectRemoteType(this.options.remote);
}
}
},
strip_stops: function(str) {
return str.replace(/\./g, '');
},
strip_spaces: function(str) {
return str.replace(/\s/g, '');
},
isImage: function(str) {
return str.match(/(^data:image\/.*,)|(\.(jp(e|g|eg)|gif|png|bmp|webp|svg)((\?|#).*)?$)/i);
},
isSwf: function(str) {
return str.match(/\.(swf)((\?|#).*)?$/i);
},
getYoutubeId: function(str) {
var match;
match = str.match(/^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/);
if (match && match[2].length === 11) {
return match[2];
} else {
return false;
}
},
getVimeoId: function(str) {
if (str.indexOf('vimeo') > 0) {
return str;
} else {
return false;
}
},
getInstagramId: function(str) {
if (str.indexOf('instagram') > 0) {
return str;
} else {
return false;
}
},

Data gets lost in a java script and .Net based chat app

This code has landed on my lap, and I don't have any clue what might be going on. The code is a Java Script in an ascx file as part of a chat system. The problem is that the chat content are lost after about 10 minutes. I don't know if this has anything to do with caching or not. I would like to know what might be causing the loss of chat content in this code.
<script type="text/javascript">
var roomid = '<%= ChatRoomID %>';
var status = "";
var msgTimer = "";
function StartTimers(sec) {
msgTimer = window.setInterval("DoRefresh()", sec);
}
function StopTimers() {
window.clearInterval(msgTimer);
msgTimer = "";
}
function SendMsg() {
if (!xmlrequest)
InitObject();
if (xmlrequest) {
var obj = document.getElementById("txtMsg");
if (obj != null && obj.value.trim().length > 0) {
StopTimers();
status = "completed";
var nowTime = new Date().getTime(); //Get now time as random
var params = "act=sendmsg&rid=" + roomid + "&gid=&msg=" + encodeURIComponent(obj.value) + "&st=" + status;
//xmlrequest.abort();
xmlrequest.onreadystatechange = SendMsg_Callback; //(GetBrowserVer() != "Firefox") ? (SendMsg_Callback) : (SendMsg_Callback());
xmlrequest.open("POST", "/site/function/chat.ashx?t=" + nowTime, false);
xmlrequest.setRequestHeader("If-Modified-Since", "0"); // Avoid the cache in IE
xmlrequest.setRequestHeader("Cache-Control", "no-cache");
xmlrequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlrequest.setRequestHeader("Content-length", params.length);
xmlrequest.setRequestHeader("Connection", "close");
xmlrequest.send(params);
//xmlrequest.onreadystatechange = SendMsg_Callback; //(GetBrowserVer() != "Firefox") ? (SendMsg_Callback) : (SendMsg_Callback());
obj.value = "";
CharacterCount(obj);
obj.focus();
StartTimers(60);
}
}
}
function SendMsg_Callback() {
if (xmlrequest.readyState == 4 && (xmlrequest.status == 200 || xmlrequest.status == 0)) {
// sometimes, the completed status will equal zero in Firefox
}
}
function DoRefresh() {
StopTimers();
Refresh();
}
function Refresh() {
if (!xmlrequest)
InitObject();
if (xmlrequest) {
var nowTime = new Date().getTime(); //Get now time as random
var params = "act=refresh&rid=" + roomid + "&gid=&st=" + status;
//xmlrequest.abort();
xmlrequest.onreadystatechange = Refresh_Callback; //(GetBrowserVer() != "Firefox") ? (Refresh_Callback) : (Refresh_Callback());
xmlrequest.open("POST", "/site/function/chat.ashx?t=" + nowTime, true);
xmlrequest.setRequestHeader("If-Modified-Since", "0"); // Avoid the cache in IE
xmlrequest.setRequestHeader("Cache-Control", "no-cache");
xmlrequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlrequest.setRequestHeader("Content-length", params.length);
//xmlrequest.setRequestHeader("Connection", "close");
xmlrequest.send(params);
xmlrequest.onreadystatechange = Refresh_Callback; //(GetBrowserVer() != "Firefox") ? (Refresh_Callback) : (Refresh_Callback());
}
}
function Refresh_Callback() {
if (xmlrequest.readyState == 4 && (xmlrequest.status == 200 || xmlrequest.status==0)) {
//if (xmlrequest.readyState == 4 && xmlrequest.status == 200) {
// Is ready
var response = xmlrequest.responseText;
//alert(response);
//document.write("<p>" + response + "</p>");
if (response != undefined && response.length > 0) {
var vals = null;
vals = response.split("<<<<<>>>>>");
if (vals == null || vals.length < 2) {
document.getElementById("msglist").value = response;
return;
}
/// The part one of response value is user list
var obj = document.getElementById("userlist");
if (obj != null && vals[0].length > 0) {
//alert(vals[0]);
obj.options.length = 0;
var options = vals[0].split(",");
for (i = 0; i < options.length; i++) {
obj.options.add(new Option(options[i], options[i]));
}
}
/// The part two of response value is chat message list
obj = document.getElementById("msglist");
if (obj != null && vals[1].length > 0) {
obj.innerHTML += vals[1] + "<br/>";
//obj.scrollIntoView("true");
obj.scrollTop = obj.scrollHeight;
}
/// The part three of response value is command or status
if (vals.length > 2) {
if (vals[2].toLowerCase() == "reload") {
//var sUrl = window.location.href;
//sUrl += (sUrl.indexOf("?") > 0) ? "&" : "?" + "r=t";
//window.location.href = sUrl; // window.location.href;
redirectURL(window.location.href);
}
else {
obj = document.getElementById("divStatus");
if (obj != null) {
obj.innerHTML = vals[2];
}
}
}
}
StartTimers(2500);
}
}
//////////////////////// End Call Ajax Function //////////////////////////////
function GetBrowserVer() {
var OsObject = "";
if (navigator.userAgent.toLowerCase().indexOf("msie") > 0) {
return "MSIE"; //IE
}
if (isFirefox = navigator.userAgent.toLowerCase().indexOf("firefox") > 0) {
return "Firefox"; //Firefox
}
if (isSafari = navigator.userAgent.toLowerCase().indexOf("safari") > 0) {
return "Safari"; //Safan
}
if (isCamino = navigator.userAgent.toLowerCase().indexOf("camino") > 0) {
return "Camino"; //Camino
}
if (isMozilla = navigator.userAgent.toLowerCase().indexOf("gecko") > 0) {
return "Gecko"; //Gecko
}
}
function getKeycode(evt) {
// Usually evt is indicated as keypress or other key events
var keycode = 0;
if (evt != undefined && evt != null && "which" in evt) {// NN4 & FF & Opera
keycode = evt.which;
}
else if (evt != undefined && evt != null && "keyCode" in evt) {// Safari & IE4+
keycode = evt.keyCode;
}
else if ("keyCode" in window.event) {// IE4+
keycode = window.event.keyCode;
}
else if ("which" in window.event) {
keycode = evt.which;
}
return keycode;
}
function DoSendMsg(e) {
//debugger
if (e.ctrlKey && getKeycode(e) == 13) {
SendMsg();
}
}
String.prototype.trim = function () {
return this.replace(/(^\s*)|(\s*$)/g, "");
}
function redirectURL(url) {
if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
var referLink = document.createElement('a');
referLink.href = url;
document.body.appendChild(referLink);
referLink.click();
} else {
window.location.href = url;
}
}
var CurrentUrl = '<%= Request.Url.ToString().ToLower() %>';
window.onload = function() {
if (CurrentUrl.indexOf("config_page_edit.aspx") < 0 && CurrentUrl.indexOf("config_page_preview.aspx") < 0) {
StartTimers(500);
}
}

Simplify syntax, how to avoid duplicate "if"?

I want to check a form when fields are error and disabling submit button as appropriate. I found a solution that works, but the syntax is ugly. :)
$(document).ready(function() {
$("#send").attr("disabled", "disabled");
$("#validatemail").keyup(function()
{
var email = $("#validatemail").val();
if (email != '')
{
if(isvalidmail(email))
{
// do stuff
}
else
{
// do stuff
}
}
else
{
// do stuff
}
});
$("#validatetitle").keyup(function()
{
var subject = $("#validatetitle").val();
if (subject != '')
{
if ((subject.length < 3) || (subject.length > 30))
{
// do stuff
}
else
{
// do stuff
}
}
else
{
// do stuff
}
});
$("#form_message").live('keyup', function()
{
// Duplicate is not smart!!!
var email = $("#validatemail").val(); // Duplicate
var subject = $("#validatetitle").val(); // Duplicate
if (
(isvalidmail(email)) // Duplicate
&&
(!((subject.length < 3) || (subject.length > 30))) // Duplicate
)
{
$("#send").removeAttr("disabled");
}
else
{
$("#send").attr("disabled", "disabled");
}
});
});
So how to simplify the code?
I spent several hours trying, but it did not work.
Thank you very much.
Regards,
Vincent
Try this.
$(document).ready(function() {
var isEmailValid = false;
var isSubjectValid = false;
$("#send").attr("disabled", "disabled");
$("#validatemail").keyup(function()
{
var email = $("#validatemail").val();
if (email != '')
{
if(isvalidmail(email))
{
// do stuff
isEmailValid = true;
}
else
{
// do stuff
isEmailValid = false;
}
}
else
{
// do stuff
}
});
$("#validatetitle").keyup(function()
{
var subject = $("#validatetitle").val();
if (subject != '')
{
if ((subject.length < 3) || (subject.length > 30))
{
// do stuff
isSubjectValid = true;
}
else
{
// do stuff
isSubjectValid = false;
}
}
else
{
// do stuff
}
});
$("#form_message").live('keyup', function()
{
// now just get all the set values here
$("#send").attr("disabled",(isEmailValid && isSubjectValid) ? "" : "disabled");
});
});
best way is to declare and initialize those variable globally and then use it ...and things which are being repeated in if condition place them in function and call it where you have to check those condition...
Try this:
$(document)
.ready(function () {
$("#send")
.attr("disabled", "disabled"), $("#validatemail")
.keyup(function () {
var a = $("#validatemail")
.val();
a != "" && isvalidmail(a)
}), $("#validatetitle")
.keyup(function () {
var a = $("#validatetitle")
.val();
a != "" && (3 > a.length || a.length > 30)
}), $("#form_message")
.live("keyup", function () {
var a = $("#validatemail")
.val(),
b = $("#validatetitle")
.val();
!isvalidmail(a) || 3 > b.length || b.length > 30 ? $("#send")
.attr("disabled", "disabled") : $("#send")
.removeAttr("disabled")
})
})

How can I fix this error "missing; before statement" in javascript?

How can I fix this error "missing; before statement" in javascript ?
My HTML Page :
http://etrokny.faressoft.com
My Javascript Code :
http://etrokny.faressoft.com/javascript.php
When assigning a function to a variable, you need a semicolon after the function.
Example: var func = function() { return false; };
Put a semicolon after all statements. JavaScript does it automatically for you when you "forget" one at the end of a line**, but since you used a tool to make everything fit on one line, this doesn't happen anymore.
** it should also be happening when a statement is followed by a }, but it's just bad practice to rely on it. I would always write all semicolons myself.
Actually, you know what, since it's so easy, I did it for you:
function getSelected() {
var selText;
var iframeWindow = window;
if (iframeWindow.getSelection) {
selText = iframeWindow.getSelection() + "";
} else if (iframeWindow.document.selection) {
selText = iframeWindow.document.selection.createRange().text;
}
selText = $.trim(selText);
if (selText != "") {
return selText;
} else {
return null;
}
}
$(document).ready(function () {
function scan_selectedText() {
if (getSelected() == null) {
return false;
}
if (getSelected().length < 25) {
return false;
}
$(document)[0].oncontextmenu = function () {
return false;
};
var result = true;
var selected_Text = getSelected();
selected_Text = selected_Text.replace(/ {2,}/g, ' ').replace(/\s{2,}/g, ' ');
$('#content .para').each(function () {
var accepted_text = $.trim($(this).text());
accepted_text = accepted_text.replace(/ {2,}/g, ' ').replace(/\s{2,}/g, ' ');
if (accepted_text.search(selected_Text) > -1) {
result = false;
}
});
var AllAccepted = "";
$('#content .para').each(function () {
var correntDiv = $.trim($(this).text()).replace(/ {2,}/g, ' ').replace(/\s{2,}/g, ' ');
AllAccepted = AllAccepted + correntDiv + " ";
});
if ($.trim(AllAccepted).search(selected_Text) > -1) {
return false;
}
if (!result) {
return false;
}
var body = $.trim($('body').text());
body = body.replace(/ {2,}/g, ' ').replace(/\s{2,}/g, ' ');
var bodyWithoutDivs = body;
$('#content').each(function () {
var correntDiv = new RegExp($.trim($(this).text()).replace(/ {2,}/g, ' ').replace(/\s{2,}/g, ' '), "");
bodyWithoutDivs = bodyWithoutDivs.replace(correntDiv, '');
});
if (bodyWithoutDivs.search(selected_Text) > -1) {
return false;
}
if (body == selected_Text) {
return true;
}
return true;
}
$(document).mousedown(function (key) {
if (key.button == 2) {
if (scan_selectedText() == true) {
$(document)[0].oncontextmenu = function () {
return false;
};
} else {
$(document)[0].oncontextmenu = function () {
return true;
};
}
}
});
var isCtrl = false;
$(document).keyup(function (e) {
if (e.which == 17) isCtrl = false;
}).keydown(function (e) {
if (e.which == 17) isCtrl = true;
if (e.which == 67 && isCtrl == true) {
$("#content2").animate({
opacity: 0
}, 500).animate({
opacity: 1
}, 500);
if (scan_selectedText() == true) {
return false;
} else {
return true;
}
}
});
document.onkeypress = function (evt) {
if (evt.ctrlKey == true && evt.keyCode == 67) {
$("#content2").animate({
opacity: 0
}, 500).animate({
opacity: 1
}, 500);
if (scan_selectedText() == true) {
return false;
} else {
return true;
}
}
};
$('*').bind('copy', function (key) {
if (scan_selectedText() == true) {
return false;
} else {
return true;
}
});
});
First thing, start with the raw human-written version of your javascript, you know, the unminimized non-machine-generated version
After you've fixed you've made sure it is free from syntax errors .... and you minimize it, don't make a mistake when copy/pasting

Categories