Put the validation error text below input field [closed] - javascript

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I don't really understand Javascript and I tried everything but can't find solution to my problem.
I'm using this plugin for validation, it works perfectly but just one small problem is that the error text it writes keeps displaying next to input field, I want it to show bellow the input field. Anyone can modify this script for that? Thank you very much :)
;(function($, window, document, undefined){
// our plugin constructor
var SimpleValidate = function(elem, options) {
this.elem = elem;
this.$elem = $(elem);
this.options = options;
this.metadata = this.$elem.data('plugin-options');
this.$requiredInputs = this.$elem.find(':input.required');
};
// the plugin prototype
SimpleValidate.prototype = {
defaults: {
errorClass: 'error',
errorText: 'Please fill out this field.',
emailErrorText: 'Please enter a valid E-mail',
errorElement: 'strong',
removeLabelChar: '*',
inputErrorClass: 'input-error',
completeCallback: '',
ajaxRequest: false
},
init: function() {
var self = this;
// Introduce defaults that can be extended either
// globally or using an object literal.
self.config = $.extend({}, self.defaults, self.options, self.metadata);
// What type of error message is it
self.errorMsgType = self.config.errorText.search(/{label}/);
self.emailErrorMsgType = self.config.emailErrorText.search(/{label}/);
self.$elem.on('submit.simpleValidate', $.proxy(self.handleSubmit, self));
return this;
},
checkField: function(index) {
var self = this;
var $field = self.$requiredInputs.eq(index);
var fieldValue = $.trim($field.val());
var labelText = $field.siblings('label').text().replace(self.config.removeLabelChar, '');
var errorMsg = '';
//Check if it's empty or an invalid email and format the error message
if(fieldValue === '') {
errorMsg = self.formatErrorMsg(self.config.errorText, labelText, self.errorMsgType);
self.hasError = true;
} else if($field.hasClass('email')) {
if(!(/^([_a-z0-9-]+)(\.[_a-z0-9-]+)*#([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/.test(fieldValue.toLowerCase()))) {
errorMsg = self.formatErrorMsg(self.config.emailErrorText, labelText, self.emailErrorMsgType);
self.hasError = true;
}
}
//If there is an error, display it
if(errorMsg !== '') {
$field.addClass(self.config.inputErrorClass).after('<' + self.config.errorElement + ' class="' + self.config.errorClass + '">' + errorMsg + '</' + self.config.errorElement + '>');
}
},
formatErrorMsg: function(errorText, labelText, errorMsgType) {
return (errorMsgType > -1 ) ? errorText.replace('{label}', labelText) : errorText;
},
handleSubmit: function(e) {
var self = this;
// We are just starting, so there are no errors yet
this.hasError = false;
// Reset existing displayed errors
self.$elem.find(self.config.errorElement + '.' + self.config.errorClass).remove();
self.$elem.find(':input.' + self.config.inputErrorClass).removeClass(self.config.inputErrorClass);
// Check each field
self.$requiredInputs.each($.proxy(self.checkField, self));
// Don't submit the form if there are errors
if(self.hasError) {
e.preventDefault();
} else if(self.config.completeCallback !== '') { // If there is a callback
self.config.completeCallback(self.$elem);
// If AJAX request
if(self.config.ajaxRequest) {
e.preventDefault();
}
}
}
};
SimpleValidate.defaults = SimpleValidate.prototype.defaults;
$.fn.simpleValidate = function(options) {
return this.each(function() {
new SimpleValidate(this, options).init();
});
};
})( jQuery, window , document );

Add this to your CSS:
.error { display: block; }
Or change ErrorElement to div.
new SimpleValidate(this, {errorElement: 'div'}).init();

just replace
$field.addClass(self.config.inputErrorClass).after('<' + self.config.errorElement + ' class="' + self.config.errorClass + '">' + errorMsg + '</' + self.config.errorElement + '>')
with:
$field.addClass(self.config.inputErrorClass).after('<p><' + self.config.errorElement + ' class="' + self.config.errorClass + '">' + errorMsg + '</' + self.config.errorElement + '></p>')

A simple solution might be to change errorElement: 'strong' to a block element, like errorElement: 'p'. You'll also want to make sure you style the elements properly with CSS.
If you'd like to learn JavaScript, I'd suggest taking a look at Eloquent JavaScript.

When you're calling this, just pass in the parameter : errorElement: 'p'. The default is to use strong, which is an inline element.

Unfortunately, I can not reproduce your code and therefore it is hard for me to say exactly what to do. However, it seems to me you should work around this piece of code:
$field.addClass(self.config.inputErrorClass).after('<' + self.config.errorElement + ' class="' + self.config.errorClass + '">' + errorMsg + '</' + self.config.errorElement + '>');
If I understood right, it adds the error message right after your input. Maybe you can use something like:
$field.addClass(self.config.inputErrorClass).after('<br>').after('<' + self.config.errorElement + ' class="' + self.config.errorClass + '">' + errorMsg + '</' + self.config.errorElement + '>');

Related

ContextMenuItem context function is not executing

I want my context menu item to be visible only if the clicked node is a link i.e. and href is either a magnet link or a torrent link. But item is visible for all the links because context function is not executing, can anybody help why context function is not executing?
Here is the code:
exports.main = function() {
var cm = require("sdk/context-menu");
var contextCode = ' self.on("context", function (node) { '+
' while(node.nodeName!="A") { node = node.parentNode; } '+
' var pat_magnet = /^magnet:/i; ' +
' var pat_torrent = /.torrent$/i; ' +
' if(pat_torrent.test(node.href) || pat_magnet.test(node.href)) { return true; } '+
' else { return false; } '+
' }); ';
var clickCode = ' self.on("click", function(node,data){ '+
' while(node.nodeName!="A") { node = node.parentNode; } '+
' var pat_hash = /[0-9abcdef]{32,40}/i; ' +
' var result = node.href.match(pat_hash); '+
' var hash = "" '
' if(result != null) { hash=result[0]; } '+
' var xhr = new XMLHttpRequest(); '+
' if(hash != "") { '+
' var apiCall = "https://www.furk.net/api/dl/add?api_key=*************&info_hash="+hash; '+
' } '+
' else{ '+
' var apiCall = "https://www.furk.net/api/dl/add?api_key=*************&url="+encodeURI(node.href); '+
' } '+
' xhr.open("GET",apiCall,true); '+
' xhr.onreadystatechange = function(){ if(xhr.readyState = 4) { if (xhr.response.status = "ok") { alert("Torrent added to Furk."); } else { alert("Torrent could not be added to Furk."); } } } '+
' xhr.send(null); '+
' });';
cm.Item({
label: "Add to Furk",
context: cm.SelectorContext("a[href]"),
contentScript: contextCode + clickCode
});
};
Please always post self-containied examples that can be directly tried in the future.
Now back to your problem: The content script actually has a syntax error.
The following line:
' var pat_torrent = /.torrent$/i ' +
lacks a semicolon, and should be:
' var pat_torrent = /.torrent$/i; ' +
The reason automatic semicolon insertion (ASI) does not work here is: The "code" is actually a string that has no newlines in it whatsoever. If there were newlines, then ASI would have worked.
Anway, another reason not to have complex content script inline. Have a look at contentScriptFile.
This error is actually logged, but the presentation sucks. In the Browser Console:
[20:57:51.707] [object Error] (expandable)
In terminal:
console.error: context-magnet:
Message: SyntaxError: missing ; before statement
Here is a fixed, reproducible sample:
var cm = require("sdk/context-menu");
var contextCode = ' self.on("context", function (node) { '+
' while(node.nodeName!="A") { node = node.parentNode; } '+
' var pat_magnet = /^magnet:/i; ' +
' var pat_torrent = /.torrent$/i; ' +
' if(pat_torrent.test(node.href) || pat_magnet.test(node.href)) { return true; } '+
' else { return false; } '+
' }); ';
cm.Item({
label: "magnet test",
context: cm.SelectorContext("a[href]"),
contentScript: contextCode
});
Edit ' var hash = "" ' has the same problem, and there are might be other such errors that I missed skimming this new code.
As I already said, please use contentScriptFile and not contentScript for long-ish scripts.
Another edit
Here is a builder using contentScriptFile, where I also fixed a couple of other errors, the most important of which are:
Use permissions so that the XHR will work.
Correctly set up the XHR to use responseType and overrideMimeType().
Use onload/onerror instead of onreadystatechange.

jQuery "Unexpected token ILLEGAL"

I have two functions, that are for showing and hiding elements by class:
if (typeof showClass != 'function') {
function showClass(trClass, buttonId, hideMessage, showMessage) {
var button = '#' + buttonId;
var value = hideMessage;
$(button).attr("value", value);
$(button).attr("onclick", "hideClass('" + trClass + "', '" + buttonId + "', '" + showMessage + "', '" + hideMessage + ");");
var classToShow = '.' + trClass;
$(classToShow).css('visibility', 'visible');
}
}
if (typeof hideClass != 'function') {
function hideClass(trClass, buttonId, showMessage, hideMessage) {
var button = '#' + buttonId;
var value = showMessage;
$(button).attr("value", value);
$(button).attr("onclick", "showClass('" + trClass + "', '" + buttonId + "', '" + hideMessage + "', '" + showMessage + ");");
var classToHide = '.' + trClass;
$(classToHide).css('visibility', 'hidden');
}
}
showClass works as excepted, but hideClass causes error "Unexpected token ILLEGAL" in Chrome. With FireFox I don't get any errors, but the function doesn't work with either of the browsers. I tried with different editors to find some illegal characters etc., but no luck. What could be the cause for this?
You're apparently trying to set up a toggling button, but it's the most convoluted mess of jQuery and inline event handlers I've ever seen.
Try this:
function setupToggle(trigger, target, hideMessage, showMessage) {
var state = false; // true means button says "show", target is hidden
var $el = $(trigger);
function update() {
$el.attr('value', state ? showMessage : hideMessage);
$(target).css('visibility', state ? 'hidden' : 'visible');
}
update(); // set initial state
$el.on('click', function() {
state = !state; // on click, flick state and refresh
update();
});
}
usage:
setupToggle('#mybutton', '.mytr', 'Hide it', 'Show it');
The code above may require minor tweaks depending on whether the default state is "hidden" or "shown".

Unable to get property of undefined or null reference

This is similar to my last question but the problem is different. I use a separate javascript file for all of my javascript functions. That file is called by my main window, and is also called in a separate instance by my child windows. My code works with every browser except IE 9 and 10. I have not tested earlier versions of IE.
IE says the offending line is window.opener.savetoparent($targetval); My previous code was opener.savetoparent($targetval); and before that I simply made the changes to the parent from the child directly. I have also gone into IE and enabled protected mode as suggested in another article with no change in behavior. Savetoparent() is available to both the child and the parent so I must call it with opener for it to run in the parent.
The error I am getting is : Unable to get property 'savetoparent' of undefined or null reference. Here is the code:
function saveandclose($wintype, $propid) {
switch($wintype) {
case 'ccdetail':
var $targetval = $('#cc-total').val();
var $fieldname = 'closingcoststotal';
break;
}
window.opener.savetoparent($targetval);
closewindow();
}
The safe to parent function is:
function savetoparent($targetval) {
$('#' + $parentloc).val($targetval);
var $name = $('#' + $parentloc).attr("name");
var $rawtargetval = jsstrtonum($targetval);
processrvsave($propertyid, $name, $rawtargetval);
calcrvtotals();
}
Any light you can shed on this would be greatly appreciated.
window is launched like this
if(window.showModalDialog) {
window.showModalDialog($childname + '.php?ploc=' + $parentloc + '&propid=' + $propid, '', 'dialogWidth: ' + $winwidth + 'px; dialogHeight: ' + $winheight + 'px;')
}
else {
window.open($childname + '.php?ploc=' + $parentloc + '&propid=' + $propid, '', 'width=' + $winwidth + ', height=' + $winheight + ', modal=yes');
}
There is no opener in showModalDialog. Use the returnValue
Also there has not been a modal parameter on window.open in many years..
Here is how to use returnValue
if(window.showModalDialog) {
$targetval = window.showModalDialog($childname + '.php?ploc=' + $parentloc + '&propid=' + $propid,
window,
'dialogWidth: ' + $winwidth + 'px; dialogHeight: ' + $winheight + 'px;'))
if(targetval) savetoparent($targetval);
}
else {
window.open($childname + '.php?ploc=' + $parentloc + '&propid=' + $propid, '', 'width=' + $winwidth + ', height=' + $winheight + ', modal=yes');
}
then
function saveandclose($wintype, $propid) {
var $targetval ="";
switch($wintype) {
case 'ccdetail':
$targetval = $('#cc-total').val();
// var $fieldname = 'closingcoststotal'; I do not see this used anywhere
break;
}
if (window.opener) window.opener.savetoparent($targetval);
else returnValue = $targetval;
closewindow();
}

