search should start only after entering 3 characters in any field - javascript

I am using Spring MVC,hibernate and JSP in my application.
Currently I have implemented functionality of search for multiple fields and I have called it on onKeyUp() function using JavaScript.
But now I want it to perform search only if there are atleast 3 characters in any field.
for example if there are 3 fields then if i enter 1 or 2 characters in one/two field and 3 characters in third field then it should call search method only on basis on 3rd field and it should ignore the input from other fields.
What will be the easy way to achieve this?

If I understand you correctly, you want to only execute the search functionality if one of multiple fields contain 3 or more characters.
Based off of solely that assumption and no other details something along the following should work:
$('.fields').each(function(k, v){
var obj = $(this);
obj.keyup(function(){
if(obj.val().length >= 3){
// Execute submission
alert(obj.val());
}
});
});
Working Example: http://jsfiddle.net/FtE9H/
The above code assumes that you have assigned a class of fields to the desired fields that should be checked to execute the search functionality. This could be modified to only look at specific element types but that is up to your full implementation.
In addition, you could empty the other fields on a successful match for a value with a length of 3 or more characters to avoid any possible confusion with your end users.

Related

JavaScript to check first word in a textarea of a form

Is it possible using Javascript (or any other language if not) to detect if a user types in the word URGENT (any case) or *URGENT* as the first word in a text field?
If so, could I get the form to pop up a message either on submit or when they type it asking them politely not to start their call with this? If they include the word anywhere else then this is fine, it's just at the start that we don't want it. Thank you.
With some little research you can know that the answer to your question is yes.
Your question has been asked and answered many times, therefore it will better for your learning expericence to do some research about it.
How? Kindly read:
developer.mozilla String/indexOf
Javascript indexOf case insensitive
//first step, catch the text that user has entered from an input with the id someTextField
var str1 =document.getElementById("someTextField").value;
//assign some values to search for, words listed here will trigger the alert.
var wordsToFind = ["urgent", "*urgent*"];
//for now, we will take the user's input, str1, and convert it to lower case, then try to check if the first word (indexOf)the words to find is 0. 0 means at the beginning of the text.
//find first word in array
if (str1.toLowerCase().indexOf(wordsToFind[0]) === 0
//find second word in array by adding OR ||
|| str1.toLowerCase().indexOf(wordsToFind[1]) === 0) {
//display a message to inform the user.
alert("Kindly you can not start a message with the word 'urgent'");
}
If you have many words, then you can put them all in the array and loop through it and try to see if the user's text contain any of the blacklisted words.
First, you will need to get the text from the textbox with something like
var s = document.getElementById('myTextBox').value;
Once you have that, there are a number of ways you could check to see if it starts with the word "URGENT". One example would be
var containsUrgent = s.substr(0, 6).toUpperCase() === 'URGENT';
Once you've done that, the simplest way to display the message on the screen would be
alert('The string in the textbox starts with URGENT');
This is not a best practice, but it should help you get started.
If you want to alert the message when the user types or submits the form, you can attach your code to the submit and keypress events.

Input field to only accept a specific number

I have created a form and now I want to add an input field inside it which would only accept a specific number i.e. the digit '4'. This is more like a spam check where the user is asked that 'What is the answer of 1+3?' and then he/she would've to enter the digit '4', in the input field, in order for the form to get processed. This could also work in a manner that if any other number is entered inside the input field and the form is submitted, a pop up window is fired explaining the error.
I have created a jsfiddle which only accepts the digit 4 but sadly it is allow accepting 'full stops'.
HTML:
<input id="humancheck" type="text" maxlength="1" name="humancheck" required />
Javascript:
jQuery('#humancheck').keyup(function () {
this.value = this.value.replace(/[^4-4\.]/g,'');
});
Your regex should only be replacing [^4] (any character which is not 4). I'm not sure why you have also included -4 (range) and \. ('.' character).
Just to note, securing on keyup doesn't help much. Anyone can fire up webkit inspector and place a 3 in there manually. If this is just a fun experiment, though, that's cool too :)
I know this post is a bit moldy, so I thought I might bring it a bit more current.
First, you should not use the 'keyup' for the event trigger, as it is to processor intensive. Imagine if you were wanting to match a number with more than one digit, and you can see how the 'keyup' becomes problematic.
Using the 'blur' event is a better trigger, as it checks the number value after the user has finished entering a number into the form field.
If I am understanding the OP, then why use a regex at all for a simple
match? Instead, this is one way I would write your function (for jQuery 1.11.0+). It also makes an additional check to assure the entry is indeed a number as well.
$('#humancheck').blur( function(){
if (isNaN(this.value)) alert('Not a Number');
if (this.value != 4) alert('Incorrect Number');
});

Validate beginning of input field with multiple values

I have a login form that users are constantly getting wrong. We are working on better informing the users but we would also like to hint them in the correct direction as they type in the input field.
All IDs are 10 characters and they start one of 4 different ways:
A00
B00
CTR
VST
I would like to hint users if they don't start with one of those 4 options, likely by triggering a hidden element to reveal itself that reminds them what a username looks like.
Most of the jQuery I can figure out, the only part I can't is the actual matching. I'm not really sure how to write the RegEx to make it work.
This will match a correct string
^((A00)|(B00)|(CTR)|(VST)).*$
In JavaScript
if (txt.search(/^((A00)|(B00)|(CTR)|(VST)).*$/) !== -1) {...}

