Is is possible to restrict the user input to only the source values with JQuery autocomplete plugin?
For example, if the source array contains "Bold","Normal","Default","100","200", the user is allowed to only type those values.
I see you already have a solution. Here's a similar way to do this, since I already put some time in on it.
http://jsfiddle.net/pxfunc/j3AN7/
var validOptions = ["Bold", "Normal", "Default", "100", "200"]
previousValue = "";
$('#ac').autocomplete({
autoFocus: true,
source: validOptions
}).keyup(function() {
var isValid = false;
for (i in validOptions) {
if (validOptions[i].toLowerCase().match(this.value.toLowerCase())) {
isValid = true;
}
}
if (!isValid) {
this.value = previousValue
} else {
previousValue = this.value;
}
});
I have a simple alternative. Check this out:
http://jsfiddle.net/uwR3Z/2/
Basically an onChange event on the textbox to clear out the value works the same.
Here is the js:
var validOptions = ["Bold", "Normal", "Default", "100", "200"];
$('#auto-complete-input').autocomplete({
autoFocus: true,
source: validOptions
});
function clearAutoCompleteInput() {
$("#auto-complete-input").val('');
}
And html:
<label for="auto-complete-input">Select one: </label>
<input id="auto-complete-input" type="text" onChange="clearAutoCompleteInput()" />
I agree with the comment made by Rephael, as you want to limit the possible values to the one in autocomplete, a safer choice would be to have a select dropdown.
As a final user can be frustrating to enter data in a textbox and not being able to write what I want. The choice of a select dropdown is "socially" accepted to be limited.
I figured out a way.
Add the following option to the plugin. This works for when the source is an array.
change: function (event, ui) {
if (!ui.item) {
var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex($(this).val()) + "$", "i"),
valid = false;
$.each(YOUR_SOURCE_ARRAY_NAME, function (index, value) {
if (value.match(matcher)) {
this.selected = valid = true;
return false;
}
});
if (!valid) {
// remove invalid value, as it didn't match anything
$(this).val("");
return false;
}
}
}
This is an old question but I what I do is
set a flag to false when entering the field (onfocus)
Set the flag to true in the autocomplete select event
Test that flag in the field onblur event.
If it is true the input is good, otherwise it is bad.
Related
I have this code for autocomplete in an HTML input :
$("#myinput")
.bind("keydown", function(event) {
// don't navigate away from the field on tab when selecting an item
if (event.keyCode === $.ui.keyCode.TAB
&& $(this).data("autocomplete").menu.active) {
event.preventDefault();
}
})
.autocomplete({
minLength: 0,
source: function(request, response) {
var results = [],
selectionStart = this.element[0].selectionStart
term = extractLast(request.term.substring(0, selectionStart));
if (term.length > 0) {
console.log(term);
if(/*input has string "where"*/)
results = $.ui.autocomplete.filter(table1, term);
else
results = $.ui.autocomplete.filter(table2, term);
}
response(results);
},
focus: function() {
return false; // prevent value inserted on focus
},
select: function(event, ui) {
var terms = split(this.value.substring(0, this.selectionStart));
terms.pop(); // remove the current input
terms.push(ui.item.value); // add the selected item
this.value =
$.trim(terms.join(" ") + this.value.substring(this.selectionStart)) + " ";
return false;
}
});
What I'm trying to do is if the input has string "where" in somewhere, then it will load autocomplete from table1, otherwise it will load from table2. How can I check if the input has that string? Thanks in advance.
You should use includes method.
var inputValue=$("#myinput").val();
if(inputValue.toLowerCase().includes("where")){
//rest of code
}
Another method is using indexOf method.
if(inputValue.indexOf("where")!==-1){
//rest of code
}
If you want to do this achievment using regex, you can use search method.
if(inputValue.search(/where/i)!==-1){
//rest of code
}
inputValue="awherea";
console.log(inputValue.search(/where/))
If you want the strongest browser support, use String#indexOf
if(this.value.indexOf('where') > -1) {
//doSomething
}
you can get your text value and use indexof to find it .
my_inp = $("#myinput").val();
if (my_inp.indexOf('where') > -1) {
console.log('yes');
}
Try with string#match method use the ternary operator for return true or false
And also Some of the More method
string.indexOf()
string.includes()
console.log('hello everyone'.match("hello") ? true : false)
For jquery you could use the contains() method
console.log($('p').is(':contains("hi")'))
console.log($('p').is(':contains("22")')) // not contains
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>hello hi</p>
I have multiple forms in different page, Is there a way to write a single function which would take care of validation or should i write code for each form separately.
$(document).ready(function () {
$('#fvujq-form1').validate();
$('#fvujq-form2').validate();
});
Note: Each form has its own rules.
Update:
$("form").each(function () {
$(this).validate({
rules: {
username: {
required: true
},
password: {
required: true
},
name: {
required: true,
},
cperson: {
required: true,
}
},
submitHandler: function (form) {
return false; //temporarily prevent full submit
}
});
});
Now the username and password of different form and name and person is of different form in different page. Is it right to proceed in this way of having a common form submission.
You should test using $('form').validate();, if that doesn't work, then use:
$('form').each(function(){
$(this).validate();
});
You can use the $("form") selector to validate all elements of type form if that's what you are asking for. I would not recommend that specifically for a page with multiple forms though.
If you can give each input element in your form a custom xx-field-type attribute eg:
<input type='text' xx-field-type='email'/>
You could use:
jQuery.fn.extend({
validate: function() {
var input_list = this.find("input");
for (var i = 0; i < input_list.length; i++) {
switch(input_list[i].attr("xx-field-type")) {
case 'username':
var value = input_list[i].val();
if (value.match(/^[a-z0-9]+$/) != true) {
return false;
}
break;
case 'password':
var value = input_list[i].val();
if (value.match(/[a-z]+/) != true
|| value.match(/[A-Z]+/) != true
|| value.match(/[0-9]+/) != true) {
return false;
}
break;
case 'email':
var value = input_list[i].val();
if (value.match(/^[a-z0-9]+#[a-z0-9]$/) != true) {
return false;
}
break;
default:
continue;
}
}
return true;
}
});
This would go through each input field of a form, check the value of it's xx-field-type attribute and use that to choose the rules that the value must match. Returns false if any fail otherwise returns true.
If you can't add custom attributes you could use classes but it feels hacky to denote form type using an attribute intended for setting display related stuff.
Untested
the field types I've used and the regexps are just for the purposes of demonstration.
Is it possible to use the isNaN() function to check if textbox value is a number without listing each field? I tried the below coded and it does not work properly. It triggers my alert regardless of what is input.
var numberCheck = function() {
var i = this.value
if(isNaN(i)==true) {
alert("You must enter an number value!");
}
}
I figured out how to do what I wanted to do. I had to define the parameters of the function as the ID of the element.
onkeyup = "numberCheck(this.id);"
var numberCheck = function(myID){
if(isNaN(document.getElementById(myID).value)){
alert("You must enter an number value!" );
};
}
I am trying to do required validation in a asp.net page.
I have multiple controls that will be hidden and displayed.
Controls like checkboxlist,dropdownlist,multiselectedlistbox.
I am using a css class called required attaching to all these controls to check the validation.
I am trying to check if each control has value or not but my code is checking each options with in each controls.
I am really not finding a way not a jquery expert just a novice...
Here is my code any ideas anyone please....
$("input[type='submit']").click(function () {
if ($(this).val() != 'Back') {
var names = [];
var info=" ";
$('.required input').each(function () {
var control = $(this);
if (control.is(':enabled')) {
names[$(this).attr('name')] = true;
}
});
$('.required option').each(function () {
var control = $(this);
if (control.is(':enabled')) {
names[$(this).attr('name')] = true;
}
});
for (name in names) {
var radio_buttons = $("input[name='" + name + "']");
if ((radio_buttons.filter(':checked').length == 0) ||(radio_buttons.filter(':selected').length == 0)) {
info += radio_buttons.closest("table").find('label').html()+"</br>";
}
}
if (info != " ") {
$("#validation_dialog p").html(info);
$("#validation_dialog").dialog({
title: "Validation Error!",
modal: true,
resizable: false,
buttons: {
Close: function () {
$(this).dialog('close');
}
}
});
return false;
}
}
});
here is a fiddle for it...
http://jsfiddle.net/bDmgk/35/
I think what you want is:
$(".required input[type='radio']:checked").each(function(){
});
instead of :
$(".required option").each(function(){ ... });
Hi I made some changes to your fiddle basically I checked for the inputs inside each column like this and then I added them to your names array.
Using
$('table.required:eq(0) input:checked')
I you can got all the inputs that are checked on the first column if the lenght of the array returned is 0 then no input is checked, i't the same procedure for the other ones.
An yes those input names are weird.
Check this fiddle
JSFiddle
I'm running into issues with the following code:
var setupSearch = {
searchSuggest: function(field) {
$.getJSON('/get-all-journals', {'url':'on'}, function(data) {
var SHCount = Number($.cookie('SHCount'));
var SHArray = new Array();
for (i=1; i <= SHCount; i++) {
SHArray.push($.cookie('SH'+i));
}
$(field).ddautocomplete(removeDuplicate(SHArray), data.response.docs, {
matchContains: true,
max: 5,
cacheLength: 5000,
selectFirst: false,
scroll: false,
formatResult: function(str) { return str; },
formatItem2: function(item) {
return item.journal_display_name;
},
formatMatch2: function(item) {
return item.journal_display_name;
},
formatResult2: function(item) {
return item.journal_display_name;
}
});
});
},
searchForm: function(form) {
var field = form.find('textarea');
// Setup query field for default text behavior
// setupField(field);
setupSearch.searchSuggest(field);
field.autogrow();
field.keydown(function(e) {
if (e.keyCode == 13) {
form.submit();
return false;
}
});
// Make all forms submitting through Advanced Search Form
form.submit(function(e) {
e.preventDefault();
setupSearch.submitSearch(form, field);
});
},
submitSearch: function(form, field) {
if (advancedSearch.checkMinFields() || (!field.hasClass('defaultText') && field.val() != '')) {
// Sync the refine lists
// syncCheckboxLists($('#refineList input'), $('#advancedRefineList input'));
form.find('button').addClass('active');
$('#advancedSearchForm').submit();
} else {
$('#queryField').focus();
}
},
When I try to use the autocomplete drop-down by hitting enter, it seems to hit a "race condition" where the form will submit what I've typed rather than what autocomplete places into the textfield. Is there some way I can control the order of events so that the form.submit() will use what autocomplete fills into the text field?
The actual autocomplete dropdown menu is most likely represented as a styled list (or some other element) that is floated to be positioned below the textbox. On submit, have your function wait (a second or two max) for the autocomplete menu to be either destroyed or hidden. This will ensure that the plugin has time to fill in the textbox before the data is submitted.
EDIT
Try something like this:
$("#myDropdown").bind("autocompleteclose", function(){
// Continue with submitting your form
});
Use that where you would submit your form, and put the submitting code inside the callback. That way, it will wait for the autocomplete to close before submitting the form. You will want to add some kind of timeout to this to prevent it from submitting after a long delay (not sure when something like this might happen, though).