I'm just learning about the jQuery AutoComplete Widget. The values pop up with a comma nicely. So, the visual display to the user is great.
My issue is how do I save the multiple values to a MySQLi database?
Here is the code:
<script>
$(function() {
var availableskills = [
"ActionScript",
"AppleScript",
..........
more languages
"XML"
];
function split( val ) {
return val.split( /,\s*/ );
}
function extractLast( term ) {
return split( term ).pop();
}
$( "#skills" )
// 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({
minLength: 0,
// could have source as a "url"
source: function( request, response ) {
// delegate back to autocomplete, but extract the last term
response( $.ui.autocomplete.filter(
availableskills, 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;
}
});
});
</script>
Now, here's my input id for letting the user select the skills:
<div class="ui-widget">
<!--<label for="skills">Tag programming languages: </label>-->
<input type="text" id="skills" size="50" />
</div>
Not sure on how to save the skills the user selects into a database. I can save data to a MySQLi db with ease; the issue is how can I take say three skills and save them into three different rows in a table in a database.
Any help, very much appreciated.
Ken
for example you will do form post with the input name skills
<form method="post" action="test.php">
<div class="ui-widget">
<input type="text" id="skills" size="50" name='skills' />
</div>
</form>
then test.php would be something like
<?php
//...do some mysql connections
$skills = explode(",",$_POST['skills']);
foreach($skills as $skill){
$statement.="INSERT INTO blahblahblah SET skill = ".mysqli_real_escape_string($skill);
}
$mysqli->multi_query($statement);
Related
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>";
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.
I am trying to create an auto complete using jqueryui.I am echo ing a database result from the remote file search.php.It is showing the correct word in the response of fire bug but the suggetion list is not at all showing in my html page.
Can anybody please help me?
i'm using the code of multipile ,remote demo in the jqueryui.com
my php code
<?php include("connection.php");
$q=mysql_real_escape_string($_GET['term']);
$x="select fieldname from tablename where fieldname like '$q%'";
$query=mysql_query($x);
while($row=mysql_fetch_array($query)) { echo $row['fieldname']."\n"; } ?>
========================================================================
------------------------------------------------------------------------
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script src="http://code.jquery.com/ui/1.9.1/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<style>
.ui-autocomplete-loading {
background: white url('images/ui-anim_basic_16x16.gif') right center no-repeat;
}
</style>
<script>
$(function() {
function split( val ) {
return val.split( /,\s*/ );
}
function extractLast( term ) {
return split( term ).pop();
}
$( "#birds" )
// 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;
}
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="birds">Birds: </label>
<input id="birds" size="50" />
</div>
If your remote file is placed on different domain you have to use JSONP.
JSON dosen't support cross-domain data transfer.
Read more about Same Origin policy
I'd like have a button on my page that display a form (in a div) which includes text box and two buttons.
I'm not too familiar yet with jquery but I did do some reading and have tried to base my code on an example found here at: http://jqueryui.com/demos/dialog/#modal-form
I have a button that looks like:
<input type='button' class='btn btn-info' value='Change VLAN' id='changevlan'/>
and a div that contains the details of the pop form that I want:
<div id="dialog-form" title="Change Vlan">
<p>You must supply a new vlan number</p>
<form>
<fieldset>
<label for="vlan">Vlan Number:</label>
<input type="text" name="vlan" id="vlan" class="text ui-widget-content ui-corner-all" />
</fieldset>
</form>
</div>
And then at the bottom of my page, i have included the jquery and jquery ui libraries (I loaded at bottom for faster page loading) and I have the following javascript: (I based it off the example i mentioned at the beginning of this post.)
<script type="text/javascript">
$(function() {
// a workaround for a flaw in the demo system (http://dev.jqueryui.com/ticket/4375), ignore!
$( "#dialog:ui-dialog" ).dialog( "destroy" );
var vlan = $( "#vlan" ),
tips = $( ".validateTips" );
function updateTips( t ) {
tips
.text( t )
.addClass( "ui-state-highlight" );
setTimeout(function() {
tips.removeClass( "ui-state-highlight", 1500 );
}, 500 );
}
function checkLength( o, n, min, max ) {
if ( o.val().length > max || o.val().length < min ) {
o.addClass( "ui-state-error" );
updateTips( "Length of " + n + " must be between " +
min + " and " + max + "." );
return false;
} else {
return true;
}
}
function checkRegexp( o, regexp, n ) {
if ( !( regexp.test( o.val() ) ) ) {
o.addClass( "ui-state-error" );
updateTips( n );
return false;
} else {
return true;
}
}
$( "#dialog-form" ).dialog({
autoOpen: false,
height: 300,
width: 350,
modal: true,
buttons: {
"Change Vlan": function() {
var bValid = true;
allFields.removeClass( "ui-state-error" );
bValid = bValid && checkLength( vlan, "vlan", 1, 1 );
bValid = bValid && checkRegexp( vlan, /^([0-9])+$/i, "vlan must be numeric." );
if ( bValid ) {
//this is where I need to redirect to another URL passing the vlan number.
$( this ).dialog( "close" );
}
},
Cancel: function() {
$( this ).dialog( "close" );
}
},
close: function() {
allFields.val( "" ).removeClass( "ui-state-error" );
}
});
$( "#changevlan" )
.button()
.click(function() {
alert('in here');
$( "#dialog-form" ).dialog( "open" );
});
});
</script>
As you can see I inserted an alert statement to ensure that i was getting into the javascript. But I don't get the alert message. And the contents of the div form just show up on the main page when it's initially rendered.
What I've checked so far:
I've tried to double check that the name of my button that should trigger the div form display matches the name of the variable i'm looking for in the javascript function:
$( "#changevlan" )
.button()
.click(function() {
alert('in here');
$( "#dialog-form" ).dialog( "open" );
});
I've also made sure that my div form is called #dialog-form
But I'm not too sure what else to try. If you ahve any suggestions, I'd appreciate it. I also need to know how to access the contents of the text box and then redirect the user to a new controller and method, passing the vlan number as a parameter.
Maybe I can just do a window.location type of thing...
Thanks.
u dont need more libraries, just make a simple jQueryUI .dialog, inside the "div" element for the dialog place some inline php from CI, something like <div id="dlgPopUpForm"><?= $this->load->view('dialogView.php'); ?></div>, then build your form in the dialogView.php of course.
At run time, the php wil be read into the div and the jquery options u use to create the dialog will handle the rest. something like $("#dlgPopUpForm").dialog({ autoOpen: false, modal: true }); $("#someButton").click(function(e){ $("#dlgPopUpForm").dialog("open"); });
dont forget to include your javascript for the form on the form view page (dialogView.php in my example)
maybe when i'm not so lazy, i'll make ya an example later today, though, its pretty straight forward
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.