I've created a custom US telephone mask on input using jQuery like -
(___) ___-____
It's working fine on keydown event.
var telMask = "(___) ___-____";
var phoneNumberBuffer = "";
$(document).ready(function () {
$(".telephone").focus(function () { handleFocus(this); });
$(".telephone").blur(function () { handleBlur(this); });
$(".telephone").keydown(function (event) { formatPhoneNumber(this, event); });
});
function mergePhoneMask() {
var tempMask = telMask;
var tempPos;
for (var i = 0; i < phoneNumberBuffer.length; i++) {
tempPos = tempMask.indexOf("_");
tempMask = tempMask.substr(0, tempPos) + phoneNumberBuffer.charAt(i) + tempMask.substr(tempPos + 1);
}
return tempMask;
}
function setPhoneNumCursor(elem) {
var position = $(elem).val().indexOf("_");
if (position < 0) { position = $(elem).val().length; }
if (elem.setSelectionRange) {
elem.focus();
elem.setSelectionRange(position, position);
}
else if (elem.createTextRange) {
var range = elem.createTextRange();
range.collapse(true);
range.moveEnd('character', position);
range.moveStart('character', position);
range.select();
}
}
function formatPhoneNumber(elem, e) {
var tempMask = telMask;
var tempPos;
if (e.which == 8) {
phoneNumberBuffer = phoneNumberBuffer.substr(0, phoneNumberBuffer.length - 1);
elem.value = mergePhoneMask();
}
if ((e.which > 47 && e.which < 58) || (e.which > 95 && e.which < 106)) {
if (phoneNumberBuffer.length < 10) {
// numpad keys don't match to charcode
if (e.which > 95 && e.which < 106) {
phoneNumberBuffer += (e.which - 96).toString();
} else {
phoneNumberBuffer += String.fromCharCode(e.which);
}
elem.value = mergePhoneMask();
}
}
//e.preventDefault();
if (phoneNumberBuffer.length == 10 || e.which == 9) {
//$(elem).parent().next().next().find("input").focus();
} else {
setPhoneNumCursor(elem);
}
}
function handleFocus(elem) {
if (elem.value == "") {
elem.value = telMask;
}
setPhoneNumCursor(elem);
}
function handleBlur(elem) {
if (elem.value == telMask) {
elem.value = "";
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div class="control-input">
<input name="telephone" maxlength="14" class="telephone" type="tel" size="14" autocomplete="tel">
</div>
Problem is, while continuing to press the backspace/delete, it removes the "(" at the beginning. I'm not sure if I missed anything here! I've some limitations to use other plugins. Thanks!
I've created a JSFiddle here!
Related
I have some java script to help the user with the phone number and prevent the form from being submitted in till the field has a valid phone number.
How ever even with a valid number it keeps telling me to use the format thats already predetermined. What am I doing worng im going to assume it has something to do with the pattern.
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], factory);
} else if (typeof exports === 'object') {
// Node/CommonJS
factory(require('jquery'));
} else {
// Browser globals
factory(jQuery);
}
}(function ($) {
var ua = navigator.userAgent,
iPhone = /iphone/i.test(ua),
chrome = /chrome/i.test(ua),
android = /android/i.test(ua),
caretTimeoutId;
$.mask = {
//Predefined character definitions
definitions: {
'9': "[0-9]",
'a': "[A-Za-z]",
'*': "[A-Za-z0-9]"
},
autoclear: true,
dataName: "rawMaskFn",
placeholder: '_'
};
$.fn.extend({
//Helper Function for Caret positioning
caret: function(begin, end) {
var range;
if (this.length === 0 || this.is(":hidden") || this.get(0) !== document.activeElement) {
return;
}
if (typeof begin == 'number') {
end = (typeof end === 'number') ? end : begin;
return this.each(function() {
if (this.setSelectionRange) {
this.setSelectionRange(begin, end);
} else if (this.createTextRange) {
range = this.createTextRange();
range.collapse(true);
range.moveEnd('character', end);
range.moveStart('character', begin);
range.select();
}
});
} else {
if (this[0].setSelectionRange) {
begin = this[0].selectionStart;
end = this[0].selectionEnd;
} else if (document.selection && document.selection.createRange) {
range = document.selection.createRange();
begin = 0 - range.duplicate().moveStart('character', -100000);
end = begin + range.text.length;
}
return { begin: begin, end: end };
}
},
unmask: function() {
return this.trigger("unmask");
},
mask: function(mask, settings) {
var input,
defs,
tests,
partialPosition,
firstNonMaskPos,
lastRequiredNonMaskPos,
len,
oldVal;
if (!mask && this.length > 0) {
input = $(this[0]);
var fn = input.data($.mask.dataName)
return fn?fn():undefined;
}
settings = $.extend({
autoclear: $.mask.autoclear,
placeholder: $.mask.placeholder, // Load default placeholder
completed: null
}, settings);
defs = $.mask.definitions;
tests = [];
partialPosition = len = mask.length;
firstNonMaskPos = null;
mask = String(mask);
$.each(mask.split(""), function(i, c) {
if (c == '?') {
len--;
partialPosition = i;
} else if (defs[c]) {
tests.push(new RegExp(defs[c]));
if (firstNonMaskPos === null) {
firstNonMaskPos = tests.length - 1;
}
if(i < partialPosition){
lastRequiredNonMaskPos = tests.length - 1;
}
} else {
tests.push(null);
}
});
return this.trigger("unmask").each(function() {
var input = $(this),
buffer = $.map(
mask.split(""),
function(c, i) {
if (c != '?') {
return defs[c] ? getPlaceholder(i) : c;
}
}),
defaultBuffer = buffer.join(''),
focusText = input.val();
function tryFireCompleted(){
if (!settings.completed) {
return;
}
for (var i = firstNonMaskPos; i <= lastRequiredNonMaskPos; i++) {
if (tests[i] && buffer[i] === getPlaceholder(i)) {
return;
}
}
settings.completed.call(input);
}
function getPlaceholder(i){
if(i < settings.placeholder.length)
return settings.placeholder.charAt(i);
return settings.placeholder.charAt(0);
}
function seekNext(pos) {
while (++pos < len && !tests[pos]);
return pos;
}
function seekPrev(pos) {
while (--pos >= 0 && !tests[pos]);
return pos;
}
function shiftL(begin,end) {
var i,
j;
if (begin<0) {
return;
}
for (i = begin, j = seekNext(end); i < len; i++) {
if (tests[i]) {
if (j < len && tests[i].test(buffer[j])) {
buffer[i] = buffer[j];
buffer[j] = getPlaceholder(j);
} else {
break;
}
j = seekNext(j);
}
}
writeBuffer();
input.caret(Math.max(firstNonMaskPos, begin));
}
function shiftR(pos) {
var i,
c,
j,
t;
for (i = pos, c = getPlaceholder(pos); i < len; i++) {
if (tests[i]) {
j = seekNext(i);
t = buffer[i];
buffer[i] = c;
if (j < len && tests[j].test(t)) {
c = t;
} else {
break;
}
}
}
}
function androidInputEvent(e) {
var curVal = input.val();
var pos = input.caret();
if (oldVal && oldVal.length && oldVal.length > curVal.length ) {
// a deletion or backspace happened
checkVal(true);
while (pos.begin > 0 && !tests[pos.begin-1])
pos.begin--;
if (pos.begin === 0)
{
while (pos.begin < firstNonMaskPos && !tests[pos.begin])
pos.begin++;
}
input.caret(pos.begin,pos.begin);
} else {
var pos2 = checkVal(true);
var lastEnteredValue = curVal.charAt(pos.begin);
if (pos.begin < len){
if(!tests[pos.begin]){
pos.begin++;
if(tests[pos.begin].test(lastEnteredValue)){
pos.begin++;
}
}else{
if(tests[pos.begin].test(lastEnteredValue)){
pos.begin++;
}
}
}
input.caret(pos.begin,pos.begin);
}
tryFireCompleted();
}
function blurEvent(e) {
checkVal();
if (input.val() != focusText)
input.change();
}
function keydownEvent(e) {
if (input.prop("readonly")){
return;
}
var k = e.which || e.keyCode,
pos,
begin,
end;
oldVal = input.val();
//backspace, delete, and escape get special treatment
if (k === 8 || k === 46 || (iPhone && k === 127)) {
pos = input.caret();
begin = pos.begin;
end = pos.end;
if (end - begin === 0) {
begin=k!==46?seekPrev(begin):(end=seekNext(begin-1));
end=k===46?seekNext(end):end;
}
clearBuffer(begin, end);
shiftL(begin, end - 1);
e.preventDefault();
} else if( k === 13 ) { // enter
blurEvent.call(this, e);
} else if (k === 27) { // escape
input.val(focusText);
input.caret(0, checkVal());
e.preventDefault();
}
}
function keypressEvent(e) {
if (input.prop("readonly")){
return;
}
var k = e.which || e.keyCode,
pos = input.caret(),
p,
c,
next;
if (e.ctrlKey || e.altKey || e.metaKey || k < 32) {//Ignore
return;
} else if ( k && k !== 13 ) {
if (pos.end - pos.begin !== 0){
clearBuffer(pos.begin, pos.end);
shiftL(pos.begin, pos.end-1);
}
p = seekNext(pos.begin - 1);
if (p < len) {
c = String.fromCharCode(k);
if (tests[p].test(c)) {
shiftR(p);
buffer[p] = c;
writeBuffer();
next = seekNext(p);
if(android){
//Path for CSP Violation on FireFox OS 1.1
var proxy = function() {
$.proxy($.fn.caret,input,next)();
};
setTimeout(proxy,0);
}else{
input.caret(next);
}
if(pos.begin <= lastRequiredNonMaskPos){
tryFireCompleted();
}
}
}
e.preventDefault();
}
}
function clearBuffer(start, end) {
var i;
for (i = start; i < end && i < len; i++) {
if (tests[i]) {
buffer[i] = getPlaceholder(i);
}
}
}
function writeBuffer() { input.val(buffer.join('')); }
function checkVal(allow) {
//try to place characters where they belong
var test = input.val(),
lastMatch = -1,
i,
c,
pos;
for (i = 0, pos = 0; i < len; i++) {
if (tests[i]) {
buffer[i] = getPlaceholder(i);
while (pos++ < test.length) {
c = test.charAt(pos - 1);
if (tests[i].test(c)) {
buffer[i] = c;
lastMatch = i;
break;
}
}
if (pos > test.length) {
clearBuffer(i + 1, len);
break;
}
} else {
if (buffer[i] === test.charAt(pos)) {
pos++;
}
if( i < partialPosition){
lastMatch = i;
}
}
}
if (allow) {
writeBuffer();
} else if (lastMatch + 1 < partialPosition) {
if (settings.autoclear || buffer.join('') === defaultBuffer) {
// Invalid value. Remove it and replace it with the
// mask, which is the default behavior.
if(input.val()) input.val("");
clearBuffer(0, len);
} else {
// Invalid value, but we opt to show the value to the
// user and allow them to correct their mistake.
writeBuffer();
}
} else {
writeBuffer();
input.val(input.val().substring(0, lastMatch + 1));
}
return (partialPosition ? i : firstNonMaskPos);
}
input.data($.mask.dataName,function(){
return $.map(buffer, function(c, i) {
return tests[i]&&c!=getPlaceholder(i) ? c : null;
}).join('');
});
input
.one("unmask", function() {
input
.off(".mask")
.removeData($.mask.dataName);
})
.on("focus.mask", function() {
if (input.prop("readonly")){
return;
}
clearTimeout(caretTimeoutId);
var pos;
focusText = input.val();
pos = checkVal();
caretTimeoutId = setTimeout(function(){
if(input.get(0) !== document.activeElement){
return;
}
writeBuffer();
if (pos == mask.replace("?","").length) {
input.caret(0, pos);
} else {
input.caret(pos);
}
}, 10);
})
.on("blur.mask", blurEvent)
.on("keydown.mask", keydownEvent)
.on("keypress.mask", keypressEvent)
.on("input.mask paste.mask", function() {
if (input.prop("readonly")){
return;
}
setTimeout(function() {
var pos=checkVal(true);
input.caret(pos);
tryFireCompleted();
}, 0);
});
if (chrome && android)
{
input
.off('input.mask')
.on('input.mask', androidInputEvent);
}
checkVal(); //Perform initial check for existing values
});
}
});
}));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<?php
session_start();
$token= md5(uniqid());
$_SESSION['delete_customer_token']= $token;
session_write_close();
?>
<!DOCTYPE html>
<head>
<title>index</title>
<script src="js/jquery-1.9.0.min.js" type="text/javascript" charset="utf-8"></script>
<script src="js/jquery.maskedinput.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$.mask.definitions['~'] = "[+-]";
$("#phone").mask("1 (999) 999-9999");
$("input").blur(function() {
$("#info").html("Unmasked value: " + $(this).mask());
}).dblclick(function() {
$(this).unmask();
});
});
</script>
</head>
<body>
<form id="msform" method="post" action=""/>
<input type="hidden" name="token" value="<?php echo $token; ?>"/>
<input type="hidden" name="miles" value=""/>
<div id="formwrap">
<div id="ftx1">FIRST NAME</div>
<input type="text" name="fname" class="box" maxlength="40" min="9" max="40" placeholder=""/>
</div>
<div id="formwrap">
<div id="ftx1">LAST NAME</div>
<input type="text" name="lname" class="box" maxlength="40" min="9" max="40" placeholder=""/>
</div>
<div id="formwrap">
<div id="ftx1">BUSINESS NAME:</div>
<input id="busname" name="busname" class="element text medium" type="text" maxlength="40" value="" placeholder=""/>
</div>
<div id="formwrap">
<div id="ftx1">TYPE OF BUSINESS:*</div>
<input id="bustype" type="bustype" name="bustype" size="" maxLength="64"
placeholder=""
title="">
</div>
<div id="formwrap">
<div id="ftx1">EMAIL: *</div>
<input id="email" type="" name="email" size="" maxLength="64"
placeholder=""
title="Please provide only a email address" novalidate/>
</div>
<div id="formwrap">
<div id="ftx1">PHONE NUMBER: *</div>
<input id="phone" name="phone" class="element text medium" maxlength="" value="" placeholder="PHONE NUMBER" type="tel" pattern="[\+]\d{2}[\(]\d{2}[\)]\d{4}[\-]\d{4}" title="Phone Number Format:1 (614) 000-0000" />
</div>
<br><br><br><br>
<input id="submit" class="button_text" type="submit" name="submit" value="SUBMIT" />
<div id="error"></div>
<h2>contact you within 24h. Thank You!</h2>
</form>
</body>
</html>
Your regular expression and field mask combination is incorrect.
[\+]\d{2}[\(]\d{2}[\)]\d{4}[\-]\d{4} will never match because (a) your mask is configured for North American-style phone numbers (it will match phone numbers in the same format as +91(12)3456-7890), and (b) your mask is not configured with a + at the beginning of the input.
You may be looking for something similar to the following to validate the field itself:
1 \(\d{3}\) \d{3}\-\d{4}
Regex101
I have one function for the number input box come with + and - button on the sides, and copy the code in my shopify theme which I use. But that function only show one time. But I need those apply to all the product offers.
(function ($) {
$.fn.bootstrapNumber = function (options) {
var settings = $.extend({
upClass: 'default',
downClass: 'default',
center: true
}, options);
return this.each(function (e) {
var self = $(this);
var clone = self.clone();
var min = self.attr('min');
var max = self.attr('max');
function setText(n) {
if ((min && n < min) || (max && n > max)) {
return false;
}
clone.focus().val(n);
return true;
}
var group = $("<div class='input-group'></div>");
var down = $("<button type='button'>-</button>").attr('class', 'btn btn-' + settings.downClass).click(function () {
setText(parseInt(clone.val()) - 1);
});
var up = $("<button type='button'>+</button>").attr('class', 'btn btn-' + settings.upClass).click(function () {
setText(parseInt(clone.val()) + 1);
});
$("<span class='input-group-btn'></span>").append(down).appendTo(group);
clone.appendTo(group);
if (clone) {
clone.css('text-align', 'center');
}
$("<span class='input-group-btn'></span>").append(up).appendTo(group);
// remove spins from original
clone.prop('type', 'text').keydown(function (e) {
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
(e.keyCode == 65 && e.ctrlKey === true) ||
(e.keyCode >= 35 && e.keyCode <= 39)) {
return;
}
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
var c = String.fromCharCode(e.which);
var n = parseInt(clone.val() + c);
//if ((min && n < min) || (max && n > max)) {
// e.preventDefault();
//}
});
clone.prop('type', 'text').blur(function (e) {
var c = String.fromCharCode(e.which);
var n = parseInt(clone.val() + c);
if ((min && n < min)) {
setText(min);
}
else if (max && n > max) {
setText(max);
}
});
self.replaceWith(group);
});
};
}(jQuery));
How do you initialise the function ?
Your problem certainly lies there...
Because it works using this:
$('input').bootstrapNumber();
See my Fiddle that includes your exact unmodified script.
Friends ,I have a text box for date to be inserted by the user but i want it to allow user to insert only "dd" ,"mm" and "yyyy" values ,slashes(/)should be already present and as soon as the user inserts "dd" values the pointer should move directly behind the slash for "mm" value and on pressing backspace it should delete the "mm" or "dd "values not the slashes(/).
Here is what i have tried but it does not give me the desired result-
function dateCheck(){
var d_value=$("#pdate").val();
if(d_value.length =="2" || d_value.length =="5")
{
$('#pdate').val($('#pdate').val()+"/");
}
}
html code-
Date:<input type="text" name="p_date" id="pdate" onkeydown="dateCheck()" placeholder="DD/MM/YYYY" required />
There's probably plugins out there, but nobody's been too forthcoming with any. Here's something I've knocked up during my lunch break :).
It's not perfect, and could be improved with some tweaking. For example, highlighting multiple characters for deletion is a bit screwy, but hopefully it's not a bad starter for 10. Credit to this post for getting/setting the caret position. Also, it does allow invalid dates right now - 12/34/5678. It wouldn't be too difficult to sort that out. I might stick something on Git and finish it off when I get home.
I've hard-coded it for dd/mm/yyyy format, but, again, with improvments, it could use the user locale.
$.fn.textboxDatePicker = function() {
var _getCaret = function(el) {
if (el.selectionStart) {
return el.selectionStart;
} else if (document.selection) {
el.focus();
var r = document.selection.createRange();
if (r == null) {
return 0;
}
var re = el.createTextRange(), rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint('EndToStart', re);
return rc.text.length;
}
return 0;
};
var _setCaretPosition = function(elem, caretPos) {
if (caretPos == 2 || caretPos == 5) {
caretPos++;
}
if (elem != null) {
if (elem.createTextRange) {
var range = elem.createTextRange();
range.move('character', caretPos);
range.select();
} else {
if (elem.selectionStart) {
elem.focus();
elem.setSelectionRange(caretPos, caretPos);
}
else elem.focus();
}
}
};
$(this).val('dd/mm/yyyy');
$(this).on("keydown", function(e) {
var keyCode = e.which || e.charCode || e.keyCode;
var key = String.fromCharCode(keyCode);
// arrows, home, end
if ([35, 36].indexOf(keyCode) > -1) {
return true;
}
if (keyCode == 37) {
var newCaretPos = _getCaret(this) - 1;
if ([2, 5].indexOf(newCaretPos) > -1) {
_setCaretPosition(this, newCaretPos - 1);
return false;
}
return true;
}
if (keyCode == 39) {
var newCaretPos = _getCaret(this) + 1;
if ([2, 5].indexOf(newCaretPos) > -1) {
_setCaretPosition(this, newCaretPos + 1);
return false;
}
return true;
}
// backspace
if (keyCode == 8) {
var text = this.value;
var caret = _getCaret(this);
if (caret == 3 || caret == 6) {
caret = caret - 2;
} else {
caret--;
}
if (caret < 0) {
return false;
}
var output = text.substring(0, caret);
key = 'd';
if (caret > 2) {
key = 'm'
};
if (caret > 4) {
key = 'y'
};
this.value = output + key + text.substring(caret + 1);
_setCaretPosition(this, caret);
return false;
}
if (/[0-9]/.test(key)) {
var text = this.value;
var caret = _getCaret(this);
if (caret > 9) {
return false;
}
var output = text.substring(0, caret);
this.value = output + key + text.substring(caret + 1);
_setCaretPosition(this, caret + 1);
}
return false;
});
};
$('.date').textboxDatePicker();
UPDATE
Might be overthinking this. Could you just use 3 separate boxes and style them to look like one, with a little JS to sort out focusing between them?
https://jsfiddle.net/w9by2350/3/
MUCH cleaner!
Try it
function datecheck(){
value=$(#input_id).val();
if(value.match(/^\d\d?\/\d\d?\/\d\d\d\d$/){
return true;
}else{
alert("not valid format")
}
}
I have a script that converts "Enter" to "Tab", and it works great until I hit a hidden field on a form.
So, is there any way to detect the hidden field, and still use the script(in IE & firefox)?
<script type="text/javascript">
function tabE(obj, e) {
var e = (typeof event != 'undefined') ? window.event : e; // IE : Moz
if (e.keyCode == 13) {
var ele = document.forms[0].elements;
for (var i = 0; i < ele.length; i++) {
var q = (i == ele.length - 1) ? 0 : i + 1; // if last element : if any other
if (obj == ele[i]) {
ele[q].focus();
break
}
}
return false;
}
}
</script>
Change your code to look like the following:
<script type="text/javascript">
function tabE(obj, e) {
var e = (typeof event != 'undefined') ? window.event : e; // IE : Moz
if (e.keyCode == 13) {
var ele = document.forms[0].elements;
for (var i = 0; i < ele.length; i++) {
var q = (i == ele.length - 1) ? 0 : i + 1; // if last element : if any other
if (obj == ele[i] && $(ele[q]).is(":visible")) {
ele[q].focus();
break
}
}
return false;
}
}
</script>
I just added a check to make sure the element you're about to focus is visible (not hidden).
EDIT: If you want to skip hidden fields entirely, use the below code.
function tabE(obj, e) {
var e = (typeof event != 'undefined') ? window.event : e; // IE : Moz
var self = $(obj),
form = self.parents('form:eq(0)'),
focusable, next;
if (e.keyCode == 13) {
focusable = form.find('input,a,select,button,textarea').filter(':visible');
next = focusable.eq(focusable.index(obj) + 1);
if (!next.length) {
next = focusable.first();
}
next.focus();
return false;
}
}
Fiddle:
https://jsfiddle.net/mwatz122/0zqzzmc1/
My proposal is full js:
function tabE(obj, e) {
var e = (typeof event != 'undefined') ? window.event : e; // IE : Moz
if (e.keyCode == 13) {
var ele = document.forms[0].elements;
for (var i = 0; i < ele.length; i++) {
var q = (i == ele.length - 1) ? 0 : i + 1; // if last element : if any other
if (obj == ele[i]) {
var style = window.getComputedStyle(ele[q]);
while (style.display == 'none' || style.visibility != 'visible' || ele[q].type == 'hidden') {
q = (q == ele.length - 1) ? 0 : q + 1; // if last element : if any other
style = window.getComputedStyle(ele[q]);
}
ele[q].focus();
break
}
}
return false;
}
}
window.onload = function() {
var inp = document.getElementsByTagName("input")
for(i=0; i<inp.length; i++) {
inp[i].addEventListener("keyup", function(e) {
tabE(this, e);
});
}
}
<form>
First name:<br>
<input type="text" name="firstname">
<br>
Last name:<br>
<input type="text" name="lastname">
<input type="text" name="myhidden" style="visibility: hidden">
<input type="hidden" name="myhidden1">
<input type="text" name="myhidden2" style="display: none">
</form>
too much recursion error occur when i execute autocomplete.js today.Before today i never see like this error in jquery when i execute autocomplete.js. i am using jQuery 1.7.2
$(function(){
$("#search_text").keyup(function(e){
var sVal = $(this).val();
if(e.which == 27) {
$('#sresult_container').remove();
return;
}
if(e.which != 40 && e.which != 38) {
$("#search").removeAttr('disabled');
$.post('http://localhost/website/index.php/search/ajaxResults',{Search:sVal},function(data){
if(data != "$$$" && data.length != 0) {
var sData = data;
var flag1 = 0;
var flag2 = 0;
var tabindex = -1;
var aFarray = sData.split('$$$');
$('#sresult_container').remove();
var $sresult_container = $('<div id="sresult_container"></div>')
.css({'position':'absolute','border':'1px solid','background-color':'white','z-index':'10000000','width':'309px'});
for(var i=0;i<aFarray.length;i++) {
var a = aFarray[i].split('|||');
if(i == 0 && a[0] != "") {
flag1 = 1;
$pages = $('<div id="pages"></div>');
$text1 = $('<p></p>').css({'background-color':'silver','text-align':'center','padding':'3px'}).text("Pages");
$pages.append($text1);
if(a.length > 5) {
a = a.slice(0,5);
}
for(var j=1;j<a.length+1;j++) {
tabindex++;
$('<div>/div>').css({'padding':'5px','text-align':'center'}).text(a[j-1]).attr({'tabindex':tabindex,'class':'result'}).appendTo($pages);
}
}
if(i == 1 && a[0] != "") {
flag2 = 1;
$articles = $('<div id="articles"></div>');
$text2 = $("<p></p>").css({'background-color':'silver','text-align':'center','padding':'3px'}).text("Articles");
$articles.append($text2);
if(a.length > 5) {
a = a.slice(0,5);
}
for(var j=0;j<a.length;j++) {
tabindex++;
$('<div></div>').css({'padding':'5px','text-align':'center'}).text(a[j]).attr({'tabindex':tabindex,'class':'result'}).appendTo($articles);
}
}
}
if(flag1 == 0)
{
$articles.children().first().remove();
$div = $sresult_container.append($articles);
}else if(flag2 == 0)
{
$pages.children().first().remove();
$div = $sresult_container.append($pages);
}else
{
$div = $sresult_container.append($pages,$articles);
}
tabindex++;
$allresluts = $('<div id="allresults"></div>').css({'padding':'5px','text-align':'center','background-color':'#FBEE92','color':'#CC3333'}).text("See All Results").attr('tabindex',tabindex).appendTo($div);
var bottom = $('#search_text').offset();
var height = $('#search_text').outerHeight();
var left = bottom.left;
var top = bottom.top+height;
$div.offset({'top':top,'left':left});
$('body').append($div);
}
else
{
$('#sresult_container').remove();
$("#search").attr('disabled','true');
}
});
}
else
{
$con_div = $('#sresult_container').children().children('div').add($('#sresult_container').children().last());
var tabindex = $con_div.length - 1;
if(e.which == 40)
{
$con_div.first().addClass("selected").focus();
var index = $con_div.first().index(this)+1;
$con_div.bind({
keydown: function(e) {
e.preventDefault();
var key = e.keyCode;
var target = $(e.target);
switch(key) {
case 38: // arrow up
if(index == 0)
{
index = tabindex+1;
}
$con_div[--index].focus();
break;
case 40: // arrow down
if(index > tabindex-1)
{
index = -1;
}
$con_div[++index].focus();
break;
case 13: //Enter
if(target.hasClass('result') == true)
{
$("#search_text").val(target.text());
$("#search").focus();
}
else
{
$('#search').click();
}
$div.remove();
break;
case 27://Esc
$div.remove();
$("#search_text").focus();
break;
}
},
focusin: function(e) {
$(e.currentTarget).addClass("selected");
},
focusout: function(e) {
$con_div.removeClass("selected");
$(e.currentTarget).removeClass("selected");
}
});
}
}
setTimeout(function()
{
$con_div = $('#sresult_container').children().children('div').add($('#sresult_container').children().last());
$con_div.live({
click : function(e){
var $target = $(e.target);
if($target.hasClass('result') == true)
{
$("#search_text").val($target.text());
$("#search").focus();
}
else
{
$('#search').click();
}
$('#sresult_container').remove();
},
mouseover : function(e){
var $target = $(e.target);
if($target.hasClass('result') == true || $target.is('#allresults'))
{
$(e.target).css('cursor','pointer');
$con_div.removeClass("selected");
$(e.target).addClass("selected");
}
},
mouseout : function(){
$con_div.removeClass("selected");
}
});
}, 200 );
});
$("#search_text").blur(function(e){
$con_div = $('#sresult_container').children().children('div').add($('#sresult_container').children().last());
if($con_div.hasClass('selected') != true)
{
$("#sresult_container").remove();
}
});
});
I got error in $('#search').click(); inside the code.