Min length of input (searchbox) - javascript

I need to add a popup window event to my search system - when a customer hit only 2 characters it should popup a small table with alert e. g. "You must enter at least 3 characters when searching..." and the background should be greyed out.
Is this possible for me? Here is my javascript code for searching (in table):
/*** SEARCHBOX ***/
//define the table search object, which can implement both functions and properties
window.tableSearch = {};
//initialize the search, setup the current object
tableSearch.init = function() {
//define the properties I want on the tableSearch object
this.Rows = document.getElementById('data').getElementsByTagName('TR');
this.RowsLength = tableSearch.Rows.length;
this.RowsText = [];
//loop through the table and add the data to the table search object
for (var i = 0; i < tableSearch.RowsLength; i++) {
this.RowsText[i] = (tableSearch.Rows[i].innerText) ? tableSearch.Rows[i].innerText.toUpperCase() : tableSearch.Rows[i].textContent.toUpperCase();
}
}
//onlys shows the relevant rows as determined by the search string
tableSearch.runSearch = function() {
//get the search term
this.Term = document.getElementById('searchbox').value.toUpperCase();
//loop through the rows and hide rows that do not match the search query
for (var i = 0, row; row = this.Rows[i], rowText = this.RowsText[i]; i++) {
row.style.display = ((rowText.indexOf(this.Term) != -1) || this.Term === '') ? '' : 'none';
}
}
//handles the enter key being pressed
tableSearch.search = function(e) {
//checks if the user pressed the enter key, and if they did then run the search
var keycode;
if (window.event) { keycode = window.event.keyCode; }
else if (e) { keycode = e.which; }
else { return false; }
if (keycode == 13) {
tableSearch.runSearch();
}
else { return false; }
}
And here is my html code (search box):
<table border="0" cellpadding="0" cellspacing="0">
<tbody><tr><td>
<input id="searchbox" size="25" maxlength="100" value="search..." style="color: gray;" name="Search" onkeyup="tableSearch.search(event)" onfocus="if(this.value == 'search...') {this.value=''}" onblur="if(this.value == ''){this.value ='search...'}" type="text" />
<input class="button_searchbox" value="Search" onclick="tableSearch.runSearch();" type="button" />
</td></tr></tbody>
</table><br />
Any ideas? Thx

This is a little example using part of your code, and a simple div as a popup:
function doSearch(event)
{
var keycode;
if (window.event) { keycode = window.event.keyCode; }
else if (e) { keycode = e.which; }
else { return false; }
if (keycode == 13)
{
if (this.searchbox.value.length > 2)
{
console.log("Searching...");
}
else
{
document.getElementById("divPopup").style.display = "block";
}
}
else
{
document.getElementById("divPopup").style.display = "none";
return false;
}
}
Div:
<div id="divPopup">You must enter at least 3 characters when searching...</div>
CSS:
#divPopup
{
color: grey;
font-family: Verdana;
font-size: 10px;
border: 1px solid black;
width: 200px;
display: none;
}
JSFiddle: http://jsfiddle.net/hescano/9NFqL/

In your runSearch function, after the statement
this.Term = document.getElementById('searchbox').value.toUpperCase();
check the length of the search term
if (this.Term.length() < 3){
alert('You must enter at least 3 characters when searching...');
return;
}
Thats all.

Related

Validating a form

