Job For Wordpress by blueglass plugin apply button validation API - javascript

i want to insert following Java Script into my Wordpress plugin
please help me
this what i written which validate from Sheetsu API
Details at - https://codepen.io/santosh-panda/pen/YOedWv?editors=1010
<input id="input-text_flacement-id">
<script src="https://script.sheetsu.com/"></script>
<script>
var input = document.getElementById('input-text_flacement-id');
var is_focused = false;
input.onfocus = function () {
is_focused = true;
}
input.onblur = function () {
if (is_focused) {
is_focused = false;
check_id(input.value);
}
}
function check_id(id) {
if (id.match(/\d{4}-\d{4}-\d{4}/)) {
document.body.append("\nchecking...");
function successFunc(data) {
var row = data.filter((row)=>row['adhar_no'] == id)
if(row.length){
document.body.append("\nid found");
}
else{
document.body.append('\nid not found');
}
}
// Get all rows where column 'adhar_no' is '3894-8873-7149'
var searchQuery = {
status: 'active',
};
Sheetsu.read("https://sheetsu.com/apis/v1.0dh/dd98887de543/", {
search: searchQuery
}, successFunc);
}
else {
document.body.append('\ninvalid id');
}
}
</script>
this code ^^ want to inster in Wordpress plugin JS
which excutive in http://www.flacement.com/jobssearch/iffco-tokio-job-in-jharsuguda/
i want it when some one apply [apply text field 1
in flacement ID it should validate from JS API if found then procedd or if not then invalide as first code. code is ready but i am confuse where to instert in follwing so it start working
Number.prototype.clamp = function(min, max) {
return Math.min(Math.max(this, min), max);
};
(function($){
$.fn.filterFind = function(selector) {
return this.find('*') // Take the current selection and find all descendants,
.addBack() // add the original selection back to the set
.filter(selector); // and filter by the selector.
};
$.fn.svgDraw = function(progress) {
this.filterFind('path').each(function() {
var pathLength = this.getTotalLength();
$(this).css('strokeDasharray', pathLength + ' ' + pathLength);
$(this).css('strokeDashoffset', pathLength * ((1 - progress)).clamp(0, 1));
});
return this;
};
$(document).ready(function(){
if( $('.jobs-modal').length ){
setTimeout(function(){
$('.jobs-modal').removeClass('hide');
}, 500);
$('.jp-apply-button').click(function(e){
e.preventDefault();
$('body').addClass('jobs-modal-open');
$('.jobs-modal').addClass('open');
});
$('.jobs-modal .modal-close').click(function(e){
e.preventDefault();
$(this).parents('.jobs-modal').removeClass('open');
$('body').removeClass('jobs-modal-open');
});
$('.jobs-modal-content').each(function(k){
$(this).find( '.inputfile' ).each(function(k){
var label = this.nextElementSibling;
var labelVal = label.innerHTML;
$(this).change(function(e){
var fileName = '';
if( this.files && this.files.length > 2 )
fileName = ( this.getAttribute( 'data-multiple-caption' ) || '' ).replace( '{count}', this.files.length );
else
fileName = e.target.value.split( '\\' ).pop();
if( fileName ){
label.querySelector( 'span' ).innerHTML = fileName;
var num = $(this).parents('.modal-input-fileinput').attr('data-files');
num = Number(num) + 1;
$(this).parents('.modal-input-fileinput').attr('data-files', num);
}else{
label.innerHTML = labelVal;
}
});
$(this).focus(function(){ $(this).addClass('has-focus') });
$(this).blur(function(){ $(this).removeClass('has-focus') });
});
});
if( $('.choose_file_multi_add').length ){
var i = 1;
$('.choose_file_multi_add').click(function(e){
e.preventDefault();
var key_id = $(this).data('key');
var parent = $(this).parents('.modal-input-fileinput');
var input = $('#file-input-tpl-'+key_id).html();
var label = $('#file-label-tpl-'+key_id).html();
var id = key_id + '-'+i;
var key = key_id + '-key-'+i;
input = input.replace( '{id}', id ).replace( '{id}', id ).replace( '{id}', id );
input = input.replace( '{nr}', i ).replace( '{nr}', i ).replace( '{nr}', i );
input = input.replace( '{key}', key ).replace( '{key}', key ).replace( '{key}', key );
label = label.replace( '{id}', id ).replace( '{id}', id ).replace( '{id}', id );
$(input).insertBefore( $('#'+key_id+' .choose_file_multi_add') );
$(label).insertBefore( $('#'+key_id+' .choose_file_multi_add') );
//parent.prepend( input );
//parent.prepend( label );
$('#'+id).change(function(e){
var fileName = '';
if( this.files && this.files.length > 1 )
fileName = ( this.getAttribute( 'data-multiple-caption' ) || '' ).replace( '{count}', this.files.length );
else
fileName = e.target.value.split( '\\' ).pop();
if( fileName ){
$('#label-'+id).find('span.name').text( fileName );
var num = $(this).parents('.modal-input-fileinput').attr('data-files');
num = Number(num) + 1;
$(this).parents('.modal-input-fileinput').attr('data-files', num);
}
});
$('.choose_file_multi .remove').click(function(e){
e.preventDefault();
var id = $(this).parents('.choose_file_multi').attr('id');
id = id.replace('label-', 'jobgroup-');
var num = $(this).parents('.modal-input-fileinput').attr('data-files');
num = Number(num) - 1;
$(this).parents('.modal-input-fileinput').attr('data-files', num);
$('.'+id).remove();
recalculateInputs();
return false;
});
$('#'+id).click();
recalculateInputs();
i++;
});
}
function recalculateInputs(){
if( $('.modal-input-fileinput.multiple .modal-input-multifile').length == 0 ){
$('.disabled-file-placeholder').addClass('input-reqired');
}else{
$('.disabled-file-placeholder').removeClass('input-reqired');
}
}
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
var sending_form = false;
$('.progress-button .progress-circle').svgDraw(0);
$("form#jobs-modal-form").submit(function(e){
e.preventDefault();
var self = this;
var toreturn = true;
$('#jobs-modal-form .input-reqired').each(function(){
var value = $(this).val();
var is_checked = false;
if( $(this).hasClass('input-job_email') ){
if( value == '' || !validateEmail(value) ){
$(this).addClass('alert').parents('.jobs-modal-input').addClass('alert');
toreturn = false;
}else{
$(this).removeClass('alert').parents('.jobs-modal-input').removeClass('alert');
}
}else if( $(this).hasClass('modal-input-checkbox') ){
var checkboxes_checked = 0;
$(this).parents('.checkbox_field').find('input[type="checkbox"]').each(function(){
var checked = $(this).prop('checked');
if( checked == true ){
checkboxes_checked++;
}
});
if( checkboxes_checked == 0 ){
$(this).addClass('alert').parents('.jobs-modal-input').addClass('alert');
toreturn = false;
}else{
$(this).removeClass('alert').parents('.jobs-modal-input').removeClass('alert');
}
}else if( $(this).hasClass('modal-input-radio') ){
var checkboxes_checked = 0;
$(this).parents('.radio_field').find('input[type="radio"]').each(function(){
var checked = $(this).prop('checked');
if( checked == true ){
checkboxes_checked++;
}
});
if( checkboxes_checked == 0 ){
$(this).addClass('alert').parents('.jobs-modal-input').addClass('alert');
toreturn = false;
}else{
$(this).removeClass('alert').parents('.jobs-modal-input').removeClass('alert');
}
}else{
if( value == '' ){
$(this).addClass('alert').parents('.jobs-modal-input').addClass('alert');
toreturn = false;
}else{
$(this).removeClass('alert').parents('.jobs-modal-input').removeClass('alert');
}
}
});
var input = document.getElementById('input-text_flacement-id');
var is_focused = false;
input.onfocus = function () {
is_focused = true;
}
input.onblur = function () {
if (is_focused) {
is_focused = false;
check_id(input.value);
}
}
function check_id(id) {
if (id.match(/\d{4}-\d{4}-\d{4}/)) {
document.body.append("\n checking...");
function successFunc(data) {
var row = data.filter((row)=>row['adhar_no'] == id)
if(row.length){
document.body.append("\n id found");
}
else{
document.body.append('\n id not found');
}
}
// Get all rows where column 'adhar_no' is '3894-8873-7149'
var searchQuery = {
status: 'active',
};
Sheetsu.read("https://sheetsu.com/apis/v1.0dh/dd98887de543/", {
search: searchQuery
}, successFunc);
} else {
document.body.append('\n invalid id');
}
}
if( toreturn && sending_form == false ){
/*
var progressBTN = $(self).find('.progress-button');
progressBTN.addClass('loading');
var progressCRCL = $(self).find('.progress-circle');
var progress = 0;
var intervalId = setInterval(function() {
progress += Math.random() * 0.5;
progressCRCL.svgDraw(progress);
if(progress >= 1) {
clearInterval(intervalId);
}
}, 200);
*/
sending_form = true;
$('.job-submit').hide();
$('.jobs-sending').show();
var formData = new FormData($("form#jobs-modal-form")[0]);
$.ajax({
type: 'POST',
url: jpsd.ajaxurl,
data: formData,
processData: false,
contentType: false,
success: function (data) {
//clearInterval(intervalId);
//progressCRCL.svgDraw(1);
// Clear all smaces and newlines that can happen on response on some servers
data = data.replace(/\s/g, "");
if( data == 'ok' ){
//setTimeout(function(){
// $(self).find('.progress-button').addClass('success');
//}, 500);
//setTimeout(function(){
$(self).slideUp();
$('#job-apply-confirmation').slideDown();
//}, 1000);
}else{
//setTimeout(function(){
// $(self).find('.progress-button').addClass('error');
//}, 500);
//setTimeout(function(){
$('.jobs-sending').hide();
//}, 1000);
}
return false;
},
});
return false;
}
return false;
});
/*
$('.progress-button').on('click', function() {
var $button = $(this);
$(this).addClass('loading');
var $progress = $(this).find('.progress-circle');
var progress = 0;
var intervalId = setInterval(function() {
progress += Math.random() * 0.5;
$progress.svgDraw(progress);
if(progress >= 1) {
clearInterval(intervalId);
//console.log("cleared interval");
$button.removeClass('loading');
if($button.attr('data-result') == "true") {
$button.addClass('success');
}
else {
$button.addClass('error');
}
}
}, 300);
// Now that we finished, unbind
$(this).off('click');
});
*/
} // end .jobs-modal length
});
})(jQuery);

Related

How do I make this popup code pop 50% one site and 50% another site?

the following code is a pop up code that will pop a window for any URL given. I want to be able to use this code to pop 50% one site, and 50% another site. I am clueless as how I can do this. Any help would be appreciated!
<script type="text/javascript">var pics=[],stat=[],pic=[];</script>
<script type="text/javascript">
if (top.location != self.location)
top.location.replace(self.location);
</script>
<script>
var puShown = false;
var PopWidth = 1370;
var PopHeight = 800;
var PopFocus = 0;
var _Top = null;
function GetWindowHeight() {
var myHeight = 0;
if( typeof( _Top.window.innerHeight ) == 'number' ) {
myHeight = _Top.window.innerHeight;
} else if( _Top.document.documentElement && _Top.document.documentElement.clientHeight ) {
myHeight = _Top.document.documentElement.clientHeight;
} else if( _Top.document.body && _Top.document.body.clientHeight ) {
myHeight = _Top.document.body.clientHeight;
}
return myHeight;
}
function GetWindowWidth() {
var myWidth = 0;
if( typeof( _Top.window.innerWidth ) == 'number' ) {
myWidth = _Top.window.innerWidth;
} else if( _Top.document.documentElement && _Top.document.documentElement.clientWidth ) {
myWidth = _Top.document.documentElement.clientWidth;
} else if( _Top.document.body && _Top.document.body.clientWidth ) {
myWidth = _Top.document.body.clientWidth;
}
return myWidth;
}
function GetWindowTop() {
return (_Top.window.screenTop != undefined) ? _Top.window.screenTop : _Top.window.screenY;
}
function GetWindowLeft() {
return (_Top.window.screenLeft != undefined) ? _Top.window.screenLeft : _Top.window.screenX;
}
function doOpen(url)
{
var popURL = "about:blank"
var popID = "ad_" + Math.floor(89999999*Math.random()+10000000);
var pxLeft = 0;
var pxTop = 0;
pxLeft = (GetWindowLeft() + (GetWindowWidth() / 2) - (PopWidth / 2));
pxTop = (GetWindowTop() + (GetWindowHeight() / 2) - (PopHeight / 2));
if ( puShown == true )
{
return true;
}
var PopWin=_Top.window.open(popURL,popID,'toolbar=0,scrollbars=1,location=1,statusbar=1,menubar=0,resizable=1,top=' + pxTop + ',left=' + pxLeft + ',width=' + PopWidth + ',height=' + PopHeight);
if (PopWin)
{
puShown = true;
if (PopFocus == 0)
{
PopWin.blur();
if (navigator.userAgent.toLowerCase().indexOf("applewebkit") > -1)
{
_Top.window.blur();
_Top.window.focus();
}
}
PopWin.Init = function(e) {
with (e) {
Params = e.Params;
Main = function(){
if (typeof window.mozPaintCount != "undefined") {
var x = window.open("about:blank");
x.close();
}
var popURL = Params.PopURL;
try { opener.window.focus(); }
catch (err) { }
window.location = popURL;
}
Main();
}
};
PopWin.Params = {
PopURL: url
}
PopWin.Init(PopWin);
}
return PopWin;
}
function setCookie(name, value, time)
{
var expires = new Date();
expires.setTime( expires.getTime() + time );
document.cookie = name + '=' + value + '; path=/;' + '; expires=' + expires.toGMTString() ;
}
function getCookie(name) {
var cookies = document.cookie.toString().split('; ');
var cookie, c_name, c_value;
for (var n=0; n<cookies.length; n++) {
cookie = cookies[n].split('=');
c_name = cookie[0];
c_value = cookie[1];
if ( c_name == name ) {
return c_value;
}
}
return null;
}
function initPu()
{
_Top = self;
if (top != self)
{
try
{
if (top.document.location.toString())
_Top = top;
}
catch(err) { }
}
if ( document.attachEvent )
{
document.attachEvent( 'onclick', checkTarget );
}
else if ( document.addEventListener )
{
document.addEventListener( 'click', checkTarget, false );
}
}
function checkTarget(e)
{
if ( !getCookie('popundr') ) {
var e = e || window.event;
var win = doOpen('https://google.com');
setCookie('popundr', 1, 24*60*60*1000);
}
}
initPu();
</script>
The above code will pop google.com. I want to be able to pop google.com and yahoo.com 50% of the time each.
You can generate a random boolean and base it off that.
var win = doOpen(Math.random() >= 0.5 ? 'https://google.com' : 'https://othersite.com');
If you need it to be exactly 50%, then you can save the last result to localStorage and invert it each time:
const showGoogle = Boolean(localStorage.getItem('showGoogle'));
const win = doOpen(showGoogle ? 'https://google.com' : 'https://othersite.com');
localStorage.setItem('showGoogle', !showGoogle);

Make result letters bold as I type in searchbox

I am using Opencart v2.2.0. Search box is autocomplete and that part is alright. But now I need to make letters bold as I type in the search box.
Example:
The user starts typing "some", and as he types, the results are:
something
awesome
etc.
NOTICE: The words "something" and "awesome" are just an example, in real time I do not know what search terms would user type in.
So far I have this code, but as I am not really a js/jquery expert, I need help implementing the upper request. Thank you all.
//<![CDATA[
function doLiveSearch( ev, keywords ) {
if( ev.keyCode == 38 || ev.keyCode == 40 ) {
return false;
}
$('#autosearch_search_results').remove();
updown = -1;
if( keywords == '' || keywords.length < 2 ) {
return false;
}
keywords = encodeURI(keywords);
$.ajax({url: $('base').attr('href') + 'index.php?route=module/autosearch/ajax_asr&keyword=' + keywords, dataType: 'json', success: function(result) {
if( result.length > 0 ) {
var eList = document.createElement('ul');
eList.id = 'autosearch_search_results';
var eListElem;
var eLink;
var eImage;
for( var i in result ) {
eListElem = document.createElement('li');
eLink = document.createElement('a');
if( (result[i].thumb) != '' )
{
eImage = document.createElement('img');
eImage.src = result[i].thumb;
eLink.appendChild(eImage);
}
// name
var el_span = document.createElement('name');
var textNode = document.createTextNode(result[i].name);
eLink.appendChild(el_span);
el_span.appendChild(textNode);
// model
if( (result[i].model) != '' )
{
var el_span = document.createElement('model');
var textNode = document.createTextNode(result[i].model);
eLink.appendChild(el_span);
el_span.appendChild(textNode);
}
if( typeof(result[i].href) != 'undefined' ) {
eLink.href = result[i].href;
}
else {
eLink.href = $('base').attr('href') + 'index.php?route=product/product&product_id=' + result[i].product_id + '&keyword=' + keywords;
}
eListElem.appendChild(eLink);
if( (result[i].price) != '' )
{
var br = document.createElement("br");
eLink.appendChild(br);
// special price
if( (result[i].special) != '' )
{
var el_span = document.createElement('special-price');
var textNode = document.createTextNode(result[i].special);
eLink.appendChild(el_span);
el_span.appendChild(textNode);
}
// price
var el_span = document.createElement('price');
var textNode = document.createTextNode(result[i].price);
eLink.appendChild(el_span);
el_span.appendChild(textNode);
}
// quantity/stock
if( (result[i].stock) != '' )
{
var br = document.createElement("br");
eLink.appendChild(br);
eLink.appendChild( document.createTextNode(result[i].stock) );
}
eList.appendChild(eListElem);
}
if( $('#autosearch_search_results').length > 0 ) {
$('#autosearch_search_results').remove();
}
//view all results
if( (result[i].viewall) != '' )
{
eListElem = document.createElement('li');
eLink = document.createElement('a');
var el_span = document.createElement('viewall');
var textNode = document.createTextNode(result[i].viewall);
eLink.appendChild(el_span);
el_span.appendChild(textNode);
eLink.href = $('base').attr('href') + 'index.php?route=product/search&search=' + keywords;
eListElem.appendChild(eLink);
eList.appendChild(eListElem);
}
$('#search').append(eList);
}
}});
return true;
}
function upDownEvent( ev ) {
var elem = document.getElementById('autosearch_search_results');
var fkey = $('#search').find('[name=search]').first();
if( elem ) {
var length = elem.childNodes.length - 1;
if( updown != -1 && typeof(elem.childNodes[updown]) != 'undefined' ) {
$(elem.childNodes[updown]).removeClass('highlighted');
}
// Up
if( ev.keyCode == 38 ) {
updown = ( updown > 0 ) ? --updown : updown;
}
else if( ev.keyCode == 40 ) {
updown = ( updown < length ) ? ++updown : updown;
}
if( updown >= 0 && updown <= length ) {
$(elem.childNodes[updown]).addClass('highlighted');
var text = elem.childNodes[updown].childNodes[0].text;
if( typeof(text) == 'undefined' ) {
text = elem.childNodes[updown].childNodes[0].innerText;
}
}
}
return false;
}
var updown = -1;
$(document).ready(function(){
$('#search').find('[name=search]').attr('autocomplete', 'off'); //disable autocomplete
$('#search').find('[name=search]').first().keyup(function(ev){
doLiveSearch(ev, this.value);
}).focus(function(ev){
doLiveSearch(ev, this.value);
}).keydown(function(ev){
upDownEvent( ev );
}).blur(function(){
window.setTimeout("$('#autosearch_search_results').remove();updown=0;", 1500);
});
$(document).bind('keydown', function(ev) {
try {
if( ev.keyCode == 13 && $('.highlighted').length > 0 ) {
document.location.href = $('.highlighted').find('a').first().attr('href');
}
}
catch(e) {}
});
});
//]]>
just add a function that highlights all the searched text end run it on every text you add to your html:
function highlightQuery(string,searchQuery){
if(!string){
return "";
}
var expr = searchQuery;
expr = expr.replace(/\s+/, "|",searchQuery);
var regex = new RegExp(expr,"gi");
return string.replace(regex, function($1){
return '<span class="highlight">'+ $1 +'</span>';
});
}
We are trying to do the formatting part at javascript
so that only display should be done at HTML part
Execute the below function on typeahead ,and then you just need to display
the resultant array( formattedResult ) in HTML.
formattedResult will contain the formatted text.
While displaying formattedResult array in HTML , put 2nd position text
in bold of each iterated item.
Please try following code:-
//argument types searchList(Array) and searchWord(String)
function formatResult(searchList, searchWord ){
var formattedResult = [[]];
for(var prop in searchList){
if(searchList[prop].indexOf("some")!=-1)
{
var index= searchList[prop].indexOf(searchWord );
var temp = [];
temp.push(searchList[prop].substring(0,index));
temp.push(searchWord.toUpperCase());
temp.push(searchList[prop].substring(index + searchWord.length,
searchList[prop].length));
//console.log(temp);
formattedResult.push(temp);
}
else{
formattedResult.push(searchList[prop])
}
}
return formattedResult;
}

Checking form submission for minimum and maximum quantities

Working with an existing script that checks input values on form submission against existence of minimum quantity. I need to include a condition to check for the existence of maximum quantity and display an error message when the condition is not met. I believe it's a matter of editing the existing conditional logic but for the life of me I cannot get the edits to function without hosing up the functioning minimum condition. Rather than submitting my failed attempt at altering the code I'm submitting a functional version that only validates minimum quantities.
$('#button-cart').on('click', function() {
var total_quantity = 0;
var min_oneside = parseInt("<?php echo $min_oneside; ?>");
var min_bothside = parseInt("<?php echo $min_bothside; ?>");
var min_noprint = parseInt("<?php echo $min_noprint; ?>");
var min_standard = parseInt(" <?php echo $minimum; ?>");
var max_standard = parseInt(" <?php echo $maximum; ?>");
var validQty = true;
var validMaxQty = true;
var validInput = true;
var oth_minimum = "Quantity must be at least <?php echo $minimum; ?>";
var oth_maximum = "Quantity must be less than <?php echo $maximum; ?>"
$('#content').find('input[name^="option-quantity"]').each(function(){
total_quantity = total_quantity + parseInt($(this).val());
});
$('#content').find('input[name="quantity"]').each(function(){
total_quantity = total_quantity + parseInt($(this).val());
});
var element = $("label:contains('Printing')").attr('for');
if(element === undefined){
if( total_quantity < min_standard ) {
validQty = false;
validInput = false;
oth_minimum = "Quantity must be at least " + min_standard;
}else if (total_quantity > max_standard){
validQty = false;
validInput = false;
oth_message = oth_maximum;
}
} else {
if ( ($("#" + element + " option:selected").text()).match("Printed One Side") ){
if( total_quantity < min_oneside ) {
validQty = false;
validInput = false;
oth_minimum = "Quantity must be at least " + min_oneside;
}else if (total_quantity > max_standard){
validQty = false;
validInput = false;
oth_message = oth_maximum;
}
}
if ( ($("#" + element + " option:selected").text()).match("Printed Both Sides") ){
if( total_quantity < min_bothside ) {
validQty = false;
validInput = false;
oth_minimum = "Quantity must be at least " + min_bothside;
}else if (total_quantity > max_standard){
validQty = false;
validInput = false;
oth_message = oth_maximum;
}
}
if ( ($("#" + element + " option:selected").text()).match("No Printing") ){
if( total_quantity < min_noprint ) {
validQty = false;
validInput = false;
oth_minimum = "Quantity must be at least " + min_noprint;
}else if (total_quantity > max_standard){
validQty = false;
validInput = false;
oth_message = oth_maximum;
}
}
}
if(!validQty) {
$('#errorQuantity').html(oth_minimum);
}
var minimum = "Quantity must be at least <?php echo $minimum; ?>";
if($('#errorQuantity').length > 0 && validQty) {
var quantity = 0;
$('#errorQuantity').empty();
$('input[type=number]').each(function () {
var currentId = $(this).attr('id');
checkboxId = currentId.replace("quantity-", "");
if(isNaN($(this).val()) || $(this).val() < 0) {
$(this).focus();
$(this).css('background-color', 'red');
validInput = false;
} else {
quantity += parseInt($(this).val());
}
});
if(quantity <= 0) {
$('#errorQuantity').append(minimum);
validInput = false;
}
}
if(validInput){
$('input[type=number]').each(function () {
$(this).css('background-color', '#FFFFFF');
});
$('#errorQuantity').empty();
$.ajax({
url: 'index.php?route=checkout/cart/add',
type: 'post',
data: $('.product-info input[type=\'text\'], .product-info input[type=\'number\'], .product-info input[type=\'date\'], .product-info input[type=\'datetime\'], .product-info input[type=\'hidden\'], .product-info input[type=\'radio\']:checked, .product-info input[type=\'checkbox\']:checked, .product-info select, .product-info textarea'),
dataType: 'json',
beforeSend: function() {
$('#button-cart').attr('disabled', true);
$('#button-cart').after('<i class="fa fa-circle-o-notch fa-spin"></i>');
},
success: function(json) {
$('.alert, .text-danger').remove();
$('.form-group').removeClass('has-error');
$('#button-cart').next('.fa-spin').remove();
$('#button-cart').attr('disabled', false);
if (json['error']) {
var errors = '';
if (json['error']['option']) {
for (i in json['error']['option']) {
var element = $('#input-option' + i.replace('_', '-'));
element.parents('.form-group').first().find('> label + div').append('<div class="text-danger">' + json['error']['option'][i] + '</div>');
}
}
if (json['error']['recurring']) {
$('select[name="recurring_id"]').after('<span class="error">' + json['error']['recurring'] + '</span>');
}
// Highlight any found errors
$('.text-danger').each(function() {
$(this).parents('.form-group').first().addClass('has-error');
});
}
if (json['success']) {
$('.tb_widget_cart > .tb_nav').load('index.php?route=common/cart/info .tb_nav > *');
window.location = $('base').attr('href') + 'index.php?route=checkout/cart';
//displayNotice('product', 'success', 'product', json['success']);
}
}
});
}
});
Should be something like :
if(element === undefined){
if( total_quantity < min_standard ) {
validQty = false;
validInput = false;
oth_message = oth_minimum;
}else if (total_quantity > max_standard){
validQty = false;
validInput = false;
oth_message = oth_maximum;
}
} else {
if ( ($("#" + element + " option:selected").text()).match("Printed One Side") ){
if( total_quantity < min_oneside ) {
validQty = false;
validInput = false;
oth_message = "Quantity must be at least " + min_oneside;
}
}
if ( ($("#" + element + " option:selected").text()).match("Printed Both Sides") ){
if( total_quantity < min_bothside ) {
validQty = false;
validInput = false;
oth_message = "Quantity must be at least " + min_bothside;
}
}
if ( ($("#" + element + " option:selected").text()).match("No Printing") ){
if( total_quantity < min_noprint ) {
validQty = false;
validInput = false;
oth_message = "Quantity must be at least " + min_noprint;
}
}
}
if(!validQty) {
$('#errorQuantity').html(oth_message);
}
You can add in the same way for the other conditionals, I added only for the first one.

How to remove a property from an item which was added using jquery

The following jquery I am using in my jsp page for adding an autocomplete option to a text field which is having an id mytextfield.
jQuery(function(){
$("#mytextfield").autocomplete("popuppages/listall.jsp");
});
Within the same page, there are some cases in which I will have to remove this autocomplete feature from this text field. ( That is the same field will have to act as a textfield without autocomplete based on the user's inputs to previous fields and options)
Is there any way so that I could remove this newly added 'autocomplete' property from the particular item, that is from $("#mytextfield").
What actually I want to know is is there any option for removing added property
Incase anyone want to refer that autocomplete code, I have attached it below..
;(function($) {
$.fn.extend({
autocomplete: function(urlOrData, options) {
var isUrl = typeof urlOrData == "string";
options = $.extend({}, $.Autocompleter.defaults, {
url: isUrl ? urlOrData : null,
data: isUrl ? null : urlOrData,
delay: isUrl ? $.Autocompleter.defaults.delay : 10,
max: options && !options.scroll ? 10 : 150
}, options);
// if highlight is set to false, replace it with a do-nothing function
options.highlight = options.highlight || function(value) { return value; };
// if the formatMatch option is not specified, then use formatItem for backwards compatibility
options.formatMatch = options.formatMatch || options.formatItem;
return this.each(function() {
new $.Autocompleter(this, options);
});
},
result: function(handler) {
return this.bind("result", handler);
},
search: function(handler) {
return this.trigger("search", [handler]);
},
flushCache: function() {
return this.trigger("flushCache");
},
setOptions: function(options){
return this.trigger("setOptions", [options]);
},
unautocomplete: function() {
return this.trigger("unautocomplete");
}
});
$.Autocompleter = function(input, options) {
var KEY = {
UP: 38,
DOWN: 40,
DEL: 46,
TAB: 9,
RETURN: 13,
ESC: 27,
COMMA: 188,
PAGEUP: 33,
PAGEDOWN: 34,
BACKSPACE: 8
};
// Create $ object for input element
var $input = $(input).attr("autocomplete", "off").addClass(options.inputClass);
var timeout;
var previousValue = "";
var cache = $.Autocompleter.Cache(options);
var hasFocus = 0;
var lastKeyPressCode;
var config = {
mouseDownOnSelect: false
};
var select = $.Autocompleter.Select(options, input, selectCurrent, config);
var blockSubmit;
// prevent form submit in opera when selecting with return key
$.browser.opera && $(input.form).bind("submit.autocomplete", function() {
if (blockSubmit) {
blockSubmit = false;
return false;
}
});
// only opera doesn't trigger keydown multiple times while pressed, others don't work with keypress at all
$input.bind(($.browser.opera ? "keypress" : "keydown") + ".autocomplete", function(event) {
// a keypress means the input has focus
// avoids issue where input had focus before the autocomplete was applied
hasFocus = 1;
// track last key pressed
lastKeyPressCode = event.keyCode;
switch(event.keyCode) {
case KEY.UP:
event.preventDefault();
if ( select.visible() ) {
select.prev();
} else {
onChange(0, true);
}
break;
case KEY.DOWN:
event.preventDefault();
if ( select.visible() ) {
select.next();
} else {
onChange(0, true);
}
break;
case KEY.PAGEUP:
event.preventDefault();
if ( select.visible() ) {
select.pageUp();
} else {
onChange(0, true);
}
break;
case KEY.PAGEDOWN:
event.preventDefault();
if ( select.visible() ) {
select.pageDown();
} else {
onChange(0, true);
}
break;
// matches also semicolon
case options.multiple && $.trim(options.multipleSeparator) == "," && KEY.COMMA:
case KEY.TAB:
case KEY.RETURN:
if( selectCurrent() ) {
// stop default to prevent a form submit, Opera needs special handling
event.preventDefault();
blockSubmit = true;
return false;
}
break;
case KEY.ESC:
select.hide();
break;
default:
clearTimeout(timeout);
timeout = setTimeout(onChange, options.delay);
break;
}
}).focus(function(){
// track whether the field has focus, we shouldn't process any
// results if the field no longer has focus
hasFocus++;
}).blur(function() {
hasFocus = 0;
if (!config.mouseDownOnSelect) {
hideResults();
}
}).click(function() {
// show select when clicking in a focused field
if ( hasFocus++ > 1 && !select.visible() ) {
onChange(0, true);
}
}).bind("search", function() {
// TODO why not just specifying both arguments?
var fn = (arguments.length > 1) ? arguments[1] : null;
function findValueCallback(q, data) {
var result;
if( data && data.length ) {
for (var i=0; i < data.length; i++) {
if( data[i].result.toLowerCase() == q.toLowerCase() ) {
result = data[i];
break;
}
}
}
if( typeof fn == "function" ) fn(result);
else $input.trigger("result", result && [result.data, result.value]);
}
$.each(trimWords($input.val()), function(i, value) {
request(value, findValueCallback, findValueCallback);
});
}).bind("flushCache", function() {
cache.flush();
}).bind("setOptions", function() {
$.extend(options, arguments[1]);
// if we've updated the data, repopulate
if ( "data" in arguments[1] )
cache.populate();
}).bind("unautocomplete", function() {
select.unbind();
$input.unbind();
$(input.form).unbind(".autocomplete");
});
function selectCurrent() {
var selected = select.selected();
if( !selected )
return false;
var v = selected.result;
previousValue = v;
if ( options.multiple ) {
var words = trimWords($input.val());
if ( words.length > 1 ) {
var seperator = options.multipleSeparator.length;
var cursorAt = $(input).selection().start;
var wordAt, progress = 0;
$.each(words, function(i, word) {
progress += word.length;
if (cursorAt <= progress) {
wordAt = i;
return false;
}
progress += seperator;
});
words[wordAt] = v;
// TODO this should set the cursor to the right position, but it gets overriden somewhere
//$.Autocompleter.Selection(input, progress + seperator, progress + seperator);
v = words.join( options.multipleSeparator );
}
v += options.multipleSeparator;
}
$input.val(v);
hideResultsNow();
$input.trigger("result", [selected.data, selected.value]);
return true;
}
function onChange(crap, skipPrevCheck) {
if( lastKeyPressCode == KEY.DEL ) {
select.hide();
return;
}
var currentValue = $input.val();
if ( !skipPrevCheck && currentValue == previousValue )
return;
previousValue = currentValue;
currentValue = lastWord(currentValue);
if ( currentValue.length >= options.minChars) {
$input.addClass(options.loadingClass);
if (!options.matchCase)
currentValue = currentValue.toLowerCase();
request(currentValue, receiveData, hideResultsNow);
} else {
stopLoading();
select.hide();
}
};
function trimWords(value) {
if (!value)
return [""];
if (!options.multiple)
return [$.trim(value)];
return $.map(value.split(options.multipleSeparator), function(word) {
return $.trim(value).length ? $.trim(word) : null;
});
}
function lastWord(value) {
if ( !options.multiple )
return value;
var words = trimWords(value);
if (words.length == 1)
return words[0];
var cursorAt = $(input).selection().start;
if (cursorAt == value.length) {
words = trimWords(value)
} else {
words = trimWords(value.replace(value.substring(cursorAt), ""));
}
return words[words.length - 1];
}
// fills in the input box w/the first match (assumed to be the best match)
// q: the term entered
// sValue: the first matching result
function autoFill(q, sValue){
// autofill in the complete box w/the first match as long as the user hasn't entered in more data
// if the last user key pressed was backspace, don't autofill
if( options.autoFill && (lastWord($input.val()).toLowerCase() == q.toLowerCase()) && lastKeyPressCode != KEY.BACKSPACE ) {
// fill in the value (keep the case the user has typed)
$input.val($input.val() + sValue.substring(lastWord(previousValue).length));
// select the portion of the value not typed by the user (so the next character will erase)
$(input).selection(previousValue.length, previousValue.length + sValue.length);
}
};
function hideResults() {
clearTimeout(timeout);
timeout = setTimeout(hideResultsNow, 200);
};
function hideResultsNow() {
var wasVisible = select.visible();
select.hide();
clearTimeout(timeout);
stopLoading();
if (options.mustMatch) {
// call search and run callback
$input.search(
function (result){
// if no value found, clear the input box
if( !result ) {
if (options.multiple) {
var words = trimWords($input.val()).slice(0, -1);
$input.val( words.join(options.multipleSeparator) + (words.length ? options.multipleSeparator : "") );
}
else {
$input.val( "" );
$input.trigger("result", null);
}
}
}
);
}
};
function receiveData(q, data) {
if ( data && data.length && hasFocus ) {
stopLoading();
select.display(data, q);
autoFill(q, data[0].value);
select.show();
} else {
hideResultsNow();
}
};
function request(term, success, failure) {
if (!options.matchCase)
term = term.toLowerCase();
var data = cache.load(term);
// recieve the cached data
if (data && data.length) {
success(term, data);
// if an AJAX url has been supplied, try loading the data now
} else if( (typeof options.url == "string") && (options.url.length > 0) ){
var extraParams = {
timestamp: +new Date()
};
$.each(options.extraParams, function(key, param) {
extraParams[key] = typeof param == "function" ? param() : param;
});
$.ajax({
// try to leverage ajaxQueue plugin to abort previous requests
mode: "abort",
// limit abortion to this input
port: "autocomplete" + input.name,
dataType: options.dataType,
url: options.url,
data: $.extend({
q: lastWord(term),
limit: options.max
}, extraParams),
success: function(data) {
var parsed = options.parse && options.parse(data) || parse(data);
cache.add(term, parsed);
success(term, parsed);
}
});
} else {
// if we have a failure, we need to empty the list -- this prevents the the [TAB] key from selecting the last successful match
select.emptyList();
failure(term);
}
};
function parse(data) {
var parsed = [];
var rows = data.split("\n");
for (var i=0; i < rows.length; i++) {
var row = $.trim(rows[i]);
if (row) {
row = row.split("|");
parsed[parsed.length] = {
data: row,
value: row[0],
result: options.formatResult && options.formatResult(row, row[0]) || row[0]
};
}
}
return parsed;
};
function stopLoading() {
$input.removeClass(options.loadingClass);
};
};
$.Autocompleter.defaults = {
inputClass: "ac_input",
resultsClass: "ac_results",
loadingClass: "ac_loading",
minChars: 1,
delay: 400,
matchCase: false,
matchSubset: true,
matchContains: false,
cacheLength: 10,
max: 100,
mustMatch: false,
extraParams: {},
selectFirst: true,
formatItem: function(row) { return row[0]; },
formatMatch: null,
autoFill: false,
width: 0,
multiple: false,
multipleSeparator: ", ",
highlight: function(value, term) {
return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
},
scroll: true,
scrollHeight: 180
};
$.Autocompleter.Cache = function(options) {
var data = {};
var length = 0;
function matchSubset(s, sub) {
if (!options.matchCase)
s = s.toLowerCase();
var i = s.indexOf(sub);
if (options.matchContains == "word"){
i = s.toLowerCase().search("\\b" + sub.toLowerCase());
}
if (i == -1) return false;
return i == 0 || options.matchContains;
};
function add(q, value) {
if (length > options.cacheLength){
flush();
}
if (!data[q]){
length++;
}
data[q] = value;
}
function populate(){
if( !options.data ) return false;
// track the matches
var stMatchSets = {},
nullData = 0;
// no url was specified, we need to adjust the cache length to make sure it fits the local data store
if( !options.url ) options.cacheLength = 1;
// track all options for minChars = 0
stMatchSets[""] = [];
// loop through the array and create a lookup structure
for ( var i = 0, ol = options.data.length; i < ol; i++ ) {
var rawValue = options.data[i];
// if rawValue is a string, make an array otherwise just reference the array
rawValue = (typeof rawValue == "string") ? [rawValue] : rawValue;
var value = options.formatMatch(rawValue, i+1, options.data.length);
if ( value === false )
continue;
var firstChar = value.charAt(0).toLowerCase();
// if no lookup array for this character exists, look it up now
if( !stMatchSets[firstChar] )
stMatchSets[firstChar] = [];
// if the match is a string
var row = {
value: value,
data: rawValue,
result: options.formatResult && options.formatResult(rawValue) || value
};
// push the current match into the set list
stMatchSets[firstChar].push(row);
// keep track of minChars zero items
if ( nullData++ < options.max ) {
stMatchSets[""].push(row);
}
};
// add the data items to the cache
$.each(stMatchSets, function(i, value) {
// increase the cache size
options.cacheLength++;
// add to the cache
add(i, value);
});
}
// populate any existing data
setTimeout(populate, 25);
function flush(){
data = {};
length = 0;
}
return {
flush: flush,
add: add,
populate: populate,
load: function(q) {
if (!options.cacheLength || !length)
return null;
/*
* if dealing w/local data and matchContains than we must make sure
* to loop through all the data collections looking for matches
*/
if( !options.url && options.matchContains ){
// track all matches
var csub = [];
// loop through all the data grids for matches
for( var k in data ){
// don't search through the stMatchSets[""] (minChars: 0) cache
// this prevents duplicates
if( k.length > 0 ){
var c = data[k];
$.each(c, function(i, x) {
// if we've got a match, add it to the array
if (matchSubset(x.value, q)) {
csub.push(x);
}
});
}
}
return csub;
} else
// if the exact item exists, use it
if (data[q]){
return data[q];
} else
if (options.matchSubset) {
for (var i = q.length - 1; i >= options.minChars; i--) {
var c = data[q.substr(0, i)];
if (c) {
var csub = [];
$.each(c, function(i, x) {
if (matchSubset(x.value, q)) {
csub[csub.length] = x;
}
});
return csub;
}
}
}
return null;
}
};
};
$.Autocompleter.Select = function (options, input, select, config) {
var CLASSES = {
ACTIVE: "ac_over"
};
var listItems,
active = -1,
data,
term = "",
needsInit = true,
element,
list;
// Create results
function init() {
if (!needsInit)
return;
element = $("<div/>")
.hide()
.addClass(options.resultsClass)
.css("position", "absolute")
.appendTo(document.body);
list = $("<ul/>").appendTo(element).mouseover( function(event) {
if(target(event).nodeName && target(event).nodeName.toUpperCase() == 'LI') {
active = $("li", list).removeClass(CLASSES.ACTIVE).index(target(event));
$(target(event)).addClass(CLASSES.ACTIVE);
}
}).click(function(event) {
$(target(event)).addClass(CLASSES.ACTIVE);
select();
// TODO provide option to avoid setting focus again after selection? useful for cleanup-on-focus
input.focus();
return false;
}).mousedown(function() {
config.mouseDownOnSelect = true;
}).mouseup(function() {
config.mouseDownOnSelect = false;
});
if( options.width > 0 )
element.css("width", options.width);
needsInit = false;
}
function target(event) {
var element = event.target;
while(element && element.tagName != "LI")
element = element.parentNode;
// more fun with IE, sometimes event.target is empty, just ignore it then
if(!element)
return [];
return element;
}
function moveSelect(step) {
listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE);
movePosition(step);
var activeItem = listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE);
if(options.scroll) {
var offset = 0;
listItems.slice(0, active).each(function() {
offset += this.offsetHeight;
});
if((offset + activeItem[0].offsetHeight - list.scrollTop()) > list[0].clientHeight) {
list.scrollTop(offset + activeItem[0].offsetHeight - list.innerHeight());
} else if(offset < list.scrollTop()) {
list.scrollTop(offset);
}
}
};
function movePosition(step) {
active += step;
if (active < 0) {
active = listItems.size() - 1;
} else if (active >= listItems.size()) {
active = 0;
}
}
function limitNumberOfItems(available) {
return options.max && options.max < available
? options.max
: available;
}
function fillList() {
list.empty();
var max = limitNumberOfItems(data.length);
for (var i=0; i < max; i++) {
if (!data[i])
continue;
var formatted = options.formatItem(data[i].data, i+1, max, data[i].value, term);
if ( formatted === false )
continue;
var li = $("<li/>").html( options.highlight(formatted, term) ).addClass(i%2 == 0 ? "ac_even" : "ac_odd").appendTo(list)[0];
$.data(li, "ac_data", data[i]);
}
listItems = list.find("li");
if ( options.selectFirst ) {
listItems.slice(0, 1).addClass(CLASSES.ACTIVE);
active = 0;
}
// apply bgiframe if available
if ( $.fn.bgiframe )
list.bgiframe();
}
return {
display: function(d, q) {
init();
data = d;
term = q;
fillList();
},
next: function() {
moveSelect(1);
},
prev: function() {
moveSelect(-1);
},
pageUp: function() {
if (active != 0 && active - 8 < 0) {
moveSelect( -active );
} else {
moveSelect(-8);
}
},
pageDown: function() {
if (active != listItems.size() - 1 && active + 8 > listItems.size()) {
moveSelect( listItems.size() - 1 - active );
} else {
moveSelect(8);
}
},
hide: function() {
element && element.hide();
listItems && listItems.removeClass(CLASSES.ACTIVE);
active = -1;
},
visible : function() {
return element && element.is(":visible");
},
current: function() {
return this.visible() && (listItems.filter("." + CLASSES.ACTIVE)[0] || options.selectFirst && listItems[0]);
},
show: function() {
var offset = $(input).offset();
element.css({
width: typeof options.width == "string" || options.width > 0 ? options.width : $(input).width(),
top: offset.top + input.offsetHeight,
left: offset.left
}).show();
if(options.scroll) {
list.scrollTop(0);
list.css({
maxHeight: options.scrollHeight,
overflow: 'auto'
});
if($.browser.msie && typeof document.body.style.maxHeight === "undefined") {
var listHeight = 0;
listItems.each(function() {
listHeight += this.offsetHeight;
});
var scrollbarsVisible = listHeight > options.scrollHeight;
list.css('height', scrollbarsVisible ? options.scrollHeight : listHeight );
if (!scrollbarsVisible) {
// IE doesn't recalculate width when scrollbar disappears
listItems.width( list.width() - parseInt(listItems.css("padding-left")) - parseInt(listItems.css("padding-right")) );
}
}
}
},
selected: function() {
var selected = listItems && listItems.filter("." + CLASSES.ACTIVE).removeClass(CLASSES.ACTIVE);
return selected && selected.length && $.data(selected[0], "ac_data");
},
emptyList: function (){
list && list.empty();
},
unbind: function() {
element && element.remove();
}
};
};
$.fn.selection = function(start, end) {
if (start !== undefined) {
return this.each(function() {
if( this.createTextRange ){
var selRange = this.createTextRange();
if (end === undefined || start == end) {
selRange.move("character", start);
selRange.select();
} else {
selRange.collapse(true);
selRange.moveStart("character", start);
selRange.moveEnd("character", end);
selRange.select();
}
} else if( this.setSelectionRange ){
this.setSelectionRange(start, end);
} else if( this.selectionStart ){
this.selectionStart = start;
this.selectionEnd = end;
}
});
}
var field = this[0];
if ( field.createTextRange ) {
var range = document.selection.createRange(),
orig = field.value,
teststring = "<->",
textLength = range.text.length;
range.text = teststring;
var caretAt = field.value.indexOf(teststring);
field.value = orig;
this.selection(caretAt, caretAt + textLength);
return {
start: caretAt,
end: caretAt + textLength
}
} else if( field.selectionStart !== undefined ){
return {
start: field.selectionStart,
end: field.selectionEnd
}
}
};
})(jQuery);
Looks like you are looking for destroy or disable method of autocomplete..
Check Documentation...
destroy
disable
$("#mytextfield").autocomplete( "destroy" )
$("#mytextfield").autocomplete( "disable" )
The difference is after destroy you cannot enable it back...but after disable by using enable you can enable it back..
You can use .removeAttr()
$(target).removeAttr('propertyName');
This will totally remove that property.
But if you want to change any property then use .prop() or .attr()

