How To Add Validation in Textbox in Jquery - php

What I need:
When User Enter a mail address in text box then commas (,) should Seprate email address.
i have used Example of jquery Autocomplete here is the url:http://jqueryui.com/autocomplete/#multiple.
i want that user enter multiple email address in textbox and (,) should seperate each email address.
here is the snapshot that i want :http://postimg.org/image/z7tv89bab/
$(function() {
var availableTags = [
"af#gmail.com",
"af1#gmail.com",
"af2#gmail.com",
"af3#gmail.com",
];
function split( val ) {
return val.split( /,\s*/ );
}
function extractLast( term ) {
return split( term ).pop();
}
$( "#tags" )
// don't navigate away from the field on tab when selecting an item
.bind( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).data( "ui-autocomplete" ).menu.active ) {
event.preventDefault();
}
})
.autocomplete({
minLength: 0,
source: function( request, response ) {
// delegate back to autocomplete, but extract the last term
response( $.ui.autocomplete.filter(
availableTags, extractLast( request.term ) ) );
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function( event, ui ) {
var terms = split( this.value );
// remove the current input
terms.pop();
// add the selected item
terms.push( ui.item.value );
// add placeholder to get the comma-and-space at the end
terms.push( "" );
this.value = terms.join( ", " );
return false;
}
});
});
Tag programming languages:

