jQuery "Unexpected token ILLEGAL" - javascript

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".

Related

free-jqgrid populate drop down in subgrid

I am having a devil of a time populating a drop down list in a sub-grid. I am using free-jqgrid 4.15.5. I have no issues when populating a drop down in the main grid but it appears that I am having ID issues when trying to get a simular drop down in the subgrid ( grid as a subgrid option) dows anyone know a reference or how to populate the drop down correctly?
my current test function for the drop down is:
function popUsersT() {
alert("subgrid id : " + window.subgrid_id + "\nfound : " + $("#" + subgrid_id).length + "\nrow id : " + window.row_id + "\nfound(row) : " + $("#" + window.row_id).length + "\ndropdown found : " + $("select", "#" + window.row_id).length + "\nsg_tableID: " + $("#" + sg_tableID).html);
var current = $("#" + subgrid_id).jqGrid('getRowData', $("#" + window.subgrid_table_id )[0].p.selrow).TaskValidator;
alert(current);
$.ajax({
url: "/Tasks/getUserList",
datatype: 'json',
mtype: 'Get',
async: false,
success: function (users) {
$("#Task").html("");
$("#Proxy").html("");
$.each(users, function (i, user) {
$("#Task").append(
$('<option></option>').val(user.name).html(user.DisplayName)
);
$("#Proxy").append(
$('<option></option>').val(user.name).html(user.DisplayName)
);
});
$("#Task").prop("disabled", false);
$("#Proxy").prop("disabled", false);
$("#Task").val(current);
$("#Proxy").val(current);
}
});
}
part of my subgrid is:
subGridRowExpanded: function (subgrid_id, row_id) {
var sg_tableID = subgrid_id + "_t";
window.subgrid_id = sg_tableID;
window.row_id = row_id;
window.subgrid_table_id = sg_tableID;
//alert(subgrid_id);
//alert(row_id);
var pager_id = "p_" + sg_tableID;
$("#" + subgrid_id).html("<table id='" + sg_tableID + "' class='scroll'></table><div id='" + pager_id + "' class='scroll'></div>");
jQuery("#" + sg_tableID).jqGrid({
url: "/Home/GetTaskSubList/" + row_id,
I keep playing with the Id values to try to get away from the errors of:
Error: 'subgrid_table_id' is undefined
Error: 'sg_tableID' is undefined
I am sure i am getting lost in trying to make this work, and was hoping this was something easy i am over looking.
thank you for your help
in the end iw as able to get it workign by setting the values:
subGridRowExpanded: function (subgrid_id, row_id) {
var sg_tableID = subgrid_id + "_t";
window.subgrid_id = sg_tableID;
window.row_id = row_id;
window.subgrid_table_id = sg_tableID;
and then referencing the values in the function by:
var currentOwner = $("#" + subgrid_id).jqGrid('getRowData', $("#" + window.subgrid_table_id)[0].p.selrow).Task;
I am not sure i fully understand the why but it does seem to work as needed. thank you

Displaying information from a JSON on map using wrong method?

I'm working through a project to show information from a third party api on a map.
I'm not very experienced figuring out what the console is telling me so I'm a little stuck on the error I'm getting. I've declared all the variables outside of the function so result is defined and all of these functions are aspects of a foursquare venue.
Uncaught TypeError: Cannot read property 'hasOwnProperty' of undefined
$.ajax({
url:'https://api.foursquare.com/v2/venues/search',
dataType: 'json',
data: 'limit=1' +
'&ll='+ placeItem.lat() +','+ placeItem.lng() +
'&client_id='+ CLIENT_ID +
'&client_secret='+ CLIENT_SECRET +
'&v=20140806' +
'&m=foursquare',
async: true,
success: function (data) {
result = data.response.venue;
contact = result.hasOwnProperty('contact') ? result.contact : '';
if (contact.hasOwnProperty('formattedPhone')) {
placeItem.phone(contact.formattedPhone || '');
}
location = result.hasOwnProperty('location') ? result.location : '';
if (location.hasOwnProperty('address')) {
placeItem.address(location.address || '');
}
bestPhoto = result.hasOwnProperty('bestPhoto') ? result.bestPhoto : '';
if (bestPhoto.hasOwnProperty('prefix')) {
placeItem.photoPrefix(bestPhoto.prefix || '');
}
if (bestPhoto.hasOwnProperty('suffix')) {
placeItem.photoSuffix(bestPhoto.suffix || '');
}
description = result.hasOwnProperty('description') ? result.description : '';
placeItem.description(description || '');
rating = result.hasOwnProperty('rating') ? result.rating : '';
placeItem.rating(rating || 'none');
url = result.hasOwnProperty('url') ? result.url : '';
placeItem.url(url || '');
placeItem.canonicalUrl(result.canonicalUrl);
// Infowindow code is in the success function so that the error message
// Content of the infowindow
contentString = '<div id="iWindow"><h4>' + placeItem.name() + '</h4><div id="pic"><img src="' +
placeItem.photoPrefix() + '110x110' + placeItem.photoSuffix() +
'" alt="Image Location"></div><p>Information from Foursquare:</p><p>' +
placeItem.phone() + '</p><p>' + placeItem.address() + '</p><p>' +
placeItem.description() + '</p><p>Rating: ' + placeItem.rating() +
'</p><p><a href=' + placeItem.url() + '>' + placeItem.url() +
'</a></p><p><a target="_blank" href=' + placeItem.canonicalUrl() +
'>Foursquare Page</a></p><p><a target="_blank" href=https://www.google.com/maps/dir/Current+Location/' +
placeItem.lat() + ',' + placeItem.lng() + '>Directions</a></p></div>';
// Add infowindows
google.maps.event.addListener(placeItem.marker, 'click', function () {
infowindow.open(map, this);
// Bounce animation
placeItem.marker.setAnimation(google.maps.Animation.BOUNCE);
setTimeout(function () {
placeItem.marker.setAnimation(null);
}, 800);
infowindow.setContent(contentString);
});
},
// Alert the user on error.
error: function (e) {
infowindow.setContent('<h5>Foursquare data is unavailable.</h5>');
document.getElementById("error").innerHTML = "<h4>Foursquare data is unavailable. Please try refreshing.</h4>";
}
});
Not sure what data the call you are making is supposed to return but the error you are getting indicates that you did not get the data you were expecting.
result = data.response.venue;
"venue" is not a defined property of data.response so when you try and access result.hasOwnProperty('contact') it has no idea what to return since result is not defined.

Put the validation error text below input field [closed]

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 + '>');

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

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