How to check the inputs for each tab? - javascript

I want to check the inputs for each tab.
My code so far: jsfiddle
$(document).ready(function () {
var tabs = $("#mytabs").tabs();
var validator = $("#formItem").validate();
$(".next-button").click(function () {
//var selected = $("#tabs").tabs("option", "selected");
//$("#tabs").tabs("option", "selected", selected + 1);
var valid = true;
var i = 0;
var $inputs = $(this).closest("div").find("input");
$inputs.each(function () {
if (!validator.element(this) && valid) {
valid = false;
}
});
if (valid) {
$("#mytabs").tabs("option", "current", 1);
}
});
//use link to submit form instead of button
$("button[id=finish_button]").click(function () {
$(this).parents("form").submit();
});
});

You need to find closest div but with class i.e tab-content or you can use the respective id as in your current implementation there is a next button for each tab. So use unique id of your div.
You currently have following defined which is incorrect,
var $inputs = $(this).closest("div").find("input");
Fix it to,
$(".next-button").click(function() {
//var selected = $("#tabs").tabs("option", "selected");
//$("#tabs").tabs("option", "selected", selected + 1);
var valid = true;
var i = 0;
var $inputs = $(this).closest("div#tabs-1").find("input");
//var $inputs = $(this).closest("div.tab-content").find("input");
$inputs.each(function() {
if (!validator.element(this) && valid) {
valid = false;
}
});
if (valid) {
$("#mytabs").tabs("option", "current", 1);
}
});