Any Good Number Picker for JQuery (or Javascript)?

Are there any good number picker for jquery (or standalone js)?
I would like a number picker where there is a max and min number that the user can choose from. Also, it have other options such as displaying odd number or even number or prime number or a range of number whereby some numbers in between are skipped.
Using a select to do this you can create an array with the numbers to skip and do a for loop to write the options:
int minNumber = 0;
int maxNumber = 10;
int[] skipThese = { 5, 7 };
for (int i = minNumber; i <= maxNumber; i++)
{
if(!skipThese.Contains(i)) Response.Write(String.Concat("<option value=\"", i, "\">", i, "</option>"));
}
You can do this with razor or any other way to output the HTML.
You can also do this with jQuery, dynamicaly, following the same idea:
$(document).ready(function() {
var minNumber = 0;
var maxNumber = 10;
var skipThese = [5, 7];
for (var i = minNumber; i <= maxNumber; i++) {
if ($.inArray(i, skipThese) == -1) $('#selectListID').append("<option value=\"" + i + "\">" + i + "</option>");
}
});
Edit:
Or you can use the C# code above in an aspx page and load it with AJAX from the page:
Create a select box in the page:
<select name="numPicker" id="numPicker">
<option>Loading...</option>
</select>
In a script in this page you could use jQuery's ajax() to fetch the data and populate the <select>:
$(document).ready(function() {
var numPickerSelect = $("#numPicker");
$.ajax({
url: 'url/to/page.aspx',
type: 'post'
success: function(data) {
numPickerSelect.find('option').remove(); // Remove the options in the select field
numPickerSelect.append(data); // Load the content generated by the server into the select field
},
error: function() {
alert('An error has ocurred!');
}
});
//Or use this (not sure if will work)
numPickerSelect.load("url/to/page.aspx");
});
I have used this. You should be able to modify to add extra options such as min and max fairly easily.
// Make a control only accept numeric input
// eg, $("#myedit").numeric()
// $("#myedit").numeric({alow: ' ,.'})
// $("#myedit").numeric({decimals: 2})
(function($) {
$.fn.alphanumeric = function(p) {
if (p == 'destroy') {
$(this).unbind('keypress');
$(this).unbind('blur');
return;
}
p = $.extend({
ichars: "!##$%^&*()+=[]\\\';,/{}|\":<>?~`.- ",
nchars: "",
allow: "",
decimals: null
}, p);
return this.each
(
function() {
if (p.nocaps) p.nchars += "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
if (p.allcaps) p.nchars += "abcdefghijklmnopqrstuvwxyz";
s = p.allow.split('');
for (i = 0; i < s.length; i++) if (p.ichars.indexOf(s[i]) != -1) s[i] = "\\" + s[i];
p.allow = s.join('|');
var reg = new RegExp(p.allow, 'gi');
var ch = p.ichars + p.nchars;
ch = ch.replace(reg, '');
var dp = p.decimals;
var isInteger = function(val) {
var objRegExp = /(^-?\d\d*$)/;
return objRegExp.test(val);
};
var isNumeric = function(val) {
// If the last digit is a . then add a 0 before testing so if they type 25. it will be accepted
var lastChar = val.substring(val.length - 1);
if (lastChar == ".") val = val + "0";
var objRegExp = new RegExp("^\\s*-?(\\d+(\\.\\d{1," + dp + "})?|\\.\\d{1," + dp + "})\\s*$", "g");
if (dp == -1)
objRegExp = new RegExp("^\\s*-?(\\d+(\\.\\d{1,25})?|\\.\\d{1,25})\\s*$", "g");
var result = objRegExp.test(val);
return result;
};
$(this).blur(function(e) {
var text = $(this).val();
if (dp != null) {
if (dp == 0) {
if (!isInteger(text)) {
$(this).val('');
e.preventDefault();
}
}
else {
if (!isNumeric(text)) {
$(this).val('');
e.preventDefault();
}
}
} else {
var c = text.split('')
for (i = 0; i < text.length; i++) {
if (ch.indexOf(c[i]) != -1) {
$(this).val('');
e.preventDefault();
};
}
}
});
$(this).keypress
(
function(e) {
switch (e.which) {
//Firefox fix, for ignoring specific presses
case 8: // backspace key
return true;
case 46: // delete key
return true;
};
if (dp != null) {
if (e.which == 32) { e.preventDefault(); return false; }
var range = getRange(this);
var typed = String.fromCharCode(e.which);
var text = $(this).val().substr(0, range.start) + typed + $(this).val().substr(range.start);
if (dp == 0) {
if (!isInteger(text)) e.preventDefault();
}
else {
if (!isNumeric(text)) e.preventDefault();
}
return;
}
if (!e.charCode) k = String.fromCharCode(e.which);
else k = String.fromCharCode(e.charCode);
if (ch.indexOf(k) != -1) e.preventDefault();
if (e.ctrlKey && k == 'v') e.preventDefault();
}
);
$(this).bind('contextmenu', function() { return false });
}
);
};
$.fn.numeric = function(p) {
if (p == 'destroy') {
$(this).unbind('keypress');
$(this).unbind('blur');
return;
}
var az = "abcdefghijklmnopqrstuvwxyz";
az += az.toUpperCase();
var opts = {};
if (!isNaN(p)) {
opts = $.extend({
nchars: az
}, { decimals: p });
} else {
opts = $.extend({
nchars: az
}, p);
}
return this.each(function() {
$(this).alphanumeric(opts);
}
);
};
$.fn.integer = function(p) {
if (p == 'destroy') {
$(this).unbind('keypress');
$(this).unbind('blur');
return;
}
var az = "abcdefghijklmnopqrstuvwxyz";
az += az.toUpperCase();
p = {
nchars: az,
allow: '-',
decimals: 0
};
return this.each(function() {
$(this).alphanumeric(p);
}
);
};
$.fn.alpha = function(p) {
if (p == 'destroy') {
$(this).unbind('keypress');
$(this).unbind('blur');
return;
}
var nm = "1234567890";
p = $.extend({
nchars: nm
}, p);
return this.each(function() {
$(this).alphanumeric(p);
}
);
};
})(jQuery);

Categories

Resources