How to Improve jquery function - javascript

I'm doing a validation and it's working fine, but I have so many repeat code and can´t find a way to improve it. Here is:
function validate( active ){
if( active[0].id === "mod_formSteps-1" ){
var $inputs = $("#formSteps-1 :input:not(:submit)");
var value = true;
$inputs.each(function() {
if( $(this).val().length < 1 || $(this).hasClass("error")){
value = false;
}
});
return value;
}
else if( active[0].id === "mod_formSteps-2" ){
var $inputs = $("#formSteps-2 :input:not(:submit)");
var value = true;
$inputs.each(function() {
if( $(this).val().length < 1 || $(this).hasClass("error")){
value = false;
}
});
return value;
}
...
...
else{
alert("something is wrong");
}
return true;
}
Now I have four if that are the same just change the paramater "mod_formStepsN" and "#formSteps-1".

Something more like this
function validate(active) {
var numb = active.prop('id').split('-').pop(),
inputs = $("#formSteps-"+numb+" :input:not(:submit)"),
value = true;
inputs.each(function () {
if ($(this).val().length < 1 || $(this).hasClass("error")) {
value = false;
}
});
return value;
}

Why not simply:
function validate( active ){
if(active[0].id != "")
{
var $inputs = $("#"+active[0].id+":input:not(:submit)");
var value = true;
$inputs.each(function() {
if( $(this).val().length < 1 || $(this).hasClass("error")){
value = false;
}
});
return value;
}
else{
alert("something is wrong");
}
return true;
}

Related

How to make multiple chunk of lines readonly in ace editor

