- Screen name: justinhyland
justinhyland's Profile
17 Posts
35 Responses
0
Followers
Show:
- Expanded view
- List view
Private Message
I plan on starting my next project soon, which I'm planning on using ReactJS, which I'm very new to. I know React uses a virtual DOM, and I've heard some things regarding issues with React and jQuery plugins, since jQuery plays entirely in the DOM.
Im basically converting a project that currently exists as PHP(CI)/MySQL/jQuery, to NodeJS/ReactJS/jQuery/(some DB here).
So pretty much, the only part of the existing project I plan on keeping, is the jQuery code, which is a LOT of code, and a few custom plugins.
I was wondering if anyone here has experience creating a jQuery heavy ReactJS application? And if so, what issues did you run into?
Ive found a lot of different answers via Google, so I thought id just ask someone here directly.
- 23-Nov-2015 12:17 AM
- Forum: Using jQuery
I'm having some issues getting a class method to fire when events are triggered.Basically, for buttons #1 and #2, you get the alert, but the _selector property is undefined, so obviously the event triggers fine, but it cant see the _selector property..But for button #3, all thats really changed, is the btnThree.eventHandler(); gets executed from within an anonymous function... But it works just fine.Any ideas? I'm sure it's something simple.- I just decided to use OOP in a project I'm working on. And I had a basic question about reaching properties in the root of the prototype from functions that lie within objects.Heres a JSFiddle: http://jsfiddle.net/454onwr3/1/ (Open console)Heres the jQuery:
- var Person = function(first, last){
- this._first = first;
- this._last = last;
- };
-
- Person.prototype = {
- full: function(){
- return this._first +' '+this._last;
- },
- first: function( ){
- return this._first;
- },
- last: function(){
- return this._last;
- },
- hobbies: {
- computers: {
- init: function(){
- console.debug(this._first +' '+this._last + ' likes Computers');
- }
- },
- cars: {
- init: function(){
- console.debug(this._first +' '+this._last + ' likes Cars');
- }
- }
- }
- };
-
- var p1 = new Person('John','Doe');
- p1.hobbies.computers.init();
-
- var p2 = new Person('Jack','Black');
- p2.hobbies.cars.init();
Basically, if I wanted to call elements deeper within the object than just the first level, how can I reach properties stored in the root? Those console outputs should say "John Doe likes Computers" and "Jack Black likes Cars". Ive been reading a few jQuery OOP Articles, mainly this one and this one.Thanks!- 05-Nov-2015 01:20 PM
- Forum: Using jQuery
Im trying to fire off an event of an element, but I need to target the element by only knowing the ID or class of an element thats 2 levels down.Example: If the DOM src is:- <table>
- <tr /* Target THIS */>
- <td>
- <span id="test">Click me</span>
- </td>
- </tr>
- </table>
Then I would want to target the <tr> element by only knowing the span#test element..Heres some stuff i've been trying, obviously none of it works..Any help would be appreciated! Thanks- 24-Oct-2015 09:29 PM
- Forum: Using jQuery
I know that JS can't do reference variables like PHP (my native language), but theres gotta be some way to accomplish something similar to it, without using a global variable.In my code, I have a function that initiates a DataTables instance (And this has nothing to do with DataTables, btw), and when DT is initiated, it launches a function that will monitor the data source of the table, and when anythings changed, it will reload the DT instance. This function that monitors the data source can be used many times.What I'm trying to do is find a way to pause the loop that watches the data source in the second function, from the initial function. My thought right now is that maybe theres a way to pass a closure as the parameter to second function, thats defined in the first function, which will accept a local variable (local to the 2nd function) that it will toggle, which controls the loop.. Not sure thats clear enough, hope so. Kinda hard to explainJSfiddle example: http://jsfiddle.net/uatvzm44/3/If anyone has any ideas, that would be great! thanks- I have a web app thats getting much bigger than expected, and it has quite a few JS files. I was looking for a way to load them quicker, and preferably asynchronous and with dependencies, meaning don't load them ALL at once, but load the ones that don't have dependencies (but ARE dependencies) first, then if they are loaded fine, load the ones dependent on them, etc etc.I looked into HeadJS (HJS) and RequireJS (RJS), and I had a few questions about both.I first started to use HJS, and it looks like I got it working fine, but I'm just not sure I'm doing it right, if someone can verify, that would be cool, code here: http://pastebin.com/RCjpUKUSSo, first off... loading CSS asynchronous and with dependencies just like it can with JavaScript would be a huge plus, and I know HJS says it can do that, and I notice RJS says it cant, because its "not possible" to do it properly. So that means that either the developers of HJS knows something that the devs of RJS don't, or that the devs of HJS settled for something sloppy.. which would you say it is? (Granted, the sources that say its not possible are over 8 years old, but theres nothing more recent to debunk that)After I used HJS a bit, I looked into RJS, and it looks a hell of a lot more powerful than HJS. So I thought about implementing it into my existing project. But as I started to look at some tutorials (primarily this one), I kinda got the feeling that its not really something you can just throw existing code into, or just tell it to load specific files in order with dependencies, it looks like it kinda forces you to code your JS into a specific paradigm that they require for you to use their model.. Is that the case? Or am I just looking at it incorrectly.
- I was looking for some users that have experience with the jQuery plugin head.js .According to the website, head.js allows you to setup js/css file dependencies and load js files asyncronously and in parallel.Looking at the API documentation and examples, I see that you can apply labels to JS files, then run some conditions when they are loaded, heres an example in their documentation:
-
// same as above, but pass files in as an Array
head.load([
{ label1: "file1.js" },
{ label2: "file2.js" }],
function() {
// do something
});
// Labels are usually used in conjuntion with: head.ready()
head.ready("label1", function() {
// do something
});
So basically, that will execute anything in the 2nd block of code (inside the closure), when the file1.js is loaded.What I wanted to do, is load more files (asyncronously) when other files are loaded..For example..First, load the jquery file- jquery.min.js
Then once thats done, load the datatables files that are dependent on jquery (asyncronously)- dataTables.searchHighlight.min.js
- dataTables.conditionalPaging.js
- ellipsis.js
- jquery.dataTables.yadcf.js
Then once thats done, load the app files that are dependent on DataTables files- myapp_core.js
- myapp_whatever.js
How would I do this with Head.js? The documentation isnt super clear. the head.ready() looks at one file/label to make sure it loaded successfully, how would you do multiple?And to have others load after that one is done, would you just put another head.load() inside the closure statement inside the head.ready()?- Im creating an app that users can create plugins for in both PHP and jQuery. I had 2 questions about the jQuery plugin setup. Im using an observable design pattern I found online, somewhere on the jQuery site actually. Heres the code thus far:The Observer:
-
/**
* @see https://api.jquery.com/jQuery.Callbacks/
* @see http://addyosmani.com/resources/essentialjsdesignpatterns/book/#highlighter_506612
*/
;(function($) {
var topics = [];
function getTopic(id) {
var callbacks;
topic = id && topics[id];
if (!topic) {
callbacks = $.Callbacks();
topic = {
publish: callbacks.fire,
subscribe: callbacks.add,
unsubscribe: callbacks.remove
};
if (id) topics[id] = topic;
}
return topic;
}
$.observer = {
publish: function(id) {
var args = (2 <= arguments.length) ? Array.prototype.slice.call(arguments, 1) : [];
var t = getTopic(id);
return t.publish.apply(t, args);
},
subscribe: function(id, fn) {
return getTopic(id).subscribe(fn);
},
unsubscribe: function(id, fn) {
return getTopic(id).unsubscribe(fn);
}
};
})(jQuery);
Creating Observable Object-
var $assets_dt = $assets_table.DataTable( {
createdRow: function ( row, data, index ) {
app.observable('assets.datatable.createrow', row, data, index);
}
} );
Example Usage:-
/**
* Color Tables functionality
*/
color_tables = {
/**
* Criteria
*
* Rules of what colors to set for what columns
*
* @todo Allow regex and the ability to apply something that allows the user to specify when a cell ISNT a value
*/
criteria: function() {
var partition_id = $( '#data-table' ).data( 'partition-id' );
var criteria = $.ajax( {
type: "GET",
url: '....smart_color.criteria.json',
async: false,
dataType: 'json'
} ).responseText;
var criteria_json = $.parseJSON(criteria);
return criteria_json[ partition_id ] || false;
},
/**
* Create Row
*
* Executes whenever the DataTables plugin initiates the tables and the rows are created (via JS, not PHP)
*
* @param row
* @param data
* @param index
*/
create_row: function( row, data, index ) {
var rules = color_tables.criteria();
var highlight_rules = [];
var i, add, classes;
if(rules) {
// Duplicate the rules array except the keys will be the column indexes in the table
$.each( rules, function ( col, r ) {
i = $( 'th#column-' + col ).index();
highlight_rules[ i ] = r;
} );
//console.log('highlight rules: ', highlight_rules);
$.each( data, function ( k, d ) {
if ( k in highlight_rules ) {
if ( $.isArray( highlight_rules[ k ].criteria ) ) {
$.each( highlight_rules[ k ].criteria, function ( sk, ss ) {
if ( data[ k ].match( new RegExp( ss ) ) ) {
//$( 'td', row ).eq( k ).addClass( highlight_rules[k].class );
if ( $.isArray( highlight_rules[ k ].classes ) ) {
classes = highlight_rules[ k ].classes.join( ' ' );
}
else {
classes = highlight_rules[ k ].classes;
}
$( 'td', row ).eq( k ).addClass( classes );
}
} );
}
else {
if ( data[ k ].match( new RegExp( highlight_rules[ k ].criteria ) ) ) {
//$( 'td', row ).eq( k ).addClass( highlight_rules[k].classes );
if ( $.isArray( highlight_rules[ k ].classes ) ) {
classes = highlight_rules[ k ].classes.join( ' ' );
}
else {
classes = highlight_rules[ k ].classes;
}
$( 'td', row ).eq( k ).addClass( classes );
}
}
}
} );
}
}
};
// The initial assets table initiation
$.observer.subscribe('assets.datatable.createrow', color_tables.create_row);
So that works decently well, I have 2 questions though...- Is there a way to set this up so the observable functions can rather filter the data? Meaning if I wanted to create a plugin to do something basic like convert the username logged in to uppsercase, just run the username through a filter, and any plugins can filter out the data, but if no plugins are setup, just pass the data on as is
- As opposed to using the above method for plugins, should I just use custom events? Example: https://learn.jquery.com/events/introduction-to-custom-events/
Thanks!- 29-Aug-2015 03:50 PM
- Forum: Getting Started
I have a script on my site that will set the window.onbeforeunload whenever an input is changed, and when the form is submitted, disable the alert, and submit the form.Current JS:-
// If any inputs are changed, enable the alert if they change pages (Unless its a .trivial form)
// Wait til the page is fully loaded to do so, since some inputs are changed via JS
$(window ).load(function(){
$('form:not(.trivial)').find( 'input, :checkbox, :radio, textarea' ).change( function (){
template.nav_alert(true);
});
});
// When the bwizard form is submitted, disable the nav alert
$('form[name="form-wizard"]').submit(function(){
template.nav_alert(false);
});
template = {
nav_alert: function ( status ) {
"use strict";
if ( status === true ) {
window.onbeforeunload = function () {
return 'Are you sure you want to leave? All changes you have made will be lost';
};
} else {
window.onbeforeunload = null;
}
}
}
What I want to do though, is kinda implement my own onBeforeUnload feature, since the regular prompt is just ugly. Somewhat like Facebooks alert when you are commenting on something or adding a wall post, and try to navigate away, it will show a nice prompt.Is there a way to basically watch if the window is going to navigate in any way? Whether it be just a HREF link, or JS onClick, or even a jQuery $('#this-item').click(){ redirectFunction(); }).. I mean anything.I know I could do something like $('a').click(), but some redirects are done when classes or ID's are clicked, etc etc.Also, how do I have a function continue with the default action after temporarily disabling it? Heres a small mock up script I created..-
$(window).load(function(){
$( 'a' ).click(function(e){
e.preventDefault();
new Messi('Are you sure you want to navigate away?', {
title: 'Navigate',
buttons: [
{
id: 1,
label: 'Continue',
val: 'continue',
class: 'btn-success'
},
{
id: 2,
label: 'Cancel',
val: 'cancel',
class: 'btn-close'
}
],
modal: true,
callback: function(val) {
if(val === 'continue'){
// How to continue with the default action? Whether
// its just an anchor link, an onClick attr, or even
// something specified in JS
}
else if(val === 'cancel'){
// Dont do anything
}
}
});
});
});
So I cant just return true or false in a Messi callback, because that will pertain to the messi callback, not the parent function.Anyhelp would be great! Thanks- I have a table on an app that im creating (DataTables currently), and as you can see below, its rather packed with columns, and unfortunately, all of them are necessary.
I wanted to hide the three left columns, Delete/Visibility/Primary, to make more space on the table. But theya re still needed, so I was thinking maybe make it so when you hover over the row, it shows the 3 options to the left of it, making it look like the row is extended or something.
Does anyone know how I could do that? Just add a div or span or something to the left of the row that shows only on hover, and make it the exact hight and position of the row?
Thanks for any help!
- I have a JS script that will execute an ajax check every X seconds for new content and if any is found, it will prepend it to the top of a timeline. I wanted to get an effect of it sliding down the other content of the timeline, Heres the script thus far:
-
$.get( '/some/url', function ( items ) {
// Error: Uncaught TypeError: Failed to execute 'getComputedStyle' on 'Window': parameter 1 is not of type 'Element'.
$( items ).hide().prependTo( ".timeline" ).slideDown();
// This works fine, just doesn't slide
//$( items ).prependTo( ".timeline" );
} );
So the error is the line with the prependTo, it throws the error:Error: Uncaught TypeError: Failed to execute 'getComputedStyle' on 'Window': parameter 1 is not of type 'Element'.The weird part is it worked fine a while ago, I just made so many changes/commits,that I'm not at all sure what caused it to stop workingAny help would be great! Thanks.- I have a timeline on my application that will load more items via AJAX as you scroll closer to the bottom, it works great, I just think that the scrolling is a little jerky, it seems to jump around when it loads the item. The scroll will jump to the half of the scroll bar then back down to the bottom. Does anyone have any idea how to make that a bit smoother?Code:
-
var scroll_threshold = 25;
var total_items = 123;
var loading = false;
var $items_loading = $('#loading-items');
var $timeline_id = $('#timeline');
var $timeline_class = $('.timeline');
var asset_id = [12,34,56];
var timestamp = '1438621944';
var limit = 5;
// Detect page scroll
$(window).scroll(function() {
// Load items if were $scroll_threshold from the bottom
if($(window).scrollTop()+$(window).height() > $(document).height()-scroll_threshold) {
// Check if theres data to load
if($timeline_id.find('li').length < total_items && loading === false) {
//prevent further ajax loading
loading = true;
//show loading image
$('#loading-items').show();
//load data from the server using a HTTP POST request
$.get('/assets/view_timeline/asset_id/' + asset_id.join('/asset_id/') + '/timestamp/'+timestamp+'/limit/'+limit, function(items){
// Append received data into the element
$timeline_class.append(items);
//hide loading image
$items_loading.hide();
// Last Loaded Timestamp
timestamp = $timeline_id.find('li:last-child').data('timestamp');
loading = false;
}).fail(function(xhr, ajaxOptions, thrownError) { //any errors?
template.alert('Timeline Error', 'Error loading timeline items: ' + thrownError, 'error');
//hide loading image
$items_loading.hide();
loading = false;
});
}
}
});
- I have a timeline on my website, and it gets live updates via AJAX calls, and it prepends any new timeline items to the top of the list.Error in console:
Error: Uncaught TypeError: Failed to execute 'getComputedStyle' on 'Window': parameter 1 is not of type 'Element'.
Heres the exact JS code for the timeline:-
// Timestamp of latest item
var first_timestamp = $timeline_class.find('li').eq(0).data('timestamp');
var $timeline_class = $('#timeline');
var scroll_at_top = '30';
var asset_id = [12,34,56];
// Check for any new items
setInterval(function() {
if( window.location.hash.substring( 1 ) !== 'no-live' ) {
// If the first timeline hasnt loaded yet, load it
if ( typeof first_timestamp === 'undefined' ) {
first_timestamp = $timeline_class.find( 'li' ).eq( 0 ).data( 'timestamp' );
}
// Only load more data if were somewhere near the top of the page
else if ( $( window ).scrollTop() < scroll_at_top ) {
loading = true;
$.get( '/assets/view_new_timeline/asset_id/' + asset_id.join( '/asset_id/' ) + '/timestamp/' + first_timestamp, function ( items ) {
// If new items were found
if ( items ) {
console.log(items);
// @todo This seems to cause a JS error (which is weird, it worked fine before)
// Error: Uncaught TypeError: Failed to execute 'getComputedStyle' on 'Window': parameter 1 is not of type 'Element'.
$( items ).hide().prependTo( ".timeline" ).slideDown();
// This works just fine though
//$( items ).prependTo( ".timeline" );
first_timestamp = $timeline_class.find( 'li' ).eq( 0 ).data( 'timestamp' );
fade_icons();
}
loading = false;
} ).fail( function ( xhr, ajaxOptions, thrownError ) { //any errors?
template.alert( 'Timeline Error', 'Error loading timeline items: ' + thrownError, 'error' );
//hide loading image
$items_loading.hide();
loading = false;
} );
}
}
}, recheck_interval*1000);
And incase anyone needs the HTML code of the AJAX response, here it is (Exact)-
<!-- being timeline-item -->
<li data-timestamp="1438620849" class="timeline-item timeline-action-updated">
<!-- begin timeline-time -->
<div class="timeline-time">
<span class="date">
August 3, 2015 </span>
<span class="time">
9:54 am </span>
</div>
<!-- end timeline-time -->
<!-- begin timeline-icon -->
<div class="timeline-icon" data-type="error">
<a name="1438620849">
<i class="fa fa-exclamation m-r-2"></i><i class="fa fa-cogs m-l-2"></i> </a>
</div>
<!-- end timeline-icon -->
<!-- begin timeline-body -->
<div class="timeline-body">
<div class="timeline-header">
<!--<span class="userimage"><img src="http://www.gravatar.com/avatar/bd61d9d0c53c648ef33e1f6ec0618cae?s=100" /></span>-->
<span class="username">
<a href="/assets/details/17">wq00-azzz-m01.sasset.ad</a>
</span>
<span class="timeline-fadein">
updated </span>
<span class="pull-right text-muted">
<a href="/account/details/1">
<div class="image user-avatar"></div>
</a>
</span>
<span class="pull-right timeline-username timeline-fadein">
Demoadmin </span>
</div>
<div class="timeline-content">
<pre>Array
(
[error] => Value 'asfdasdf' does not follow the format required for attribute 'Server Name'
)
</pre>
</div>
<div class="timeline-footer p-b-30">
<span class="float-left">
Mon Aug 3 9:54:09 MST 2015 </span>
<span class="float-right timeline-fadein">
<a href="/assets/details/17" class="m-l-8 ttip no-underline" data-tooltip-title="View details for this asset">
<i class="fa fa-info-circle fa-lg"></i>
</a>
<a href="/assets/timeline/17" class="m-l-8 ttip no-underline" data-tooltip-title="Timeline for this asset">
<i class="fa fa-clock-o fa-lg"></i>
</a>
<a href="/assets/edit/17" class="m-l-8 ttip no-underline" data-tooltip-title="Edit this asset">
<i class="fa fa-edit fa-lg"></i>
</a>
</span>
</div>
</div>
<!-- end timeline-body -->
</li>
<!-- end timeline-item -->
- I may have one of the weirdest problems I have ever had. I have a portion of script (included below), which gets executed when the page loads. As far as I can tell, this function only gets called once, the weird part though, is the entire function executes twice.... I debugged it as much as I can. When I comment out the line where I call it (once), it doesnt get executed at all, when I uncomment it, it gets executed twice...I dont see anywhere in the function where it executes itself, and if it did, I would think it would do it more than twice.ANY help would be great.Heres the small portion where it gets executed:
-
<script>
forms.sidebar_search();
</script>
And again, somehow that executes the sidebar_search() twice, but when I comment out that one single line, it wont get executed at all.And heres the function itself.-
sidebar_search: function() {
// Hide/Show the sidebar when the menu is collapsed
$('[data-click=sidebar-minify]').click(function(e) {
forms.sidebar_search_visibility();
});
// Make API call to get quick search setting
var quick_search_api = $.ajax({
type: "GET",
url: '/REST/app/setting/config/my_site/name/asset_quicksearch',
async: false,
dataType: 'json'
}).responseText;
console.log("RES: " + quick_search_api);
var quick_search = $.parseJSON( quick_search_api );
// Check if the quick search is enabled
if(quick_search.asset_quicksearch === true) {
// Query for all primary values of current partition
var result = $.ajax( {
type: "GET",
url: '/REST/partition/primary_attribute_values',
async: false,
dataType: 'json'
} ).responseText;
var primary_attribute = $.parseJSON( result );
// Populate the search field if values are set
if ( primary_attribute.values ) {
//$('#sidebar-search-container' ).removeClass('display-none' ).addClass('display-block');
$( '#sidebar-search-container' ).fadeIn( 'slow' );
$( '#sidebar-search' ).autocomplete( {
source: primary_attribute.values
} );
// Submit action
var do_submit = function () {
var search_val = $( '#sidebar-search' ).val();
if( $.trim(search_val) !== '') {
$( location ).attr( 'href', '/assets/search/' + primary_attribute.column + '/' + search_val );
}
};
// On enter
$( '#sidebar-search-form' ).submit( function ( e ) {
e.preventDefault();
do_submit();
} );
// On the button click
$( '#sidebar-search-form-button' ).click( function ( e ) {
e.preventDefault();
do_submit();
} );
} else {
console.log( 'No primary attribute for partition, hiding Quick Asset Search' );
//$('#sidebar-search-container' ).removeClass('display-block' ).addClass('display-none');
$( '#sidebar-search-container' ).fadeOut( 'slow' );
}
}
}
Thanks in advance for any help!- Hey guys, so im working on a JS script that basically just takes an ID and value, then disables/enables a bunch of inputs depending on the value type (using a switch statement), then executes another function doing something similar. It works fine, just really ugly. I figured theres gotta be a better way to do it...Heres the code, let me know if you guys have any ideas!
-
syncAttributeSettings(1, 'string');
syncAttributeSettings(2, 'text');
syncAttributeSettings(3, 'select');
syncAttributeSettings(4, 'multiselect');
syncAttributeSettings(5, 'boolean');
var syncAttributeSettings = function(row_id, value){
switch(value){
case 'string':
$('#placeholder-' + row_id).removeAttr('readonly');
$('#primary-' + row_id).removeAttr('readonly');
$('#unique-' + row_id).removeAttr('readonly');
$('#regex-' + row_id).removeAttr('readonly');
$('#min-' + row_id).removeAttr('readonly');
$('#max-' + row_id).removeAttr('readonly');
break;
case 'text':
$('#placeholder-' + row_id).removeAttr('readonly');
$('#primary-' + row_id).removeAttr('readonly');
$('#unique-' + row_id).removeAttr('readonly');
$('#regex-' + row_id).removeAttr('readonly');
$('#min-' + row_id).removeAttr('readonly');
$('#max-' + row_id).removeAttr('readonly');
break;
case 'select':
$('#placeholder-' + row_id).attr('readonly','readonly');
$('#primary-' + row_id).attr('readonly','readonly');
$('#primary-' + row_id).prop('checked', false);
$('#unique-' + row_id).removeAttr('readonly');
$('#regex-' + row_id).attr('readonly','readonly');
$('#regex-' + row_id).val('');
$('#min-' + row_id).attr('readonly','readonly');
$('#min-' + row_id).val('');
$('#max-' + row_id).attr('readonly','readonly');
$('#max-' + row_id).val('');
break;
case 'multiselect':
$('#placeholder-' + row_id).attr('readonly','readonly');
$('#primary-' + row_id).attr('readonly','readonly');
$('#primary-' + row_id).prop('checked', false);
$('#unique-' + row_id).removeAttr('readonly');
$('#regex-' + row_id).attr('readonly','readonly');
$('#regex-' + row_id).val('');
$('#min-' + row_id).removeAttr('readonly');
$('#max-' + row_id).removeAttr('readonly');
break;
case 'boolean':
$('#placeholder-' + row_id).attr('readonly','readonly');
$('#primary-' + row_id).attr('readonly','readonly');
$('#primary-' + row_id).prop('checked', false);
$('#unique-' + row_id).attr('readonly','readonly');
$('#unique-' + row_id).prop('checked', false);
$('#regex-' + row_id).attr('readonly','readonly');
$('#regex-' + row_id).val('');
$('#min-' + row_id).attr('readonly','readonly');
$('#min-' + row_id).val('');
$('#max-' + row_id).attr('readonly','readonly');
$('#max-' + row_id).val('');
break;
}
/* Change value input to match this type
*/
changeValueType(row_id, value);
}
var changeValueType = function(id, newType){
switch (newType){
case 'select':
$('#string_' + id).css({"display":"none"});
$('#select_' + id).css({"display":"block"});
$('#boolean_' + id).css({"display":"none"});
$('#multiselect_' + id).css({"display":"none"});
$('#text_' + id).css({"display":"none"});
break;
case 'text':
$('#string_' + id).css({"display":"none"});
$('#select_' + id).css({"display":"none"});
$('#boolean_' + id).css({"display":"none"});
$('#multiselect_' + id).css({"display":"none"});
$('#text_' + id).css({"display":"block"});
break;
case 'multiselect':
$('#string_' + id).css({"display":"none"});
$('#select_' + id).css({"display":"none"});
$('#boolean_' + id).css({"display":"none"});
$('#multiselect_' + id).css({"display":"block"});
$('#text_' + id).css({"display":"none"});
break;
case 'boolean':
$('#string_' + id).css({"display":"none"});
$('#select_' + id).css({"display":"none"});
$('#boolean_' + id).css({"display":"block"});
$('#multiselect_' + id).css({"display":"none"});
$('#text_' + id).css({"display":"none"});
break;
default:
$('#string_' + id).css({"display":"block"});
$('#select_' + id).css({"display":"none"});
$('#boolean_' + id).css({"display":"none"});
$('#multiselect_' + id).css({"display":"none"});
$('#text_' + id).css({"display":"none"});
break;
}
};
EDITI changed the changeValueType function to cut it down..-
var changeValueType = function(id, newType){
var types = ['string','text','select','multiselect','boolean'];
$.each(types , function(i, val) {
if(newType === val) {
$('#' + val + '_' + id).addClass('display-block');
$('#' + val + '_' + id).removeClass('display-none');
} else {
$('#' + val + '_' + id).addClass('display-none');
$('#' + val + '_' + id).removeClass('display-block');
}
});
};
So now just want to cut down the syncAttributeSettings() ... Its so ugly!- Basically, im trying to write a script that uses AJAX to verify if a username exists. Depending on the response from the AJAX call, it should return true or false. I know I can accomplish this by doing async:false, but thats a no no.Heres a basic version of the script:
-
function whatever (username) {
var result = true;
$.get( "/account/check_username/" + username, function ( response ) {
if($.trim( response ) == 'Exists') {
result = false;
}
} );
return result;
}
Anyway to have it set result to false? I know since its Async, the ajax call, the function returns the result variable before the ajax call is complete.A friend of mine gave me a hint saying I could use a deferred promise, but I havent been able to figure it out.- 14-Oct-2013 08:21 PM
- Forum: Using jQuery
So I have a form that does a lot of validation using jQuery. At the top, it sets a doSubmit variable to true, then if theres an issue with one of the form elements, it sets it to false. At the end, theres an if statement, if doSubmit is true, then return true to submit the form. Heres the code- jQuery(document).ready(function($) {
- $('#new_asset').submit(function() {
- doSubmit = true;
- /**
- * REQUIRED CLASS CHECK
- * Loop through each input with "required" class, make sure they ahve a value
- */
- $('.required').each(function() {
- var attr = $(this);
- var attr_name = this.name;
- var ignore = ['checkbox','select'];
- var type = $(this).attr('type');
- if( ! attr.val()) {
- var str="Attribute '%s' set the doSubmit value to FALSE, because it is a required value, and not populated";
- var cons=str.replace("%s",attr_name);
- console.log(cons);
- doSubmit = false;
- /* Generate the error string from the language file, insert the
- * attribute name in place of %s
- */
- var str="Attribute <i>%s</i> is a required attribute";
- var alrt=str.replace("%s",attr_name);
- alert_error(alrt);
- } else {
- var str="Value check for required attribute '%s' was successful";
- var cons=str.replace("%s",attr_name);
- console.log(cons);
- }
- });
- /**
- * UNIQUE CLASS CHECK
- * Loop through each input with "unique" class, make sure they're unique,
- * this is done by performing an AJAX call to /assets/does_value_exist with
- * the attribute ID and value, the result will determine if its unique or not
- */
- $('.unique').each(function() {
- var attr = $(this);
- var attr_name = this.name;
- var attr_val = this.value;
- var attr_id = $(this).attr('data-attr_id');
- var ignore = ['checkbox','select'];
- var type = $(this).attr('type');
- /* Check to make sure the input type allows unique values
- * Some input types cant have uniques.. (EG: Multiselect, checkbox, etc)
- *
- * var str="Attribute <i>%s</i> is a required attribute";
- var alrt=str.replace("%s",attr_name);
- alert_error(alrt);
- */
- if(jQuery.inArray(type, ignore) == -1) {
- if(attr.val()) {
- $.ajax({
- type : "POST",
- data : "attr=" + attr_id + "&val=" + attr_val + "&ignore=86",
- url : "/assets/does_value_exist",
- success: function (data, textStatus, xhr) {
- var str="Uniqueness check for attribute '%s' was successful; Data Returned: %s";
- var cons=str.replace("%s",attr_name);
- var cons=cons.replace("%s",data);
- console.log(cons);
- /* The value of the "/assets/does_value_exist" page
- * will be the number of results found, which will
- * be the value of the variable 'data'
- */
- // If no matches found for the value...
- if (data == 0) {
- var str="Attribute '%s' is unique";
- var cons=str.replace("%s",attr_name);
- console.log(cons);
- // If 1 or more value was found...
- } else if (data >= 1) {
- var str="Attribute '%s' set the doSubmit value to FALSE, because it requires a unique value, and this value already exists";
- var cons=str.replace("%s",attr_name);
- console.log(cons);
- console.log('Setting doSubmit val to false');
- doSubmit = false;
- console.log('doSubmit val:' + doSubmit);
- var str="Attribute '%s' requires a unique value, the value you have specified is already in use";
- var alrt=str.replace("%s",attr_name);
- alert_error(alrt);
- // If... maybe it didnt return a numerical value?
- } else {
- var str="Uniqueness check for attribute '%s' failed. Expecting 'true' or 'false', but got: %s";
- var cons=str.replace("%s",attr_name);
- var cons=cons.replace("%s",data);
- console.log(cons);
- }
- },
- error: function ( xhr, ajaxOptions, thrownError ) {
- var str="Uniqueness check for attribute '%s' was UNSUCCESSFUL (AJAX call failed: %s)";
- var cons=str.replace("%s",attr_name);
- var cons=cons.replace("%s",thrownError);
- console.log(cons);
- doSubmit = false;
- var str="Uniqueness validation for attribute '%s' failed, (Check logs for more information)";
- var alrt=str.replace("%s",attr_name);
- alert_error(alrt);
- }
- });
- }
- } else {
- var str="Attribute '%s' requires unique value, but this attribute type (%s) does not allow unique values.";
- var cons=str.replace("%s",attr_name);
- var cons=cons.replace("%s",type);
- console.log(cons);
- }
- });
- /**
- * REGEX CLASS CHECK
- *
- */
- $('.regex').each(function() {
- var attr = $(this);
- var attr_name = this.name;
- var attr_val = this.value;
- var attr_id = $(this).attr('data-attr_id');
- var ignore = ['checkbox','select'];
- var type = $(this).attr('type');
- if(jQuery.inArray(type, ignore) == -1) {
- if(attr.val()) {
- $.ajax({
- type : "POST",
- data : "attr=" + attr_id + "&val=" + attr_val,
- url : "/assets/regex_check",
- success: function (data, textStatus, xhr) {
- if(data == "false") {
- var str="Attribute '%s' set the doSubmit value to FALSE, because it requires a regex match, and it did not match the regex pattern";
- var cons=str.replace("%s",attr_name);
- console.log(cons);
- doSubmit = false;
- var str="Value for the attribute <i>%s</i> does not match the reqular expression requirements";
- var alrt=str.replace("%s",attr_name);
- alert_error(alrt);
- }
- }
- });
- }
- } else {
- var str="Attribute '%s' has regex class, but is not a regexable input type (%s)";
- var cons=str.replace("%s",attr_name);
- console.log(cons);
- }
- });
- /**
- * MAX CLASS
- * Check if any attributes have the max characters setting enabled
- */
- $('.max').each(function() {
- var attr = $(this);
- var attr_name = this.name;
- var attr_val = this.value;
- var max = $(this).attr('data-max_chars');
- var ignore = ['checkbox','select'];
- var type = $(this).attr('type');
- if(jQuery.inArray(type, ignore) == -1) {
- if(attr.val()) {
- if(attr_val.length > max) {
- var str="Attribute '%s' set the doSubmit value to FALSE, because a maximum char limit exists, and it was exceeded";
- var cons=str.replace("%s",attr_name);
- console.log(cons);
- doSubmit = false;
- var str="Attribute '%s' has a maximum length of %d characters";
- var alrt=str.replace("%s",attr_name);
- var alrt=alrt.replace("%d",max);
- alert_error(alrt);
- }
- }
- } else {
- var str="Attribute '%s' has the max class, but is not an input type that allows max value length (%s)";
- var cons=str.replace("%s",attr_name);
- var cons=cons.replace("%s",type);
- console.log(cons);
- }
- });
- /**
- * MIN CLASS
- * Check if any attributes have the min characters setting enabled
- */
- $('.min').each(function() {
- var attr = $(this);
- var attr_name = this.name;
- var attr_val = this.value;
- var min = $(this).attr('data-min_chars');
- var ignore = ['checkbox','select'];
- var type = $(this).attr('type');
- if(jQuery.inArray(type, ignore) == -1) {
- if(attr.val()) {
- if(attr_val.length < min) {
- var str="Attribute '%s' set the doSubmit value to FALSE, because a minimum char limit exists, and it was not met";
- var cons=str.replace("%s",attr_name);
- console.log(cons);
- doSubmit = false;
- var str="Attribute '%s' has a minimum of %d characters";
- var alrt=str.replace("%s",attr_name);
- var alrt=alrt.replace("%d",max);
- alert_error(alrt);
- }
- }
- } else {
- var str="Attribute '%s' has the min class, but is not an input type that allows min value length (%s)";
- var cons=str.replace("%s",attr_name);
- var cons=cons.replace("%s",attr_name);
- console.log(cons);
- }
- });
- var str="Result of asset form attribute validation: %s";
- var cons=str.replace("%s",doSubmit);
- console.log(cons);
- /* I would think that this if statement gets executed last, but it doesnt.
- * it seems to get executed much earlier
- */
- if (doSubmit) {
- // Disable the "leave form verification" thingy. THis gets enabled when any attribute value is modified
- $('#doPrompt').val('no');
- console.log('SUCCESS doPrompt val: ' + doSubmit);
- return true;
- } else {
- console.log('FAIL doPrompt val: ' + doSubmit);
- return false;
- }
- });
- });
Heres the console log outputProcessing attribute "E-Mail" (ID: 118) asset_form_validation.js?ignore=86:358Processing attribute "E-Mail" (ID: 118) asset_form_validation.js?ignore=86:358Processing attribute "E-Mail" (ID: 118) asset_form_validation.js?ignore=86:358Value check for required attribute 'First Name' was successful asset_form_validation.js?ignore=86:93Value check for required attribute 'Last Name' was successful asset_form_validation.js?ignore=86:93Value check for required attribute 'E-Mail' was successful asset_form_validation.js?ignore=86:93Value check for required attribute 'Username' was successful asset_form_validation.js?ignore=86:93Result of asset form attribute validation: true asset_form_validation.js?ignore=86:321SUCCESS doPrompt val: true asset_form_validation.js?ignore=86:329Uniqueness check for attribute 'Username' was successful; Data Returned: 0 asset_form_validation.js?ignore=86:130Attribute 'Username' is unique asset_form_validation.js?ignore=86:141Uniqueness check for attribute 'E-Mail' was successful; Data Returned: 1 asset_form_validation.js?ignore=86:130Attribute 'E-Mail' set the doSubmit value to FALSE, because it requires a unique value, and this value already exists asset_form_validation.js?ignore=86:147Setting doSubmit val to false asset_form_validation.js?ignore=86:149doSubmit val:falseSo you can see, on the line that has SUCCESS... that means it jumped right down to the if statement, before it got done processing the other form elements...Anyone have an idea why this is happening?- «Prev
- Next »
-
-
-
-
-
-
Moderate user : justinhyland
-
-
© 2013 jQuery Foundation
Sponsored by
and others.