IM working on a simple form, and Im trying to validate the fields,
with below code I able to validate the field and add a message if the field is empty.
}
First you need to scan the page for labels:
var labels = document.getElementsByTagName('LABEL');
for (var i = 0; i < labels.length; i++) {
if (labels[i].htmlFor != '') {
var elem = document.getElementById(labels[i].htmlFor);
if (elem)
elem.label = labels[i];
}
}
Then you can simply use following in your IF-ELSE condition,
document.getElementById(id).label.classList.add('red-text');
and
document.getElementById(id).label.classList.remove('red-text');
I also added CSS class for the text to be red.
.red-text {
color: #ff0000;
}
Final code:
function validation(id) {
var labels = document.getElementsByTagName('LABEL');
for (var i = 0; i < labels.length; i++) {
if (labels[i].htmlFor != '') {
var elem = document.getElementById(labels[i].htmlFor);
if (elem)
elem.label = labels[i];
}
}
var value = document.getElementById(id).value;
if (value === "" || value == null) {
document.getElementById('Err' + id).innerHTML = "- Field Required";
document.getElementById(id).classList.add('class');
document.getElementById(id).label.classList.add('red-text');
} else {
document.getElementById('Err' + id).innerHTML = "";
document.getElementById(id).classList.remove('class');
document.getElementById(id).label.classList.remove('red-text');
}
}
.class {
background: #f97d7d;
color: #ff0000;
border: 1px solid #ff0000 !important;
}
.red-text {
color: #ff0000;
}
<label for="Name">* Name <span class="error" id="ErrName"></span></label>
<input type="text" name="Name" id="Name" onblur="validation('Name')">
Change your javascript code to following:
function validation(id) {
var value = document.getElementById(id).value;
if (value === "" || value == null) {
document.getElementById('Err' + id).innerHTML = "- Field Required";
document.getElementById(id).classList.add('class');
var label = findLabel(document.getElementById('Name'));
label.classList.add('class');
} else {
document.getElementById('Err' + id).innerHTML = "";
document.getElementById(id).classList.remove('class');
var label = findLabel(document.getElementById('Name'));
label.classList.remove('class');
}
}
function findLabel(el) {
var idVal = el.id;
labels = document.getElementsByTagName('label');
for (var i = 0; i < labels.length; i++) {
if (labels[i].htmlFor == idVal)
return labels[i];
}
}
.class
{
background: #f97d7d;
color: #ff0000;
border: 1px solid #ff0000 !important;
}
<label class="" for="Name">* Name <span class="error" id="ErrName"></span></label>
<input type="text" name="Name" id="Name" onblur="validation('Name')">
I've added a function findLable to get the label for that input, and using that, added error class to that label.
The span is defined as class "error" but you haven't defined that class.
I think it is better to bind blur and input events
the code:
Name.addEventListener('blur', function(){
if (!Name.value){
ErrName.innerHTML="Field Required";
this.classList.add('class');
ErrName.parentNode.style.color="red";
}
});
Name.addEventListener('input',function(){
if (Name.value.length && ErrName.innerHTML=="Field Required" ){
ErrName.innerHTML="";
this.classList.remove('class');
ErrName.parentNode.style.color="black";
}
});
a liddle fiddle

Jquery:Registration Number Validation on Keypress

I everyone I have a text-box
Number : <input type="text" name="Number" placeholder="MH03AH6414" id="txtRegNo" />
<span id="errmsg"></span>
The text-box must take value like the placeholder input(1st two character alphabet (a-z or A-Z) 2nd two character number (0-9) the 3rd two character alphabet (a-z or A-Z) and last four character number (0-9)
I have tried to do with key-press event and all but not formed properly
$("#txtRegNo").keypress(function (e) {
var dataarray = [];
var dInput = $(this).val();
for (var i = 0, charsLength = dInput.length; i < charsLength; i += 1) {
dataarray .push(dInput.substring(i, i + 1));
}
alert(dataarray);
alert(e.key);
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
$("#errmsg").html("Digits Only").show().fadeOut("slow");
return false
}
});
Please help me.
Thanks in advance
I tried of focusout which now works fine with me but I want to prevent from keyinput
Here is the jsfiddle solution
http://jsfiddle.net/ntywf/2470/
Try this out. Modified the function as per requirement
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
Number : <input type="text" name="Number" placeholder="MH03AH6414" id="txtRegNo" />
<span id="errmsg"></span>
<!-- end snippet -->
<script>
$("#txtRegNo").keyup(function (e) {
$("#errmsg").html('');
var validstr = '';
var dInput = $(this).val();
var numpattern = /^\d+$/;
var alphapattern = /^[a-zA-Z]+$/;
for (var i = 0; i < dInput.length;i++) {
if((i==2||i==3||i==6||i==7)){
if(numpattern.test(dInput[i])){
console.log('validnum'+dInput[i]);
validstr+= dInput[i];
}else{
$("#errmsg").html("Digits Only").show();
}
}
if((i==0||i==1||i==4||i==5)){
if(alphapattern.test(dInput[i])){
console.log('validword'+dInput[i]);
validstr+= dInput[i];
}else{
$("#errmsg").html("ALpahbets Only").show();
}
}
}
$(this).val(validstr);
return false;
});
</script>

auto tabbing on the first textbox isnt working