I tried to make parts of code read-only in Ace editor.
I have tried by using code given in JsFiddle
$(function() {
var editor = ace.edit("editor1")
, session = editor.getSession()
, Range = require("ace/range").Range
, range = new Range(1, 4, 1, 10)
, markerId = session.addMarker(range, "readonly-highlight");
session.setMode("ace/mode/javascript");
editor.keyBinding.addKeyboardHandler({
handleKeyboard : function(data, hash, keyString, keyCode, event) {
if (hash === -1 || (keyCode <= 40 && keyCode >= 37)) return false;
if (intersects(range)) {
return {command:"null", passEvent:false};
}
}
});
before(editor, 'onPaste', preventReadonly);
before(editor, 'onCut', preventReadonly);
range.start = session.doc.createAnchor(range.start);
range.end = session.doc.createAnchor(range.end);
range.end.$insertRight = true;
function before(obj, method, wrapper) {
var orig = obj[method];
obj[method] = function() {
var args = Array.prototype.slice.call(arguments);
return wrapper.call(this, function(){
return orig.apply(obj, args);
}, args);
}
return obj[method];
}
function intersects(range) {
return editor.getSelectionRange().intersects(range);
}
function preventReadonly(next, args) {
if (intersects(range)) return;
next();
}
});
I got a problem when I keep pressing backspace it went into the read-only part and there was no editable part left.
How can I make multiple chunks of code read-only and avoid last character from read-only getting deleted.
Also, how to achieve the whole thing dynamically where I have markers in text specifying editable portions ?
Check the below code that allows multiple chunk of lines read-only with Enter at end of range to prevent non reversible delete and drag/drop handled.
function set_readonly(editor,readonly_ranges) {
var session = editor.getSession()
, Range = require("ace/range").Range;
ranges = [];
function before(obj, method, wrapper) {
var orig = obj[method];
obj[method] = function() {
var args = Array.prototype.slice.call(arguments);
return wrapper.call(this, function(){
return orig.apply(obj, args);
}, args);
}
return obj[method];
}
function intersects(range) {
return editor.getSelectionRange().intersects(range);
}
function intersectsRange(newRange) {
for (i=0;i<ranges.length;i++)
if(newRange.intersects(ranges[i]))
return true;
return false;
}
function preventReadonly(next, args) {
for(i=0;i<ranges.length;i++){if (intersects(ranges[i])) return;}
next();
}
function onEnd(position){
var row = position["row"],column=position["column"];
for (i=0;i<ranges.length;i++)
if(ranges[i].end["row"] == row && ranges[i].end["column"]==column)
return true;
return false;
}
function outSideRange(position){
var row = position["row"],column=position["column"];
for (i=0;i<ranges.length;i++){
if(ranges[i].start["row"]< row && ranges[i].end["row"]>row)
return false;
if(ranges[i].start["row"]==row && ranges[i].start["column"]<column){
if(ranges[i].end["row"] != row || ranges[i].end["column"]>column)
return false;
}
else if(ranges[i].end["row"] == row&&ranges[i].end["column"]>column){
return false;
}
}
return true;
}
for(i=0;i<readonly_ranges.length;i++){
ranges.push(new Range(...readonly_ranges[i]));
}
ranges.forEach(function(range){session.addMarker(range, "readonly-highlight");});
session.setMode("ace/mode/javascript");
editor.keyBinding.addKeyboardHandler({
handleKeyboard : function(data, hash, keyString, keyCode, event) {
if (Math.abs(keyCode) == 13 && onEnd(editor.getCursorPosition())){
return false;
}
if (hash === -1 || (keyCode <= 40 && keyCode >= 37)) return false;
for(i=0;i<ranges.length;i++){
if (intersects(ranges[i])) {
return {command:"null", passEvent:false};
}
}
}
});
before(editor, 'onPaste', preventReadonly);
before(editor, 'onCut', preventReadonly);
for(i=0;i<ranges.length;i++){
ranges[i].start = session.doc.createAnchor(ranges[i].start);
ranges[i].end = session.doc.createAnchor(ranges[i].end);
ranges[i].end.$insertRight = true;
}
var old$tryReplace = editor.$tryReplace;
editor.$tryReplace = function(range, replacement) {
return intersectsRange(range)?null:old$tryReplace.apply(this, arguments);
}
var session = editor.getSession();
var oldInsert = session.insert;
session.insert = function(position, text) {
return oldInsert.apply(this, [position, outSideRange(position)?text:""]);
}
var oldRemove = session.remove;
session.remove = function(range) {
return intersectsRange(range)?false:oldRemove.apply(this, arguments);
}
var oldMoveText = session.moveText;
session.moveText = function(fromRange, toPosition, copy) {
if (intersectsRange(fromRange) || !outSideRange(toPosition)) return fromRange;
return oldMoveText.apply(this, arguments);
}
}
function refresheditor(id,content,readonly) {
var temp_id=id+'_temp';
document.getElementById(id).innerHTML="<div id='"+temp_id+"'></div>";
document.getElementById(temp_id).innerHTML=content;
var editor = ace.edit(temp_id);
set_readonly(editor,readonly);
}
function get_readonly_by_editable_tag(id,content){
var text= content.split("\n");
var starts=[0],ends=[];
text.forEach(function(line,index){
if((line.indexOf("<editable>") !== -1))ends.push(index);
if((line.indexOf("</editable>") !== -1))starts.push(index+1);
});
ends.push(text.length);
var readonly_ranges=[];
for(i=0;i<starts.length;i++){
readonly_ranges.push([starts[i],0,ends[i],0])
}
refresheditor(id,content,readonly_ranges);
}
var content=document.getElementById("code").innerHTML;
function readonly_lines(id,content,line_numbers){
var readonly_ranges=[];
all_lines= line_numbers.sort();
for(i=0;i<line_numbers.length;i++){
readonly_ranges.push([line_numbers[i]-1,0,line_numbers[i],0]);
}
refresheditor(id,content,readonly_ranges);
}
get_readonly_by_editable_tag("myeditor",content)
//readonly_lines("myeditor",content,[5,7,9]);
.ace_editor {
width:100%;
height:300px;
}
.readonly-highlight{
background-color: red;
opacity: 0.2;
position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ace.c9.io/build/src/ace.js"></script>
<link rel="stylesheet" type="text/css" href="http://jsfiddle.net/css/normalize.css">
<link rel="stylesheet" type="text/css" href="http://jsfiddle.net/css/result-light.css">
<button onclick="get_readonly_by_editable_tag('myeditor',content)">Readonly by tags</button>
<button onclick="readonly_lines('myeditor',content,[3,7])">Readonly lines 3 and 7 </button>
<div id="myeditor" ></div>
<div id="code" style="display:none;">//<editable>
//</editable>
function refresheditor() {
//<editable>
document.getElementById("myeditor").innerHTML="<div id='editor'></div>";
document.getElementById("editor").innerHTML=document.getElementById("code").innerHTML;
//</editable>
var editor = ace.edit("editor")
, session = editor.getSession()
, Range = require("ace/range").Range;
ranges = [];
var text= document.getElementById("code").innerHTML.split("\n");
var starts=[0],ends=[];
text.forEach(function(line,index){
if((line.indexOf("&lt;editable&gt;") !== -1))ends.push(index);
if((line.indexOf("&lt;/editable&gt;") !== -1))starts.push(index+1);
});
ends.push(text.length);
for(i=0;i<starts.length;i++){
ranges.push(new Range(starts[i], 0,ends[i] ,0));
}
ranges.forEach(function(range){session.addMarker(range, "readonly-highlight");});
session.setMode("ace/mode/javascript");
//<editable>
editor.keyBinding.addKeyboardHandler({
handleKeyboard : function(data, hash, keyString, keyCode, event) {
var pos=editor.getCursorPosition();
if (Math.abs(keyCode) == 13){
for (i=0;i<ranges.length;i++){
if((ranges[i].end["row"]==pos["row"])&&(ranges[i].end["column"]==pos["column"])){ return false;}
}
}
if (hash === -1 || (keyCode <= 40 && keyCode >= 37)) return false;
for(i=0;i<ranges.length;i++){
if (intersects(ranges[i])) {
return {command:"null", passEvent:false};
}
}
}
});
//</editable>
before(editor, 'onPaste', preventReadonly);
before(editor, 'onCut', preventReadonly);
for(i=0;i<ranges.length;i++){
ranges[i].start = session.doc.createAnchor(ranges[i].start);
ranges[i].end = session.doc.createAnchor(ranges[i].end);
ranges[i].end.$insertRight = true;
}
function before(obj, method, wrapper) {
var orig = obj[method];
obj[method] = function() {
var args = Array.prototype.slice.call(arguments);
return wrapper.call(this, function(){
return orig.apply(obj, args);
}, args);
}
return obj[method];
}
function intersects(range) {
return editor.getSelectionRange().intersects(range);
}
function preventReadonly(next, args) {
for(i=0;i<ranges.length;i++){if (intersects(ranges[i])) return;}
next();
}
}
refresheditor();
</div>
This code snippet will prevent the user from editing the first or last line of the editor:
editor.commands.on("exec", function(e) {
var rowCol = editor.selection.getCursor();
if ((rowCol.row == 0) || ((rowCol.row + 1) == editor.session.getLength())) {
e.preventDefault();
e.stopPropagation();
}
});
https://jsfiddle.net/tripflex/y0huvc1b/
Source:
https://groups.google.com/forum/#!topic/ace-discuss/yffGsSG7GSA
sorry: this code does not handle drag/drop
I added this last proposal last week: Ace Editor: Lock or Readonly Code Segment

Only on Chrome I got this error: Uncaught TypeError: Illegal constructor [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
When I did load jQuery on Chrome I will receive this error: "Uncaught TypeError: Illegal constructor"
On rest browsers (IE, Mozilla) it's working fine. Here is couple screen shots from my PC. It's a same error.
(source: vaziuoju.lt)
Code:
$(Document).ready (function () {
$("p.warning").hide();
$( "#newAdsForm" ).submit(function( event ) {
var vailidEmail = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
var vardas = $("#vardas").val(); var vardasTest = false;
var vardas = vardas.replace(/<(?:.|\n)*?>/gm, '');
var pastas = $("#pastas").val(); var pastasTest = false;
var phone = $("#phone").val(); var phoneTest = false;
var kada = $("#inputField").val(); var kadaTest = false;
var kaina = $("#kaina").val(); var kainaTest = false;
var kaina = kaina.replace(/<(?:.|\n)*?>/gm, '');
var skelbimas = $("#skelbimas").val(); var skelbimasTest = false;
var skelbimas = skelbimas.replace(/<(?:.|\n)*?>/gm, '');
if (vardas == "") {
$("p#vardas").fadeOut("fast", function () {
$("p#vardas").text ("Vardas būtinas!");
});
$("p#vardas").fadeIn("fast");
vardasTest = false;
} else {
$("p#vardas").fadeOut("fast");
vardasTest = true;
}
if (pastas == "") {
$("p#pastas").fadeOut("fast", function () {
$("p#pastas").text ("El. paštas būtinas!");
});
$("p#pastas").fadeIn("fast");
pastasTest = false;
} else if (!pastas.match(vailidEmail)) {
$("p#pastas").fadeOut("fast", function () {
$("p#pastas").text("Negaliojantis pašto adresas!");
});
$("p#pastas").fadeIn("fast");
pastasTest = false;
} else {
$("p#pastas").fadeOut("fast");
pastasTest = true;
}
if (phone == "") {
$("p#phone").fadeOut("fast", function () {
$("p#phone").text ("Telefono numeris būtinas!");
});
$("p#phone").fadeIn("fast");
phoneTest = false;
}
else if (!phone.match(/^[0-9-+]+$/)) {
$("p#phone").fadeOut("fast", function () {
$("p#phone").text ("Neteisingas Telefono numeris!");
});
$("p#phone").fadeIn("fast");
phoneTest = false;
} else {
$("p#phone").fadeOut("fast");
phoneTest = true;
}
var comp = kada.split('-');
if ((comp[0].length != 4) || (comp[1].length != 2) || (comp[2].length != 2) || (kada.length != 10)) {
$("p#kada").fadeOut("fast", function () {
$("p#kada").text ("Blogai nurodyta data!");
});
$("p#kada").fadeIn("fast");
kadaTest = false;
} else if ((!comp[0].match(/^\d+$/)) || (!comp[1].match(/^\d+$/)) || (!comp[2].match(/^\d+$/))) {
$("p#kada").fadeOut("fast", function () {
$("p#kada").text ("Blogai nurodyta data2!");
});
$("p#kada").fadeIn("fast");
kadaTest = false;
} else {
$("p#kada").fadeOut("fast");
kadaTest = true;
}
if (kaina.length != 0) {
var number = /^\-{0,1}(?:[0-9]+){0,1}(?:\.[0-9]+){0,1}$/i;
var regex = RegExp(number);
if (!regex.test(input) && input.length>0) {
$("p#kaina").fadeOut("fast", function () {
$("p#kaina").text ("Neteisinga kaina!");
});
$("p#kaina").fadeIn("fast");
kainaTest = false;
} else {
$("p#kaina").fadeOut("fast");
kainaTest = true;
}
} else {
$("p#kaina").fadeOut("fast");
kainaTest = true;
}
if (vardasTest && pastasTest && phoneTest && kadaTest && kainaTest) return true;
else return false;
});
});
Part of HTML code
<tr><td>Vardas</td><td><input type = "text" class = "newAdd" name = "vardas" id = "vardas" <?php if (isset($_SESSION ['vardas'])) echo "value = '".$_SESSION ['vardas']; ?>'/><p class = "warning" id = "vardas">Vardas būtinas!</p></td></tr>
Any ideas how I can fix it?
You should try it with a lowercase
"d"
$(document).ready(function(){...
javascript is case-sensitive once a variable is set

How to access the JQuery object

How do I access the jquery object when validateName is called?
In my code below, errorDate is not a JQuery object.
Correction to variable name
$(document).ready(function() {
var errorDate = $("#errorDate");
errorDate.blur(validateName);
function validateName() {
if (errorDate.val().length == "") {
errorDate.addClass("error");
return false;
}
else {
errorDate.removeClass("error");
return true;
}
}
});
Just use $(this) instead of name.
You can
$(document).ready(function() {
var errorDate = $("#errorDate");
errorDate.blur(validateName);
function validateName() {
var $this = $(this);
if ($this.val().length == "") {
$this.addClass("error");
return false;
}
else {
$this.removeClass("error");
return true;
}
}
});
Or use errorDate instead of name since it is a closure variable
$(document).ready(function() {
var errorDate = $("#errorDate");
errorDate.blur(validateName);
function validateName() {
if (errorDate.val().length == "") {
errorDate.addClass("error");
return false;
}
else {
errorDate.removeClass("error");
return true;
}
}
});
Try this,
$(document).ready(function() {
var errorDate = $("#errorDate");
errorDate.blur(validateName);
function validateName() {
// no need to get length you can use $(this).val()==""
if ($(this).val() == "") {
$(this).addClass("error");
return false;
}
else {
$(this).removeClass("error");
return true;
}
}
});
Fiddle http://jsfiddle.net/jtWFX/

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