Another jQuery autocomplete issue

So, i have read at least 20-30 auto complete problems here on so and i cannot find any solutions. For some odd reason i keep getting value = undefined. Here is my code.
//Cycles through each input and turns it into a person searcher.
$.each(settings.input, function() {
var input = $(this);
input.autocomplete({
delay: 70,
minLength: 2,
source: function(req, add) {
var val = input.val();
$.post(VUI.SITE_URL + "scripts/autocomplete/_AutoComplete.php", {q: val, display_count: settings.displayCount, action: "user"}, function(data) {
data = eval("(" + data + ")");
if (data.length > 0) {
var results = new Array(data.length);
$.each(data, function(key, value) {
results[key] = {desc: value, value: value.firstname + " " + value.lastname};
});
add(results);
} else {
add(["No results..."]);
}
});
},
select: function(event, ui) {
alert(ui.item ? ("Selected: " + ui.item.value + " aka " + ui.item.id) : "Nothing selected, input was " + this.value);
}
}) // end auto complete.
.data("autocomplete")._renderItem = function($ul, item) {
var $li = $("<li></li>"),
$inner = $("<div class='st-display side-content clearfix'style='padding-top:6px'></div>"),
$a = $("<a></a>"),
$img = $("<div class='image fl'></div>").html(ST.Image.getImage({
uid: item.desc.uid,
type: ST.ST_IMAGE_TYPE_THUMBNAIL_SMALL
})),
$content = $("<div class='content fl'></div>").html(
item.desc.firstname + " " + item.desc.lastname + "<br/>" +
"<span class='color:#979797;font-weight:bold'>" + item.desc.city + ", " + item.desc.state + "</span>"
);
$inner.append($img).append($content);
$a.append($inner);
$li.append($a);
$ul.append($li);
return $ul;
} // end _renderItem */
I tried to make it so that its very straight forward. But it wont work! (its facebook like auto complete). The auto complete displays properly (item does not equal undefined at that point), but when i highlight it, item becomes undefined so item.value (line 6347 of jquery.ui.1.8.13) throws exception!
Anyone see problems?
Here is something interesting... When i do not use data("autocomplete")._renderItem (for custom completion) the selecting works! ... So why does overriding the custom rendering cause issues? I am even returning the UL.
The only thing in your code that's different from a working version I've got of something very similar is that I initialise $li with:
var $li = $( '<li></li>' ).data('item.autocomplete', item);
That attaches the data to the list item which I think the autocomplete plugin uses to get the value at selection time.
Hope it helps

Jquery Scope Problems

function drawLabel(labelsIndex) {
// Check not deleted Label data:(DBID, text, styling, x, y, isDeleted)
if (!labelData[labelsIndex][5]) {
// Create
var newLabel = $('<div id="label' + labelsIndex + '" style="font-size:' + (labelData[labelsIndex][6] * currentScale) + 'px;z-index:9999;position:absolute;left:' + labelData[labelsIndex][3] + 'px;top:' + labelData[labelsIndex][4] + 'px;' + labelData[labelsIndex][2] + '">' + labelData[labelsIndex][1] + '</div>');
$('#thePage').append(newLabel);
// Click edit
$('#label' + labelsIndex).dblclick(function() {
if (!isDraggingMedia) {
var labelText = $('#label' + labelsIndex).html();
$('#label' + labelsIndex).html('<input type="text" id="labelTxtBox' + labelsIndex + '" value="' + labelText + '" />');
document.getElementById('#label' + labelsIndex).blur = (function(index) {
return function() {
var labelText = $('#labelTxtBox' + index).val();
$('#label' + index).html(labelText);
};
})(labelsIndex);
}
});
The code is meant to replace a div's text with a textbox, then when focus is lost, the textbox dissapears and the divs html becomes the textbox value.
Uncaught TypeError: Cannot set property 'blur' of null
$.draggable.start.isDraggingMediaresources.js:27
c.event.handlejquery1.4.4.js:63
I think I'm getting a tad confused with the scope, if anyone could give me some points I'd appreciate it. It would also be good if someone could show me how to remove the blur function after it has been executed (unbind?)
document.getElementById('#label' + labelsIndex).blur is a javascript function and less jquery :) therefore the # hash there is just irrelevant.
$('#label'+labelsIndex).bind('blur',function (){
//labelText value goes here //
});
EDIT
to be honest ur over complicating it :)
<div id="txt1">I am div</div>
<textarea id="txt2">I am text</textarea>
$('#edit_button').click(function (){
var val = $('#txt1').hide().html();// hide the div,then get value,
$('#txt2').show().val(val);//show txtarea then put value of div into it
});
Do the opposite for $('#save_button');

Categories