the following is code is used to create a credit card. My only promblem is that auto tabbing doesnt work for my textbox with the id of card.i have a external file for the auto tabbing and i have attached the code under the html code.Thanks in advance.
<head>
<title>Credit Card</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.min.js"></script>
<script src="jquery.autotab.js"></script>
<script src="Jstepper.js"></script>
</head>
</body oncopy="return false" oncut="return false" onpaste="return false">
<style>
#Month{
width: 20px;
}
#Year{
width: 40px;
}
#Cvc{
width: 30px;
}
</style>
<p>Payment:
Credit card<input type="radio" id='radio_1' name='payment' value="credit">
<div class="text1">
<form name="cardForm" method="post">
<p>Card number:<input type="text" name="FirstField" id='card' value=""
onKeyup="autotab(this,document.cardForm.SecondField)" maxlength=16 >
Expiration: Month:-<input type="text" name="SecondField" id='Month' value=""
onKeyup="autotab(this,document.cardForm.ThirdField)" maxlength=2 >
Year:-<input type="text" id='Year' name="ThirdField" value="" onKeyup="autotab(this, document.cardForm.FourthField)"maxlength=4></p>
3 digit CVC:-<input type="text" name="FourthField" id='Cvc' value="" maxlength=3></p>
</form>
</div>
</body>
<!--Jump when expiration number is typed-->
<!--month and year-->
<!--exp date has to greater than or equal to current date -->
<!--on every keypress check if the length is 16-->
<!--macthes-->
<!-- Import numeric from src folder-->
<script src="numeric.js"></script>
<script>
//autotab doesnt work for the first feild
//can still copy and paste text
$(document).ready(function () {
$(".text1").hide();
$("#radio_1").click(function () {
<!--passes card id to keypress function-->
$('#card').keypress();
//disable copy and paste
$('#card').bind();
$('#Month').keypress();
$('#Month').bind();
$('#Month').jStepper({minValue:0, maxValue:12});
$('#Year').keypress();
$('#Year').bind();
$('#Cvc').keypress();
$('#Cvc').bind();
$(".text1").show();
});
});
</script>
<html>
/*
Auto tabbing script- By JavaScriptKit.com
http://www.javascriptkit.com
This credit MUST stay intact for use
*/
function autotab(original,destination){
if (original.getAttribute&&original.value.length==original.getAttribute("maxlength"))
destination.focus()
}
my isnumeric file
$(this).keypress(function (e) {
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
return false;
}
});
//check for the type of credit card and prints to console
$(this).keypress(function (e) {
var input = document.getElementById('card');
input.onkeyup = function() {
if(input.value.length == 16){
var str = input.value;
var VisaRegx = /^4[0-9]{6,}$/i;
var Visafound = str.match(VisaRegx);
if(Visafound != null){
console.log("Visa Found");
}
var MasterRegx = /^5[1-5][0-9]{5,}$/i;
var Masterfound = str.match(MasterRegx);
if(Masterfound != null){
console.log("Master Card Found");
}
var AmericanExpressRegx = /^3[47][0-9]{5,}$/i;
var AmericanExpressfound = str.match(AmericanExpressRegx);
if(AmericanExpressfound != null){
console.log("American Express Card Found");
}
//^(?:2131|1800|35[0-9]{3})[0-9]{3,}$
var DinersClubRegx = /^3(?:0[0-5]|[68][0-9])[0-9]{4,}$/i;
var DinersClubfound = str.match(DinersClubRegx);
if(DinersClubfound != null){
console.log("Diners Club Card Found");
}
var DiscoverRegx = /^6(?:011|5[0-9]{2})[0-9]{3,}$/i;
var Discoverfound = str.match(DiscoverRegx);
if(Discoverfound != null){
console.log("Discover Card Found");
}
var JcbRegx = /^(?:2131|1800|35[0-9]{3})[0-9]{3,}$/i;
var Jcbfound = str.match(JcbRegx);
if(Jcbfound != null){
console.log("Jcb Card Found");
}
}
}
});
//checks for credit card expiration
$(this).keypress(function (e) {
var Monthinput = document.getElementById('Month').value;
var Yearinput = document.getElementById('Year').value;
var today = new Date();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(Yearinput.length == 4){
if(yyyy > Yearinput){
console.log("The card is expired cause of the year");
}
}
if(Yearinput.length == 4 && Monthinput.length == 2){
if(yyyy == Yearinput && mm > Monthinput){
console.log("The card is expired cause of the current month");
}
}
});
//Disable copy and paste
$(this).bind("cut copy paste",function(e) {
e.preventDefault();
});

onBlur change textbox background color