Try jquery validation plugin to validate textbox.
// Code to accept multile mails
jQuery.validator.addMethod("multiemail", function (value, element) {
if (this.optional(element)) {
return true;
}
var emails = value.split(','),
valid = true;
for (var i = 0, limit = emails.length; i < limit; i++) {
value = emails[i];
valid = valid && jQuery.validator.methods.email.call(this, value, element);
}
return valid;
}, "Invalid email format: please use a comma to separate multiple email addresses.");
The above function should be used in validation js
var validator = $("#frmlogin").validate({
errorElement: 'div',
rules: {
email: {
required: true,
email: true,
multiemail: true
}
});

Related

jQuery Autocomplete ComboBox Options Echo'd by PHP Getting Removed when Match Typed

Currently I have a combobox which options gets echo'd by PHP since the values are in an array. The code of the combobox is as follows:
<div class="ui-widget">
Project
<br>
<select id="combobox">
<?php
foreach($projects as $value)
{
echo "<option value=".$value.">".$value."</option>";
}
?>
</select>
</div>
What I am trying to achieve is when a user types into the combobox he gets a dropdown-list with all the entries of the array that match the text the user typed in the combobox.
The user can then select an option from the dropdown-list or choose to type the entry completely(but it needs to mach the entries in the dropdown-list).
To achieve all this i am currently using the Autocomplete function of jQuery.
All the code that I am using to achieve this can be watched here: http://jqueryui.com/autocomplete/#combobox.
The code for the combobox I use is as follows:
<script>
(function( $ ) {
$.widget( "custom.combobox", {
_create: function() {
this.wrapper = $( "<span>" )
.addClass( "custom-combobox" )
.insertAfter( this.element );
this.element.hide();
this._createAutocomplete();
this._createShowAllButton();
},
_createAutocomplete: function() {
var selected = this.element.children( ":selected" ),
value = selected.val() ? selected.text() : "";
this.input = $( "<input>" )
.appendTo( this.wrapper )
.val( value )
.attr( "title", "" )
.addClass( "custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left" )
.autocomplete({
delay: 0,
minLength: 0,
source: $.proxy( this, "_source" )
})
.tooltip({
tooltipClass: "ui-state-highlight"
});
this._on( this.input, {
autocompleteselect: function( event, ui ) {
ui.item.option.selected = true;
this._trigger( "select", event, {
item: ui.item.option
});
},
autocompletechange: "_removeIfInvalid"
});
},
_createShowAllButton: function() {
var input = this.input,
wasOpen = false;
$( "<a>" )
.attr( "tabIndex", -1 )
.attr( "title", "Show All Items" )
.tooltip()
.appendTo( this.wrapper )
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass( "ui-corner-all" )
.addClass( "custom-combobox-toggle ui-corner-right" )
.mousedown(function() {
wasOpen = input.autocomplete( "widget" ).is( ":visible" );
})
.click(function() {
input.focus();
// Close if already visible
if ( wasOpen ) {
return;
}
// Pass empty string as value to search for, displaying all results
input.autocomplete( "search", "" );
});
},
_source: function( request, response ) {
var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
response( this.element.children( "option" ).map(function() {
var text = $( this ).text();
if ( this.value && ( !request.term || matcher.test(text) ) )
return {
label: text,
value: text,
option: this
};
}) );
},
_removeIfInvalid: function( event, ui ) {
// Selected an item, nothing to do
if ( ui.item ) {
return;
}
// Search for a match (case-insensitive)
var value = this.input.val(),
valueLowerCase = value.toLowerCase(),
valid = false;
this.element.children( "option" ).each(function() {
if ( $( this ).text().toLowerCase() === valueLowerCase ) {
this.selected = valid = true;
return false;
}
});
// Found a match, nothing to do
if ( valid ) {
return;
}
// Remove invalid value
this.input
.val( "" )
.attr( "title", value + " didn't match any item" )
.tooltip( "open" );
this.element.val( "" );
this._delay(function() {
this.input.tooltip( "close" ).attr( "title", "" );
}, 2500 );
this.input.autocomplete( "instance" ).term = "";
},
_destroy: function() {
this.wrapper.remove();
this.element.show();
}
});
})( jQuery );
$(function() {
$( "#combobox" ).combobox();
$( "#toggle" ).click(function() {
$( "#combobox" ).toggle();
});
});
</script>
The problem that I am having right now is when a user types text in the combobox and the dropdown-list appears and he fully types out an entry of the dropdown-list the combobox still gets cleared. This is not supposed to happen. Whenever the user clicks on the combobox the item doesn't get cleared.
To make is a bit clearer here is an image of the combobox:
So above you can see the combobox. Whenever a user types something he gets a dropdown-list with all the results matched(project 1, project 10).
The problem that I am having right now is when a user types out "project 1" without clicking on the item in the dropdown-list the text in the combobox still gets removed by the Autocomplete function in jQuery.
If the user clicks on the item then there is no problem at all.
Funny thing is that the Autocomplete function works without any problems if I don't echo the option elements with PHP.
so:
<option value="project 1">project 1</option>
<option value="project 2">project 2</option>
<option value="project 3">project 3</option>
instead of:
foreach($projects as $value)
{
echo "<option value=".$value.">".$value."</option>";
}
Any help is greatly appreciated.
Change from
echo "<option value=".$value.">".$value."</option>";
TO
echo "<option value='".$value."'>".$value."</option>";

How to keep select after jquery append

Ok guys here's the fiddle
http://jsfiddle.net/wKbXx/24/
$(function() {
$( 'input[name=q1]' ).on( 'change', function() {
var sel = $('[id^="comm"]'), opt = $( '<option/>' );
if ($(this).is(':checked')) {
sel.append( $("<option />").val(this.value).text( this.id ) );
} else {
$('option[value=' + this.value + ']').remove();
}
});
});
What I need to do is to select two colors with the check boxes. Let say red, and blue. Then using the select, Mark one red and one blue. Then check green. I want it to keep the selected data. Right now once you select green it wipes that data. How can I do that?
UPDATED TO REFLECT WORKING ANSWER.. UPDATED FIDDLE TOO
I would go for a slightly different approach; instead of always resetting the select boxes, I would check whether the text in the changed checkbox is already contained in the select boxes. If it is, I would assume it's been unchecked and remove the option from the select boxes. Otherwise I would append just that new option to the select boxes.
$(function() {
$( 'input[name=q1]' ).on( 'change', function() {
var sel = $('[id^="comm"]'), opt = $( '<option/>' );
if (sel.find('option').text().indexOf(this.id) > 0) {
$('option[value=' + this.value + ']').remove();
} else {
sel.append( $("<option />").val(this.value).text( this.id ) );
}
});
});
The downside with this version is that the order of the colors in the select boxes is determined by the order in which the checkboxes are clicked; with your version, the order of the colors in the select boxes is always the same as in the checkboxes.
(Hope that made sense.)
Here's a fiddle: http://jsfiddle.net/Niffler/0hLxzvh8/
This may be the answer to your question...
You should have your rewrite on top as well.
$(function() {
var sel = $('[id^="comm"]'), opt = $( '<option/>' );
sel.html( opt.clone().text( '[Select One]' ) );
$( 'input[name=q1]' ).on( 'change', function() {
if ($(this).is(':checked')) {
sel.append( $("<option />").val(this.value).text( this.id ) );
}
else {
//Remove where ID matches up
sel.children().remove();
}
if( sel.find( 'option' ).length > 1 ) {
if( sel.find( 'option' ).length === 2 ) {
sel.find( 'option' ).eq( 1 ).attr( 'selected',true );
}
}
});
});
Cheers!
You need to get the value of the select box before you replace the options, then reset the value at the end.
$(function() {
$( 'input[name=q1]' ).on( 'change', function() {
var sel = $('[id^="comm"]'), opt = $( '<option/>' );
sel.each(function(){
sel.data('previous', sel.val());
});
// overwrite the existing options
sel.html( opt.clone().text( '[Select One]' ) );
$( 'input[name=q1]:checked' ).each( function() {
sel.append( $("<option />").val(this.value).text( this.id ) );
});
// if it had a value, set it back to that.
if ( currentValue != '' ){
sel.each(function(){
sel.val(sel.data('previous'));
});
} else {
if( sel.find( 'option' ).length > 1 ) {
if( sel.find( 'option' ).length === 2 ) {
sel.find( 'option' ).eq( 1 ).attr( 'selected',true );
}
}
}
});
});

AutoComplete Highligh Issue

I want to highlight matched characters in jquery autocomplete.
If i type GC,it give me below,which is OK
Green Community
Now i want G and C both to be bold/strong.
$('#9').autocomplete({
source: "auto_loc_name.php",
selectFirst: true,
minLength: 0,
select: function (event, ui) {
alert(ui.item.value);
}
});
I was using JQuery Autocomplete as a combobox and your needs work well with me and you can review the following code may be help you :
(function( $ ) {
$.widget( "ui.combobox", {
_create: function() {
var input,
self = this,
select = this.element.hide(),
selected = select.children( ":selected" ),
value = selected.val() ? selected.text() : "",
wrapper = $( "<span>" )
.addClass( "ui-combobox" )
.insertAfter( select );
input = $( "<input>" )
.appendTo( wrapper )
.val( value )
.addClass( "ui-state-default" )
.autocomplete({
delay: 0,
minLength: 0,
source: function( request, response ) {
var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
response( select.children( "option" ).map(function() {
var text = $( this ).text();
if ( this.value && ( !request.term || matcher.test(text) ) )
return {
label: text.replace(
new RegExp(
"(?![^&;]+;)(?!<[^<>]*)(" +
$.ui.autocomplete.escapeRegex(request.term) +
")(?![^<>]*>)(?![^&;]+;)", "gi"
), "<strong>$1</strong>" ),
value: text,
option: this
};
}) );
},
select: function( event, ui ) {
ui.item.option.selected = true;
self._trigger( "selected", event, {
item: ui.item.option
});
},
change: function( event, ui ) {
if ( !ui.item ) {
var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( $(this).val() ) + "$", "i" ),
valid = false;
select.children( "option" ).each(function() {
if ( $( this ).text().match( matcher ) ) {
this.selected = valid = true;
return false;
}
});
if ( !valid ) {
// remove invalid value, as it didn't match anything
$( this ).val( "" );
select.val( "" );
input.data( "autocomplete" ).term = "";
return false;
}
}
}
})
.addClass( "ui-widget ui-widget-content ui-corner-left" );
input.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.label + "</a>" )
.appendTo( ul );
};
$( "<a>" )
.attr( "tabIndex", -1 )
.attr( "title", "Show All Items" )
.appendTo( wrapper )
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass( "ui-corner-all" )
.addClass( "ui-corner-right ui-button-icon" )
.click(function() {
// close if already visible
if ( input.autocomplete( "widget" ).is( ":visible" ) ) {
input.autocomplete( "close" );
return;
}
// work around a bug (likely same cause as #5265)
$( this ).blur();
// pass empty string as value to search for, displaying all results
input.autocomplete( "search", "" );
input.focus();
});
}
});
})( jQuery );
and I think your needs in the following part but I don't know how to use that in your code :
source: function( request, response ) {
var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
response( select.children( "option" ).map(function() {
var text = $( this ).text();
if ( this.value && ( !request.term || matcher.test(text) ) )
return {
label: text.replace(
new RegExp(
"(?![^&;]+;)(?!<[^<>]*)(" +
$.ui.autocomplete.escapeRegex(request.term) +
")(?![^<>]*>)(?![^&;]+;)", "gi"
), "<strong>$1</strong>" ),
value: text,
option: this
};
}) );
},
You can try something like this, based on code from jQueryUI: how can I custom-format the Autocomplete plug-in results?
function monkeyPatchAutocomplete() {
$.ui.autocomplete.prototype._renderItem = function (ul, item) {
var matchstring = [];
$.each(this.term.split(""), function(index, c){
matchstring.push("^"+c+"|\b"+c);
});
var output = item.label.replace(new RegExp("(" + matchstring.join("|") + ")", "gi"), '<span class="ui-menu-item-highlight">$1</span>');
return $("<li>")
.append($("<a>").html(output))
.appendTo(ul);
};
}
$(function () {
monkeyPatchAutocomplete();
});
May or may not work. The idea is to get a Regex string like ^G|\bG for each character. I'm sure this misses quite a few cases, so keep working on it.
Edit: working jFiddle. http://jsfiddle.net/9MC5M/ Like the code above but with a few bug fixes. The search is deliberatly broken, it just returns all items to showcase the highlighting.