check text area for certain character combinations

I have a text area which gets filled in various ways including paste, keyboard input, from an autocomplete etc.
Now I want to validate this text area and if contains any combination, including multiples of some characters and if so, set it to empty.
The characters I want to filter are: tabs, new lines, spaces, carriage returns, as well as some watermark text - basically any non-meaningful character.
Note that valid text might contain special characters such as ()!#%<>,;:/||{}[] and possibly a few more.
Valid values might contain new lines, spaces etc. but will also have other valid characters (the stuff above plus 0-9, a-z, A-Z etc.)
Currently, I have the following wrapped in a jquery .change event:
<textarea cols="70" rows="3" class="cssTextarea cptEntryArea formFocus"></textarea>
$('.cptEntryArea').live('change', function(e)
{
var myval = "";
myval = $(this).val().trim();
myval.replace(/\r\n|\r|\n|\u0085|\u000C|\u2028|\u2029|^\s*$|^\s+|\s+$/g, "");
if ((myval == watermarkText) || (myval.length == 0))
{
$(this).val("");
e.stopPropagation();
return false;
};
});
The idea is to simply blank it out if it has "non-visual" characters in it in any combination.
Any optimization or better method to get this done?
EDIT1: Looks like I can do some adjustment here as the jQuery trim is:
trim: function( text ) {
return (text || "").replace( /^\s+|\s+$/g, "" );
}
Sounds like a very strange thing to do. What is the watermarkText for? Would it not be a better idea to catch before the text is put into the textarea i.e. on keydown, return null if the ascii value < 33? Your event only fires when the item is changed/lost focus, not immediately when some text is entered.
You could try doing /mg for the regex multi-line.
As it ended up, I had to manage my keystrokes more efficiently as well as the event management of the end result. My solution is a quite complex interactive page where multiple methods are used to populate the value with configurable options of which group of methods and the acceptable values that are allowed, thus the complexity of the resolution.
various methods used to populate the textarea:
Free form (user entered)
Autocomplete - validated against and choosen from a user entered string to produce the select list.
Text MUST match the database exactly
Freeform text allowed, but the associated ID must be in the database
New user text allowed, but must be posted as a new value to the select list
programatic population (pull from database/other value and populate)
All of this makes the validation rules complex however the other answer is being accepted as it best helped resolve the issue.
Note that there are actually multiple keystrokes that get in play here with various actions based on the keystroke and the options in play for a particular user.
Thanks to everyone for the assistance.

Restricting text box inputs to a given regexp using jQuery

Consider the following text box:
<input type="text" name="quantity" id="quantity_field" />
Using jQuery I want to restrict the set of valid inputs into quantity_field by the following regexp:
<script>
var quantityRegexp = "^(0|[1-9]+[0-9]*)$";
</script>
More specifically I want to make the browser discard any characters entered into quantity_field that would make the value of the text field not conform to the given regexp. (A corresponding check would of course also be made on the server-side.)
Examples:
If the user types "foo 234" only "234" would get entered in the text box.
If the user types "001230" only "1230" would get entered in the text box.
If the user types "foo1bar" only "1" would get entered in the text box.
Question: What is the simplest way to acheive this using jQuery?
Not an answer to your question (since I have no knowledge of jQuery), but the regex ^[1-9]*[0-9]*$ might not do as you expect or think. It matches empty strings but also a number like 000000. I expect that you don't want that since your first character class [1-9] explicitly ignores the zero. I think you should change the first * into a +: ^[1-9]+[0-9]*$. However, that regex will reject the (single) number 0. If you want to include that, you should do: ^(0|[1-9]+[0-9]*)$.
If you don't know how many characters the user is going to type in (and just want to restrict them to numbers), the jQuery Validation Plugin is your best bet.
$('form.to-validate').validate({
rules: {
quantity: { digits: true }
}
});
That will only allow the user to enter in digits. If you know how many characters the person is going to type, then I also recommend using the Masked Input plugin for jQuery, which will give the user a nice visual indication of what they need to type and also prevent them from entering in characters you do not want in the field.
If you're not after just digits and must check against a regular expression, this post has the method to add a custom validation method to the jQuery Validation Plugin which should get you what you want.
Hope that helps!
I advise you to let the user tpye whatever he wants, then do a validation on submit of the form. (Of course you must still check on the server-side as he could easily disable or alter the javascript validation code)
For validation look into the
jQuery Validation Pluging
Define a global variable "oldVal" (not described below), which contains the last known good value. Bind to the keydown action for the input field:
<script>
$("#quantity_field").keydown(function() {
var newVal = $("#quantity_field").val();
var quantityRegexp = /^(0|[1-9]+[0-9]*)$/;
// success
if (quantityRegexp.test(newVal)) {
oldVal = newVal;
// hide error
$("#quantity_field_error").hide();
}
// else failure
else {
$("#quantity_field").val(oldVal);
// display error message
$("#quantity_field_error").show();
}
});
</script>
This should get you started

Categories

Resources