How can i change my textbox background and border color if return true from the function ? if return false my textbox background border will change, but when return true it remain red color. how can i fix this ? any help will be appreciated.
Javascript
function checkPostcode()
{
var message = "";
if (document.mainform.POSTCODE.value.length != 5)
{
message += "Invalid entry. Postcode must be in 5 number.";
}
else
{
for (var i = 0; i < document.mainform.POSTCODE.value.length; i++)
{
var f = document.mainform.POSTCODE.value.charAt(i);
if (!(parseFloat(f) >= 0) || !(parseFloat(f) <= 9))
{
var jdap = "no";
}
}
if (jdap=="no")
{
message += "Invalid entry. Please enter numbers only.";
}
}
if (message != "")
{
document.getElementById("posterrMsg").innerHTML = message;
document.getElementById("posterrMsg").style.display = "inline";
document.getElementById("POSTCODE").style.border = "thin solid red";
document.getElementById("POSTCODE").style.background = "#FFCECE";
document.mainform.POSTCODE.value = "";
document.mainform.POSTCODE.focus();
return false;
}
else{
document.getElementById("posterrMsg").innerHTML = "";
document.getElementById("posterrMsg").style.display = "";
document.getElementById("POSTCODE").style.border = "thin solid #CCCCCCC";
document.getElementById("POSTCODE").style.background = "FFFFFF";
return true;
}
}
HTML
<label id="posterrMsg" class="errMsg"></label>
<input type="text" name="POSTCODE" id="POSTCODE" value="<%=POSTCODE%>" onblur="checkPostcode();" maxlength="5" />
Just change
document.getElementById("POSTCODE").style.border = "thin solid #CCCCCCC";
to
document.getElementById("POSTCODE").style.border = "";
Another option:
document.getElementById("POSTCODE").className = "validPostcode";
or
document.getElementById("POSTCODE").className = "invalidPostcode";
If you want to add more styling.
Both are valid options here.
I would refactor your code a bit and maybe create an outer function which calls checkPostcode for validation.
Use !== so
if (message !== "")
so that you are checking the same type and value.
You also had a couple of typeos in your background colours.
See working JSFiddle here

Opening input when writing #Q# in textarea

I have textarea. Now, I want to do that once you write "#q + number#" ( e.g. #q1# ), it will create new input field.
For example if you write: "Hello my name is #q1# and my favorite food is #q2#". It will open two input fields.
And when you delete one of those #q + number#, it will delete the same field that was intended to the #q#
For example: if you write "Hello my name is #q1# and my favorite food is #q2#, and the input fields look like that:
<input type="text" q="1" />
<input type="text" q="2" />
and next that I delete the #q1# it supposed to look like that:
and don't delete the value of q="2" input.
How can I do that in jQuery/JavaScript?
Take a look at this quick fiddle http://jsfiddle.net/NgxvP/1/
Here you have something to start playing with
<html>
<head>
<style>
#inputField { position:relative;
width: 200px;
height: 200px;
background-color: #cda;
}
</style>
<script src="jquery-1.7.1.min.js"></script>
<script>
// in_array function provided by phpjs.org
function in_array (needle, haystack, argStrict)
{
var key = '',
strict = !! argStrict;
if (strict)
{
for (key in haystack)
{
if (haystack[key] === needle)
{
return true;
}
}
}
else
{
for (key in haystack)
{
if (haystack[key] == needle)
{
return true;
}
}
}
return false;
}
var addedFields = new Array();
function checkFields(input, charCode)
{
var text = (charCode) ? input.value + String.fromCharCode(charCode) : input.value;
var pattern = /#q[0-9]#/g;
var matches = text.match(pattern);
if (!matches) { matches = new Array(); }
if (addedFields.length>0 && addedFields.length != matches.length)
{
for (var index in addedFields)
{
if (!in_array('#q'+ index +'#', matches))
{
$('#q'+index).remove();
delete addedFields[index];
}
}
}
if (matches)
{
for (var i=0; i<matches.length; i++)
{
var code = matches[i];
var index = code.match(/[0-9]/)[0];
if ( $('#q'+index).length == 0 )
{
addFields(index);
}
}
}
}
function addFields(i)
{
addedFields[i] = true;
var fields = '';
for (var index in addedFields)
{
fields += '<input type="text" q="'+ index +'" id="q'+ index +'" />';
}
$('#inputField').html(fields);
}
</script>
</head>
<body>
<div id="formID">
<form>
<textarea onkeypress="checkFields(this, event.charCode); return true;" onkeyup="checkFields(this); return true;"></textarea>
<div id="inputField"></div>
</form>
</div>
</body>
</html>
EDITED: to avoid appending unordered input text fields, but showing them always ordered by their index, as commented in dfsq answer
I created a jsfiddle for your convenience http://jsfiddle.net/2HA5s/

Categories

Resources