how to pass hidden id using json in jquery ui autocomplete?

perhaps it is duplicate,but i can't found solution so i posted this question.I am use jquery ui for auto complete search box. it works fine but the problem is i want to search using id.example:when user type paris,i try to send city_id in mysql for search. so problem is how to pass hidden id with json?
here the code:
<input type="text" name="grno" id="grno" class="input" title="<?php echo $lng['vldgrno'];?>
jquery code:
<script>
$(function() {
function split( val ) {
return val.split( /,\s*/ );
}
function extractLast( term ) {
return split( term ).pop();
}
$( "#grno" )
// don't navigate away from the field on tab when selecting an item
.bind( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).data( "ui-autocomplete" ).menu.active ) {
event.preventDefault();
}
})
.autocomplete({
source: function( request, response ) {
$.getJSON( "pages/search.php", {
term: extractLast( request.term )
}, response );
},
search: function() {
// custom minLength
var term = extractLast( this.value );
if ( term.length < 1 ) {
return false;
}
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function( event, ui ) {
var terms = split( this.value );
// remove the current input
terms.pop();
// add the selected item
terms.push( ui.item.value );
// add placeholder to get the comma-and-space at the end
terms.push( "" );
this.value = terms.join( "," );
alert(data.id);
return false;
}
});
});
</script>
autocomplete.php :
<?php
mysql_connect('localhost','root','');
mysql_select_db('school');
$return_arr = array();
$term = trim(strip_tags($_GET['term']));//retrieve the search term that autocomplete sends
//create select query
$query = "select `grno`,`first_name`,`student_id` from `tbl_student` where `grno` like '%".$term."%' or `first_name` like '%".$term."%'";
// Run the query
$result = mysql_query ($query);
$array = array();
while($obj = mysql_fetch_array($result)){
$array['name'] = $obj['first_name']."(".$obj['grno'].")";
array_push($return_arr,$obj['first_name']."(".$obj['grno'].")");
}
$json = json_encode($return_arr);
echo $json;
?>
so.how to pass student_id in autocomplete.php,like label and value.{label='xyz' value='1'}
In autocomplete.php replace this code
array_push($return_arr,array("value"=>$obj['student_id'],"label"=>$obj['first_name']."(".$obj['grno'].")"));
and in your script change this
terms.push( ui.item.label );
$( "#stud_id" ).val( ui.item.value );
hope,this is what you find.