try this code.
here's a codepen
and Here's the code. It is not working here for some reason but you can see it working in codepen
+function ($) {
'use strict';
// VALIDATOR CLASS DEFINITION
// ==========================
var Validator = function (element, options) {
this.$element = $(element)
this.options = options
options.errors = $.extend({}, Validator.DEFAULTS.errors, options.errors)
for (var custom in options.custom) {
if (!options.errors[custom]) throw new Error('Missing default error message for custom validator: ' + custom)
}
$.extend(Validator.VALIDATORS, options.custom)
this.$element.attr('novalidate', true) // disable automatic native validation
this.toggleSubmit()
this.$element.on('input.bs.validator change.bs.validator focusout.bs.validator', $.proxy(this.validateInput, this))
this.$element.on('submit.bs.validator', $.proxy(this.onSubmit, this))
this.$element.find('[data-match]').each(function () {
var $this = $(this)
var target = $this.data('match')
$(target).on('input.bs.validator', function (e) {
$this.val() && $this.trigger('input.bs.validator')
})
})
}
Validator.INPUT_SELECTOR = ':input:not([type="submit"], button):enabled:visible'
Validator.DEFAULTS = {
delay: 500,
html: false,
disable: true,
custom: {},
errors: {
match: 'Does not match',
minlength: 'Not long enough'
},
feedback: {
success: 'glyphicon-ok',
error: 'glyphicon-remove'
}
}
Validator.VALIDATORS = {
'native': function ($el) {
var el = $el[0]
return el.checkValidity ? el.checkValidity() : true
},
'match': function ($el) {
var target = $el.data('match')
return !$el.val() || $el.val() === $(target).val()
},
'minlength': function ($el) {
var minlength = $el.data('minlength')
return !$el.val() || $el.val().length >= minlength
}
}
Validator.prototype.validateInput = function (e) {
var $el = $(e.target)
var prevErrors = $el.data('bs.validator.errors')
var errors
if ($el.is('[type="radio"]')) $el = this.$element.find('input[name="' + $el.attr('name') + '"]')
this.$element.trigger(e = $.Event('validate.bs.validator', {relatedTarget: $el[0]}))
if (e.isDefaultPrevented()) return
var self = this
this.runValidators($el).done(function (errors) {
$el.data('bs.validator.errors', errors)
errors.length ? self.showErrors($el) : self.clearErrors($el)
if (!prevErrors || errors.toString() !== prevErrors.toString()) {
e = errors.length
? $.Event('invalid.bs.validator', {relatedTarget: $el[0], detail: errors})
: $.Event('valid.bs.validator', {relatedTarget: $el[0], detail: prevErrors})
self.$element.trigger(e)
}
self.toggleSubmit()
self.$element.trigger($.Event('validated.bs.validator', {relatedTarget: $el[0]}))
})
}
Validator.prototype.runValidators = function ($el) {
var errors = []
var deferred = $.Deferred()
var options = this.options
$el.data('bs.validator.deferred') && $el.data('bs.validator.deferred').reject()
$el.data('bs.validator.deferred', deferred)
function getErrorMessage(key) {
return $el.data(key + '-error')
|| $el.data('error')
|| key == 'native' && $el[0].validationMessage
|| options.errors[key]
}
$.each(Validator.VALIDATORS, $.proxy(function (key, validator) {
if (($el.data(key) || key == 'native') && !validator.call(this, $el)) {
var error = getErrorMessage(key)
!~errors.indexOf(error) && errors.push(error)
}
}, this))
if (!errors.length && $el.val() && $el.data('remote')) {
this.defer($el, function () {
var data = {}
data[$el.attr('name')] = $el.val()
$.get($el.data('remote'), data)
.fail(function (jqXHR, textStatus, error) { errors.push(getErrorMessage('remote') || error) })
.always(function () { deferred.resolve(errors)})
})
} else deferred.resolve(errors)
return deferred.promise()
}
Validator.prototype.validate = function () {
var delay = this.options.delay
this.options.delay = 0
this.$element.find(Validator.INPUT_SELECTOR).trigger('input.bs.validator')
this.options.delay = delay
return this
}
Validator.prototype.showErrors = function ($el) {
var method = this.options.html ? 'html' : 'text'
this.defer($el, function () {
var $group = $el.closest('.form-group')
var $block = $group.find('.help-block.with-errors')
var $feedback = $group.find('.form-control-feedback')
var errors = $el.data('bs.validator.errors')
if (!errors.length) return
errors = $('<ul/>')
.addClass('list-unstyled')
.append($.map(errors, function (error) { return $('<li/>')[method](error) }))
$block.data('bs.validator.originalContent') === undefined && $block.data('bs.validator.originalContent', $block.html())
$block.empty().append(errors)
$group.addClass('has-error')
$feedback.length
&& $feedback.removeClass(this.options.feedback.success)
&& $feedback.addClass(this.options.feedback.error)
&& $group.removeClass('has-success')
})
}
Validator.prototype.clearErrors = function ($el) {
var $group = $el.closest('.form-group')
var $block = $group.find('.help-block.with-errors')
var $feedback = $group.find('.form-control-feedback')
$block.html($block.data('bs.validator.originalContent'))
$group.removeClass('has-error')
$feedback.length
&& $feedback.removeClass(this.options.feedback.error)
&& $feedback.addClass(this.options.feedback.success)
&& $group.addClass('has-success')
}
Validator.prototype.hasErrors = function () {
function fieldErrors() {
return !!($(this).data('bs.validator.errors') || []).length
}
return !!this.$element.find(Validator.INPUT_SELECTOR).filter(fieldErrors).length
}
Validator.prototype.isIncomplete = function () {
function fieldIncomplete() {
return this.type === 'checkbox' ? !this.checked :
this.type === 'radio' ? !$('[name="' + this.name + '"]:checked').length :
$.trim(this.value) === ''
}
return !!this.$element.find(Validator.INPUT_SELECTOR).filter('[required]').filter(fieldIncomplete).length
}
Validator.prototype.onSubmit = function (e) {
this.validate()
if (this.isIncomplete() || this.hasErrors()) e.preventDefault()
}
Validator.prototype.toggleSubmit = function () {
if(!this.options.disable) return
var $btn = $('button[type="submit"], input[type="submit"]')
.filter('[form="' + this.$element.attr('id') + '"]')
.add(this.$element.find('input[type="submit"], button[type="submit"]'))
$btn.toggleClass('disabled', this.isIncomplete() || this.hasErrors())
}
Validator.prototype.defer = function ($el, callback) {
callback = $.proxy(callback, this)
if (!this.options.delay) return callback()
window.clearTimeout($el.data('bs.validator.timeout'))
$el.data('bs.validator.timeout', window.setTimeout(callback, this.options.delay))
}
Validator.prototype.destroy = function () {
this.$element
.removeAttr('novalidate')
.removeData('bs.validator')
.off('.bs.validator')
this.$element.find(Validator.INPUT_SELECTOR)
.off('.bs.validator')
.removeData(['bs.validator.errors', 'bs.validator.deferred'])
.each(function () {
var $this = $(this)
var timeout = $this.data('bs.validator.timeout')
window.clearTimeout(timeout) && $this.removeData('bs.validator.timeout')
})
this.$element.find('.help-block.with-errors').each(function () {
var $this = $(this)
var originalContent = $this.data('bs.validator.originalContent')
$this
.removeData('bs.validator.originalContent')
.html(originalContent)
})
this.$element.find('input[type="submit"], button[type="submit"]').removeClass('disabled')
this.$element.find('.has-error').removeClass('has-error')
return this
}
// VALIDATOR PLUGIN DEFINITION
// ===========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var options = $.extend({}, Validator.DEFAULTS, $this.data(), typeof option == 'object' && option)
var data = $this.data('bs.validator')
if (!data && option == 'destroy') return
if (!data) $this.data('bs.validator', (data = new Validator(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.validator
$.fn.validator = Plugin
$.fn.validator.Constructor = Validator
// VALIDATOR NO CONFLICT
// =====================
$.fn.validator.noConflict = function () {
$.fn.validator = old
return this
}
// VALIDATOR DATA-API
// ==================
$(window).on('load', function () {
$('form[data-toggle="validator"]').each(function () {
var $form = $(this)
Plugin.call($form, $form.data())
})
})
}(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="contact-form">
<form data-toggle="validator" action="contact_script" method="post" role="form">
<div class="form-group">
<input name="name" type="text" class="form-control input-lg" placeholder="Your Name" required>
</div>
<div class="form-group">
<input name="email" type="email" class="form-control input-lg" placeholder="E-mail" required>
</div>
<div class="form-group">
<input name="phone" type="text" class="form-control input-lg" placeholder="Contact No." required>
</div>
<div class="form-group">
<input name="subject" type="text" class="form-control input-lg" placeholder="Subject" required>
</div>
<div class="form-group">
<textarea name="message" class="form-control input-lg" rows="5" placeholder="Message"></textarea>
</div>
<button type="submit" class="btn wow bounceInRight" data-wow-delay="0.8s">Send</button>
</form>
</div>

Related

Imgur upload add to input form

I've create this code in HTML
<div class="margin-bottom"><p class="title"><strong>Picture</strong></p>
<div class="textbox-group margin-bottom">
<span class="textbox-group-addon pointer" id="basic-addon"><div class="dropzones"><div class="info"><i class="fa fa-upload" title="Picture Preview"></i></div></div></span>
<input id="preview" class="textbox" name="preview" value="" type="text" aria-describedby="basic-addon">
</div><div class="loading-modal text-center"><i class="fa fa-spinner fa-pulse fa-3x fa-fw"><span class="sr-only"></span></i> Uploading...</div>
and here is my imguruploads.js
/* Imgur Upload Script */
(function (root, factory) {
"use strict";
if (typeof define === 'function' && define.amd) {
define([], factory);
} else if (typeof exports === 'object') {
module.exports = factory();
} else {
root.Imgur = factory();
}
}(this, function () {
"use strict";
var Imgur = function (options) {
if (!this || !(this instanceof Imgur)) {
return new Imgur(options);
}
if (!options) {
options = {};
}
if (!options.clientid) {
throw 'Provide a valid Client Id here: https://api.imgur.com/';
}
this.clientid = options.clientid;
this.endpoint = 'https://api.imgur.com/3/image';
this.callback = options.callback || undefined;
this.dropzones = document.querySelectorAll('.dropzones');
this.info = document.querySelectorAll('.info');
this.run();
};
Imgur.prototype = {
createEls: function (name, props, text) {
var el = document.createElement(name), p;
for (p in props) {
if (props.hasOwnProperty(p)) {
el[p] = props[p];
}
}
if (text) {
el.appendChild(document.createTextNode(text));
}
return el;
},
insertAfter: function (referenceNode, newNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
},
post: function (path, data, callback) {
var xhttp = new XMLHttpRequest();
xhttp.open('POST', path, true);
xhttp.setRequestHeader('Authorization', 'Client-ID ' + this.clientid);
xhttp.onreadystatechange = function () {
if (this.readyState === 4) {
if (this.status >= 200 && this.status < 300) {
var response = '';
try {
response = JSON.parse(this.responseText);
} catch (err) {
response = this.responseText;
}
callback.call(window, response);
} else {
throw new Error(this.status + " - " + this.statusText);
}
}
};
xhttp.send(data);
xhttp = null;
},
createDragZone: function () {
var input;
input = this.createEls('input', {type: 'file', className: 'input', accept: 'image/*'});
Array.prototype.forEach.call(this.dropzones, function (zone) {
zone.appendChild(input);
this.status(zone);
this.upload(zone);
}.bind(this));
},
loading: function () {
var div, i, span;
div = this.createEls('div', {className: 'loading-modals'});
i = this.createEls('i', {className: 'fa fa-spinner fa-pulse fa-3x fa-fw'});
span = this.createEls('span', {className: 'sr-only'});
div.appendChild(i);
i.appendChild(span);
document.body.appendChild(div);
},
status: function (el) {
var div = this.createEls('div', {className: 'statuss'});
this.insertAfter(el, div);
},
matchFiles: function (file, zone) {
var status = zone.nextSibling;
if (file.type.match(/image/) && file.type !== 'image/svg+xml') {
document.body.classList.add('loading');
status.classList.remove('pm_alert', 'red_alert');
status.innerHTML = '';
var fd = new FormData();
fd.append('image', file);
this.post(this.endpoint, fd, function (data) {
document.body.classList.remove('loading');
typeof this.callback === 'function' && this.callback.call(this, data);
}.bind(this));
} else {
status.classList.remove('pm_alert');
status.classList.add('red_alert');
status.innerHTML = 'Invalid archive';
}
},
upload: function (zone) {
var events = ['dragenter', 'dragleave', 'dragover', 'drop'],
file, target, i, len;
zone.addEventListener('change', function (e) {
if (e.target && e.target.nodeName === 'INPUT' && e.target.type === 'file') {
target = e.target.files;
for (i = 0, len = target.length; i < len; i += 1) {
file = target[i];
this.matchFiles(file, zone);
}
}
}.bind(this), false);
events.map(function (event) {
zone.addEventListener(event, function (e) {
if (e.target && e.target.nodeName === 'INPUT' && e.target.type === 'file') {
if (event === 'dragleave' || event === 'drop') {
e.target.parentNode.classList.remove('dropzone-dragging');
} else {
e.target.parentNode.classList.add('dropzone-dragging');
}
}
}, false);
});
},
run: function () {
var loadingModal = document.querySelector('.loading-modal');
if (!loadingModal) {
this.loading();
}
this.createDragZone();
}
};
return Imgur;
}));
var feedback = function(res) {
textarea: '',
document.textarea = $('#preview');
if (res.success === true) {
var wahaha = res.data.link.replace();
document.text.add( wahaha );
document.querySelector('.status').classList.add('bg-success');
document.querySelector('.status').innerHTML =
'<div class="text-left">Copy dan Paste kan link gambar <i class="fa fa-hand-o-down fa-fw"></i> ke form <strong>atas</strong> <i class="fa fa-hand-o-up fa-fw"></i></div>' + '<div class="text-center scaleimages padding-topbottom"><input class="textbox image-url media-heading" value=' + wahaha + '/>' + '<img class="img" src=' + wahaha + '/>';
}
};
new Imgur({
clientid: '3da90edf4016361', //You can change this ClientID
callback: feedback
});
this code work well but not work like what I want, I want when the image uploaded successfully then the link "wahaha" added to this input form
<input id="preview" class="textbox" name="preview" value="" type="text" aria-describedby="basic-addon">
Yes there are input form show when it finish upload, but what I want is the text added to another input form
anyone have an idea to fix this?
just add this code
document.getElementById('gambar_preview').value = wahaha;
and everything work like what I want

element.val() returning previous value

Here is my problem
I am trying to create a button that calls a directive function which then activates the google place 'place_changed' event that is assigned to the directive. If the getPlace() function doesn't return a result e.g. var result = scope.gPlace.getPlace(); then I want force a place prediction by doing the following.
if( result === undefined ) {
result = { name: element.val() }
}
however the problem is that this code will work when the page is first loaded but subsequent attempts will assign the var result to the previous text that was entered. e.g. Type "Adelaide" and click on the button equals successful process however now type melbourne and click on the button will still equal "Adelaide"
'use strict';
angular.module( "ngAutocomplete", [])
.directive('ngAutocomplete', function() {
return {
require: 'ngModel',
scope: {
ngModel: '=',
options: '=?',
details: '=?',
setFn: '&'
},
link: function(scope, element, attrs, controller) {
//options for autocomplete
var opts
var watchEnter = false
//convert options provided to opts
var initOpts = function() {
opts = {}
if (scope.options) {
if (scope.options.watchEnter !== true) {
watchEnter = false
} else {
watchEnter = true
}
if (scope.options.types) {
opts.types = []
opts.types.push(scope.options.types)
scope.gPlace.setTypes(opts.types)
} else {
scope.gPlace.setTypes([])
}
if (scope.options.bounds) {
opts.bounds = scope.options.bounds
scope.gPlace.setBounds(opts.bounds)
} else {
scope.gPlace.setBounds(null)
}
if (scope.options.country) {
opts.componentRestrictions = {
country: scope.options.country
}
scope.gPlace.setComponentRestrictions(opts.componentRestrictions)
} else {
scope.gPlace.setComponentRestrictions(null)
}
}
}
if (scope.gPlace == undefined) {
scope.gPlace = new google.maps.places.Autocomplete(element[0], {});
}
google.maps.event.addListener(scope.gPlace, 'place_changed', function() {
var result = scope.gPlace.getPlace();
//hack to make sure we have an object to pass to ensure we can get results from the called function activateGetPlace
if( result === undefined ) {
result = { name: element.val() }
}
console.log("the result", result);
if (result !== undefined) {
if (result.address_components !== undefined) {
scope.$apply(function() {
scope.details = result;
controller.$setViewValue(element.val());
});
}
else {
if (watchEnter) {
getPlace(result)
}
}
}
})
//function to get retrieve the autocompletes first result using the AutocompleteService
var getPlace = function(result) {
var autocompleteService = new google.maps.places.AutocompleteService();
if (result.name.length > 0){
autocompleteService.getPlacePredictions(
{
input: result.name,
offset: result.name.length,
types: opts.types,
componentRestrictions: opts.componentRestrictions
},
function listentoresult(list, status) {
if(list == null || list.length == 0) {
scope.$apply(function() {
scope.details = null;
});
} else {
var placesService = new google.maps.places.PlacesService(element[0]);
placesService.getDetails(
{'reference': list[0].reference},
function detailsresult(detailsResult, placesServiceStatus) {
if (placesServiceStatus == google.maps.GeocoderStatus.OK) {
scope.$apply(function() {
controller.$setViewValue(detailsResult.formatted_address);
element.val(detailsResult.formatted_address);
scope.details = detailsResult;
//on focusout the value reverts, need to set it again.
var watchFocusOut = element.on('focusout', function(event) {
element.val(detailsResult.formatted_address);
element.unbind('focusout')
})
});
}
}
);
}
});
}
}
controller.$render = function () {
var location = controller.$viewValue;
element.val(location);
};
//watch options provided to directive
scope.watchOptions = function () {
return scope.options
};
scope.$watch(scope.watchOptions, function () {
initOpts()
}, true);
scope.activateGetPlace = function() {
google.maps.event.trigger(scope.gPlace, 'place_changed');
}
scope.setFn({theDirFn: scope.activateGetPlace});
}
};
});
var mechanicsearch = angular.module('mechanicsearch', ['ngRoute','ngResource','ngAutocomplete']),
radiusOptions = [];
mechanicsearch.run(function($rootScope) {
$rootScope.$on('handleActiveJobsPanel', function(event, args) {
$rootScope.$broadcast('activateJobsPanel', args);
});
$rootScope.$on('handleActiveFinalise', function(event, args) {
$rootScope.$broadcast('activateFinalisePanel', args);
});
$rootScope.$on('handleActiveSearch', function(event, args) {
$rootScope.$broadcast('activateSearchPanel', args);
});
});
mechanicsearch.filter('htmlToPlaintext', function() {
return function(text) {
return text ? String(text).replace(/<[^>]+>/gm, '') : '';
};
});
// mechFactory service
mechanicsearch.factory('mechFactory', function($resource,$window) {
var mechanics = [];
var jobs = [];
var addMechanic = function(mechanic){
mechanics.push(mechanic);
};
var getAllMechanics = function(){
return mechanics;
};
var removeAllMechanics = function() {
mechanics = [];
}
var addJob = function(job) {
jobs.push(job);
}
var getAllJobs = function() {
return jobs;
}
var removeAllJobs = function() {
jobs = [];
}
return {
getMechanics: function(location,radius) {
return $resource('/ajax/api.cfm?api=mechanic&function=getMechanicByLocation&lat=:lat&lng=:lng&radius=:radius' ).get({lat:location.lat,lng:location.lng,radius:radius});
},
getJobs: function() {
return $resource('/ajax/api.cfm?api=job&function=getJobsAssignedtoWorkshop' ).get();
},
sendMechanicsJobNotifications: function(mechanics, jobs) {
return $resource('/ajax/api.cfm?api=job&function=sendMechanicsJobNotifications&mechanics=:mechanics&jobs=:jobs' ).get({mechanics:mechanics.toString(),jobs:jobs.toString()});
},
addMechanic: addMechanic,
removeAllMechanics: removeAllMechanics,
getAllMechanics: getAllMechanics,
addJob: addJob,
removeAllJobs: removeAllJobs,
getAllJobs: getAllJobs
}
});
mechanicsearch.controller('SearchCtrl', ['$timeout', '$scope', '$window', '$location', '$routeParams', 'filterFilter', 'mechFactory', '$resource', '$element',
function ($timeout, $scope, $window, $location, $routeParams, filterFilter, mechFactory, $resource, $element) {
$scope.place = {};
$scope.place.address = null;
$scope.place.lat = null;
$scope.place.lng = null;
$scope.radius = 25;
$scope.mechanics = [];
$scope.selection = [];
$scope.alert = null;
$scope.showSearchPanel = true;
//Helper method to get selected mechanics
$scope.selectedMechanics = function selectedMechanics() {
filterFilter($scope.mechanics, { selected: true })
};
//allow mechanic checkbox to select/deselect on click
$scope.toggleMechanicSelect = function(mechanic) {
mechanic.selected = !mechanic.selected;
}
$scope.goToJobListing = function() {
$scope.showSearchPanel = false;
mechFactory.removeAllMechanics();
for( var i in $scope.selection ) {
mechFactory.addMechanic($scope.selection[i]);
}
$scope.$emit('handleActiveJobsPanel');
}
// watch mechanics for changes
$scope.$watch('mechanics|filter:{selected:true}', function (nv) {
$scope.selection = nv.map(function (mechanic) {
return mechanic.objectid;
});
}, true);
//watch the returning google autocomplete details object
$scope.$watch('details', function() {
if( $scope.details !== undefined && $scope.details !== null ) {
$scope.place.address = $scope.details.formatted_address;
$scope.place.lat = $scope.details.geometry.location.lat();
$scope.place.lng = $scope.details.geometry.location.lng();
}
});
// watch the $scope.place data for changes
$scope.$watchCollection('place', function() {
if( $scope.place.lat !== null || $scope.place.lng !== null ) {
$scope.getMechanics();
}
});
$scope.$watch('radius', function() {
if( Number.isInteger(parseInt($scope.radius)) ){
$scope.getMechanics();
}
});
$scope.setDirectiveFn = function(directiveFn) {
$scope.directiveFn = directiveFn;
};
$scope.getMechanics = function() {
mechFactory.getMechanics($scope.place, $scope.radius).$promise.then(
function successfulResult (mechanicsData) {
if (!mechanicsData || !mechanicsData.data.length){
$scope.alert = 'Sorry, no mechanic found in "' + $scope.place.address + '" with radius of ' + $scope.radius + '.';
$scope.mechanics = [];
$scope.selection = [];
} else {
$scope.alert = mechanicsData.data.length + ' mechanic(s) found in "' + $scope.place.address + '" with radius of ' + $scope.radius + ' km.';
$scope.mechanics = mechanicsData.data;
$scope.selection = [];
}
}, function failedResult (err) {
$scope.alert = err.message;
});
};
//display panel once we have recieved the event
$scope.$on('activateSearchPanel', function(event, args) {
$scope.mechanics = [];
$scope.selection = [];
$scope.alert = null;
$scope.showSearchPanel = true;
$scope.place = {};
$scope.radius = 25;
});
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular-route.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular-resource.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCmN0htBqG3DGo04KKKzC9srgIrhP0Dq5o&libraries=places"></script>
<div id="mechanicsearch" data-ng-app="mechanicsearch">
<div data-ng-controller="SearchCtrl" ng-show="showSearchPanel">
<aside class="workshopsearch" >
<form method="post" class="form-inline" role="form">
<div class="row">
<div class="col-sm-6 form-group input-group-lg">
<input type="text" id="geoSearch" ng-model="autocomplete" class="form-control" ng-autocomplete options="{ types: 'geocode', country: 'au', watchEnter: true }" details="details" set-fn="setDirectiveFn(theDirFn)" />
</div>
<div class="col-sm-6 input-group input-group-lg">
<input type="text" class="form-control" name="radius" id="radius" placeholder="Radius" data-ng-model="radius">
<span class="input-group-btn"><button class="btn btn-go" ng-click="directiveFn()">Go</button</span>
</div>
</div>
</form>
</aside>
</div>
</div>
}
Why are you using element.val() when you have an ngModel bound to the input? Why not use scope.ngModel instead?

I want to add a loading png in LiveSearch

I am using a plugin for live search .. everything is working fine .. i just want to add a loading png that appear on start of ajax request and disappear on results ..
please help me to customize the code just to add class where form id="search-kb-form" .. and remove the class when results are completed.
<form id="search-kb-form" class="search-kb-form" method="get" action="<?php echo home_url('/'); ?>" autocomplete="off">
<div class="wrapper-kb-fields">
<input type="text" id="s" name="s" placeholder="Search what you’re looking for" title="* Please enter a search term!">
<input type="submit" class="submit-button-kb" value="">
</div>
<div id="search-error-container"></div>
</form>
This is the plugin code
jQuery.fn.liveSearch = function (conf) {
var config = jQuery.extend({
url: {'jquery-live-search-result': 'search-results.php?q='},
id: 'jquery-live-search',
duration: 400,
typeDelay: 200,
loadingClass: 'loading',
onSlideUp: function () {},
uptadePosition: false,
minLength: 0,
width: null
}, conf);
if (typeof(config.url) == "string") {
config.url = { 'jquery-live-search-result': config.url }
} else if (typeof(config.url) == "object") {
if (typeof(config.url.length) == "number") {
var urls = {}
for (var i = 0; i < config.url.length; i++) {
urls['jquery-live-search-result-' + i] = config.url[i];
}
config.url = urls;
}
}
var searchStatus = {};
var liveSearch = jQuery('#' + config.id);
var loadingRequestCounter = 0;
// Create live-search if it doesn't exist
if (!liveSearch.length) {
liveSearch = jQuery('<div id="' + config.id + '"></div>')
.appendTo(document.body)
.hide()
.slideUp(0);
for (key in config.url) {
liveSearch.append('<div id="' + key + '"></div>');
searchStatus[key] = false;
}
// Close live-search when clicking outside it
jQuery(document.body).click(function(event) {
var clicked = jQuery(event.target);
if (!(clicked.is('#' + config.id) || clicked.parents('#' + config.id).length || clicked.is('input'))) {
liveSearch.slideUp(config.duration, function () {
config.onSlideUp();
});
}
});
}
return this.each(function () {
var input = jQuery(this).attr('autocomplete', 'off');
var liveSearchPaddingBorderHoriz = parseInt(liveSearch.css('paddingLeft'), 10) + parseInt(liveSearch.css('paddingRight'), 10) + parseInt(liveSearch.css('borderLeftWidth'), 10) + parseInt(liveSearch.css('borderRightWidth'), 10);
// Re calculates live search's position
var repositionLiveSearch = function () {
var tmpOffset = input.offset();
var tmpWidth = input.outerWidth();
if (config.width != null) {
tmpWidth = config.width;
}
var inputDim = {
left: tmpOffset.left,
top: tmpOffset.top,
width: tmpWidth,
height: input.outerHeight()
};
inputDim.topPos = inputDim.top + inputDim.height;
inputDim.totalWidth = inputDim.width - liveSearchPaddingBorderHoriz;
liveSearch.css({
position: 'absolute',
left: inputDim.left + 'px',
top: inputDim.topPos + 'px',
width: inputDim.totalWidth + 'px'
});
};
var showOrHideLiveSearch = function () {
if (loadingRequestCounter == 0) {
showStatus = false;
for (key in config.url) {
if( searchStatus[key] == true ) {
showStatus = true;
break;
}
}
if (showStatus == true) {
for (key in config.url) {
if( searchStatus[key] == false ) {
liveSearch.find('#' + key).html('');
}
}
showLiveSearch();
} else {
hideLiveSearch();
}
}
};
// Shows live-search for this input
var showLiveSearch = function () {
// Always reposition the live-search every time it is shown
// in case user has resized browser-window or zoomed in or whatever
repositionLiveSearch();
// We need to bind a resize-event every time live search is shown
// so it resizes based on the correct input element
jQuery(window).unbind('resize', repositionLiveSearch);
jQuery(window).bind('resize', repositionLiveSearch);
liveSearch.slideDown(config.duration)
};
// Hides live-search for this input
var hideLiveSearch = function () {
liveSearch.slideUp(config.duration, function () {
config.onSlideUp();
for (key in config.url) {
liveSearch.find('#' + key).html('');
}
});
};
input
// On focus, if the live-search is empty, perform an new search
// If not, just slide it down. Only do this if there's something in the input
.focus(function () {
if (this.value.length > config.minLength ) {
showOrHideLiveSearch();
}
})
// Auto update live-search onkeyup
.keyup(function () {
// Don't update live-search if it's got the same value as last time
if (this.value != this.lastValue) {
input.addClass(config.loadingClass);
var q = this.value;
// Stop previous ajax-request
if (this.timer) {
clearTimeout(this.timer);
}
if( q.length > config.minLength ) {
// Start a new ajax-request in X ms
this.timer = setTimeout(function () {
for (url_key in config.url) {
loadingRequestCounter += 1;
jQuery.ajax({
key: url_key,
url: config.url[url_key] + q,
success: function(data){
if (data.length) {
searchStatus[this.key] = true;
liveSearch.find("#" + this.key).html(data);
} else {
searchStatus[this.key] = false;
}
loadingRequestCounter -= 1;
showOrHideLiveSearch();
}
});
}
}, config.typeDelay);
}
else {
for (url_key in config.url) {
searchStatus[url_key] = false;
}
hideLiveSearch();
}
this.lastValue = this.value;
}
});
});
};
add a background to the loading class
.loading {
background:url('http://path_to_your_picture');
}

detect when 2 calendar values changed

I am making a financial report where user choose 2 dates search_date1 and search_date2, and then a monthly report is generated.
I created first a daily report with only one calendar and when it is changed I apply some AJAX script to it and it works correctly:
var myApp = {};
myApp.search_date = "";
document.getElementById('search_date').onchange = function (e) {
if (this.value != myApp.search_date) {
var d = $("#search_date").val();
$.ajax({
...
});
}
}
Now I can't know how to detect if both calendars are changed to apply AJAX script according to their values.
EDIT
Is it correct to do the following:
var myApp = {};
myApp.search_date1 = "";
myApp.search_date2 = "";
document.getElementById('search_date1').onchange = function (e) {
if (this.value != myApp.search_date1) {
var d1 = $("#search_date1").val();
document.getElementById('search_date2').onchange = function (e) {
if (this.value != myApp.search_date2) {
var d2 = $("#search_date2").val();
$.ajax({
...
})
}
});
}
});
try this:
var temp = {
from: null,
to: null
}
document.getElementById('from').onchange = function(e){
temp.from = e.target.value;
goAjax();
}
document.getElementById('to').onchange = function(e){
temp.to = e.target.value;
goAjax();
}
function goAjax(){
if(temp.from && temp.to && new Date(temp.from) < new Date(temp.to)){
//do ajax call
console.log('valid')
}
}
<input type="date" id='from'/>
<br>
<input type="date" id='to'/>
I would have captured the change event for both elements :
$("#search_date1, #search_date2").on('change',function(){
var d1 = $("#search_date1").val();
var d2 = $("#search_date2").val();
$.ajax({...});
});
What you do in your edit may work, but it would be better (and easier) do something like this
var myApp = {};
myApp.original_search_date1 = $("#search_date1").val();
myApp.original_search_date2 = $("#search_date2").val();
myApp.search_date1 = $("#search_date1").val();
myApp.search_date2 = $("#search_date2").val();
document.getElementById('search_date1').onchange = function (e) {
if ($("#search_date1").val() != myApp.search_date1) {
myApp.search_date1 = $("#search_date1").val();
sendAjax();
}
});
document.getElementById('search_date2').onchange = function (e) {
if ($("#search_date2").val() != myApp.search_date2) {
myApp.search_date2 = $("#search_date2").val();
sendAjax();
}
});
function sendAjax() {
if (myApp.original_search_date1 !== myApp.search_date1 &&
myApp.original_search_date2 !== myApp.search_date2) {
$.ajax({
...
});
}
}
Cant you just set a variable to check if its been changed with true/false then run the script if both variables are true.
Something like,
var searchOneToggled = false,
searchTwoToggled = false;
$('#search_date_one').on('input', function() {
searchOneToggled = true;
runYourFunction();
});
$('#search_date_two').on('input', function() {
searchTwoToggled = true;
runYourFunction();
});
function runYourFunction() {
if(searchOneToggled === true && searchTwoToggled === true) {
alert('hello world');
}
}

Jquery plugin call methods

Hi i have this little plugin installed:
(function($) {
$.fn.tagfield = function(options) {
if (options && options.add) {
this.each(function(i, elem) {
add_tags(elem, options.add);
});
} if (options && options.remove) {
this.each(function(i, elem) {
remove_tags(elem, options.add);
});
} else {
this.each(function(i, elem) {
var initial_tags = $(elem).val();
$(elem).val('');
tagfield(this, $(elem));
$(initial_tags.split(',')).each(function(i, v) {
v = $.trim(v);
if (v !== '') add_tags(elem, v);
})
});
}
};
var KEYS = {
"enter": "\r".charCodeAt(0),
"space": " ".charCodeAt(0),
"comma": 188,
"backspace": 8
};
var tagfield_id_for = function(real_input) {
return $(real_input).attr('id') + '_tagfield';
};
var add_tags = function(real_input, text) {
remove_tags(real_input, text);
var tag = $('<span class="tag">').append('<span class="text">' + text +'</span>'),
close = $('<a class="close" href="#">X</a>');
close.click(function(e) {
remove_tags(real_input, text);
});
tag.append(close);
$('#' + tagfield_id_for(real_input) + " .tags").append(tag);
real_input = $(real_input);
real_input.val(($.trim(real_input.val()) === '' ? [] : real_input.val().split(',')).concat([text]).join(','));
};
var remove_tags = function(real_input, text) {
$('#' + tagfield_id_for(real_input) + " .tags .tag").each(function(i, v) {
v = $(v);
if (v.find('.text').html() === text) {
v.remove();
real_input = $(real_input);
var tags = $(real_input.val().split(',')).filter(function(i, v) {
return v !== text;
});
real_input.val(Array.prototype.join.call(tags));
}
});
};
var tagfield = function(real_input, elem) {
var tagfield = $('<div class="tagfield">').attr('id', tagfield_id_for(real_input)),
input = $('<input type="text"/>'),
buffer = $('<span class="buffer">'),
tags = $('<span class="tags">');
tagfield.append(tags);
tagfield.append(buffer);
tagfield.append(input);
tagfield.click(function(e) {
input.focus();
});
var check_add_tag = function() {
if (buffer.html()) {
var tag_text = buffer.html();
buffer.html('');
add_tags(real_input, tag_text);
}
};
var add_tag = function(text) {
};
input.keydown(function(e) {
if (e.which === KEYS.enter || e.which === KEYS.space || e.which === KEYS.comma) {
e.preventDefault();
check_add_tag();
}
if (e.which === KEYS.backspace) {
if (buffer.html() === "") {
remove_tags(real_input, tagfield.find('.tag').last().find('.text').html());
} else {
var s = buffer.html();
buffer.html(s.slice(0, s.length-1));
}
}
});
input.blur(check_add_tag);
input.keyup(function(e) {
buffer.append(input.val());
input.val('');
});
$(real_input).hide().after(tagfield);
};
})(jQuery);
does anyone can show me how can i call the methods add_tags() and remove_tags() ?
thanks
$("selector").tagfield({remove:someobject});
$("selector").tagfield({add:someobject});
but the "remove" thing will not work i think, since the second "if" in fn.tagfield watches for "options.remove" but removes the "options.add" ...

Categories

Resources