Help me to solve problem with jQuery and PHP

I want to apply "Jquery UI Autocomplete with multiple values" to one registration forms input field.
What i want to do exactly: When visitor types name of existing user to this input field, first of all, script searches for name existence, completes it (if exists), adds comma. User can type second, third... existing usernames to this field, and everytime script will auto complete. And when visitor clicks to submit button, PHP searches for id's of this usernames, creates array of id's, adds it to new users "friends" field in db table.
My code:
HTML
<form action="index.php" method="post">
<input class="std" type="text" name="friends" id="friends"/>
<input type="submit" name="submit">
</form>
Jquery
$(function() {
function split( val ) {
return val.split( /,\s*/ );
}
function extractLast( term ) {
return split( termĀ ).pop();
}
$( "#friends" )
// don't navigate away from the field on tab when selecting an item
.bind( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).data( "autocomplete" ).menu.active ) {
event.preventDefault();
}
})
.autocomplete({
source: function( request, response ) {
$.getJSON( "search.php", {
term: extractLast( request.term )
}, response );
},
search: function() {
// custom minLength
var term = extractLast( this.value );
if ( term.length < 2 ) {
return false;
}
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function( event, ui ) {
var terms = split( this.value );
// remove the current input
terms.pop();
// add the selected item
terms.push( ui.item.value );
// add placeholder to get the comma-and-space at the end
terms.push( "" );
this.value = terms.join( ", " );
return false;
}
});
});
search.php
$conn = mysql_connect("localhost", "user", "pass") or die( mysql_error() );;
mysql_select_db("db", $conn) or die( mysql_error() );;
$q = strtolower($_GET["term"]);
if (!$q) return;
$query = mysql_query("select id, fullname from usr_table where fullname like '$q%'") or die(mysql_error());
$results = array();
while ($row = mysql_fetch_array($query)) {$results[] = array ( "id" => $row[0] , "label" => $row[1], "value" => $row[1] );}
echo json_encode($results);
My questions:
I need only id of written name,
and fullname. I don't need value.
How can i delete it from jquery
code?
how to fetch array of id's
of written names, and put to
"friends" field of usr_table after
submission of registration form?
And finally i want to realise it
with mysqli. Which parts of code i
must change?
Sorry for my bad
english
This autocompleter can do what you want:
http://www.devbridge.com/projects/autocomplete/jquery/#demo
Just try to type country names separated by commas. I use it on my webpages and works well.

Categories