Auto-suggests upon entering character(s) into an input field? - php

There is a HUGE database of cities and other stuff in the system (locations) waiting to be driven out as a drop down list, div(s) or something what can compress huge amount of choices - instantly after every character of wanted location is entered into that input field.
Its similar like adding tags here when we are submitting questions. So if we enter "L" London and Lazio gonna be listed, after "La" - only Lazio will stay available.
Any steps or cool examples how to accomplish this? Tried to find something cool by myself but no luck. I'm using jquery.

This may be not the best sollution but it works on my site. This script implements street name auto complete, which depends on the state and city the user had entered before. This particular piece of code listens to the event "keyup". If user has entered more than one letter, the script launches ajax request in which .php script analyses the parameters we sent, makes SQL query and replies. If the user is lucky enough and he gets some suggestion for the street name he tries to find, we show him div with id=hintsTable. We also create event listener (click) for each auto complete option, in which we replace the value of input field for the one from auto complete option and hides the drop-down list.
I hope it helps.
$("#street input").keyup(function(){ //street enter
var input = $('#street input').val(); //we get what user has already entered
var code = $('#mregionSelect').val(); //city id
if(input.length > 1)
{
$.ajax({
type : "POST",
url : "components/com_areas/ajaxhelper.php",
data : "input=" + encodeURIComponent(input) + "&code=" + code,
cache : false,
}).done(function(msg){
if(msg.length > 0)
{
$('#hintsTable').html(msg); //fill drop-down list with auto complete options
$('#hints').css('display', 'block'); //show the list
$('#hintsTable tr').click(function(){
var hint = this.cells[0].innerHTML;
$('#street input').val(hint);
$('#hints').css("display", "none");
})
}
else
{
$('#hintsTable').html('');
$('#hints').css('display', 'none');
//$('#findButton').css('display', 'none');
}
})
}
else
{
$('#hintsTable').html('');
$('#hints').css('display', 'none');
//$('#findButton').css('display', 'none');
}
})

You could create a textbox with a div under
<input name="txtSearch" type="text" onkeydown="jscriptfunc();" autocomplete="off"/>
<div class="autoDiv"></div> (could use CSS to format the div accordingly)
Now the jscriptfunc for when the user presses a key down could be coded to call a PHP script with the help of ajax. This PHP script is taking whatever the user typed thus far and performing a simple pattern match search e.g.
Select * from table where field like '$input%' limit 5;
Then we just take the result and feed it into the div

Related

JQUERY load from TXT file, show VALUE in dropdown, GET user choice - Logical and JS help needed

Hello fellow programmers. I'm in a need of community assistance :)
I have a php form with three dropdowns that has jquery function that loads .txt files and builds two dynamic dropdowns realted to first choice.
First user choses option (hardcoded in script) - normal dropdown. Then the script takes control of other choices.
Script is here. Details of my question are below
<script type="text/javascript">
$(function() {
$("#text-one").change(function() {
$.get("/textdata2/podgrupa/" + $(this).val() + ".txt", function(data) {
$('#text-two').html('<select onChange="load_subcategory(this.value)" name="podkategorija">'+data+'</select>');
if($("#text-two select").val()!='base'){
$.get("/textdata2/podkategorija/" + $("#text-two select").val() + ".txt", function(data) {
$('#text-three').html('<select name="podgrupa">'+data+'</select>');
}).fail(function() {
alert("Missing file: /textdata2/podkategorija/" + $("#text-two select").val() + ".txt");
$("#text-three").html('<select name="podgrupa"><option>Odaberite rubriku</option></select>') ;
});
}else
$("#text-three").html('<select name="podgrupa"><option>Odaberite rubriku</option></select>');
});
});
});
function load_subcategory(val){
$.get("/textdata2/podkategorija/" + val + ".txt", function(data) {
$('#text-three').html('<select name="podgrupa">'+data+'</select>');
}).fail(function() {
alert("Missing file: /textdata2/podkategorija/" + val + ".txt");
$("#text-three").html('<select name="podgrupa"><option>Odaberite rubriku</option></select>')
});
}
</script>
example of one txt file from podgrupa folder
<option value="360">Iznajmljivanje</option>
<option value="361">Unajmljivanje</option>
<option value="456">Cimeri</option>
example of one txt file from podkategorija folder (that is related by value to choice in dropdown that looks into podgrupa folder)
<option value="120">regija 051</option>
<option value="121">regija 052</option>
<option value="122">ostalo</option>
When form posts data that user had choose, it writes values from tags. With these values jquery script knows which choice is connected to other.
For example: If user had chose: Rooms (from first hardcoded dropdown - code is 155 in option value), then script automaticaly loads second dropdown with choices from txt file (podgrupa), then user choses from those choices (for example Cimeri - 456) in second dropdown (podgrupa), and script loads third dropdown value (podkategorija) related to choice from second. User then choses value from that 3rd dropdown (for example regija 052 - 121)
After form submission, these values would be written by php: 155, 456, 121.
However, I need it to write different values for second(456) and third(121) choice. - For second it needs to write value "3" and for third value "2" if user has chosen those choices from example. As you can see those different values are the same as position of choice in txt file.
Can something like that be achived with ? Maybe with additional ID? Or maybe these values (456, 121) sholud be the ID, and value sholud be order in txt file (1,2,3...)
Hope you understand what I want to achieve :)
Thanks for help in advance
You can attach more information about each option than just a single value like 121 or 456, etc. You can either attach custom attributes to each option tag or perhaps even use jQuery's data method to store any arbitrary data to each option that you deem helpful. Here's a working example of what I'm talking about using the data approach: http://jsfiddle.net/qC6HK/
var dynamicDropdown = $('<select id="dropdown">');
var option1 = $('<option value="123">Option 1 Text</option');
dynamicDropdown.append(option1);
option1.data('coolData', 'the value of coolData');
Hope that helps.
Andy

Re-styling a form with jQuery?

I have this script set up that echoes all relevant users in a database to a page with check-boxes beside them. You can make a group out of these users in the database by checking some of the boxes and submitting the form. This all works great.
Unfortunately our designer doesn't like this. What she wants is basically a list of six empty fields on the left of the screen. Then, when you click a plus button next to a person's name on the right of the screen, that name appears in the first empty field...and so on with each subsequent plus button that's clicked.
So instead of re-coding all this (it's really not an option) I think I can just 're-style' all this with jQuery. I can style the check-boxes so they look like a plus when they're not selected and a minus when they are selected.
Then I just need to have some sort of event so that when when the check box is clicked, the person's name is taken and inserted into the first empty box. It's all just smoke and mirrors. The empty box could just be a div with a border. Functionally, it will all work the same as before.
Can anyone confirm if this is feasible? My JS knowledge sucks and I'm not sure where to begin. Plus I already have the following jQuery validator function on the page and I don't want this new JS to interfere with it:
$(document).ready(function(){
$("#myform").validate({
debug: false,
rules: {
group: {required: true},
},
messages: {
group: {required: " Field required.", loginRegex: " Invalid character."},
},
submitHandler: function(form) {
$('input[type=submit]').attr('disabled', 'disabled');
$('#results').html('Loading...');
$.post('process_group.php', $("#myform").serialize(), function(data) {
$('#results').html(data);
});
}
});
});
I suppose what I'm requesting is advice on how to code a check box to insert it's value into some div when it's checked. And to remove that value when it's unchecked.
If I understand you correctly, you need to do the following things with JQuery:
1)Replace your checkboxes () generated by server side code with clickable +/- signs.
You can do this by finding the checkboxes and replacing their default stage with an empty link that has a background image of a +.
$('checkbox').remove().html('Some Name');
Instead of an inline style you should make the plus and minus sign background images CSS classes if you know how.
2)You want to change the + to a - when it is clicked, and 3) have the user's name next to the + sign appear someplace else (in an empty input box?)
To toggle the background image, just change the style (or class if you know how to make the image a CSS class) when clicked. Then take the contents and put it in your target element.
This jsFiddle might help to illustrate what I'm describing above: http://jsfiddle.net/Ap2yW/1/

Fill Single Input Based On Prior Select - MYSQL PHP JS?

I want to grab my customers phone number from a MYSQL database and auto populate it into an input box based on users selection of customers in a prior dropdown box.
I've managed to do this in the past when filling in larger amounts of data but what I've previously used seems like a lot of code to auto fill a single input box.
I know how to fill the customer phone based on the data passed from the prior page (although I've deleted that bit here) but I want that data to change dynamically as users use the dropdown.
There's got to be an easy way to do this but I'm a complete newb at js (and only barely proficient at PHP & MYSQL). Can anyone give me a hand?
My PHP/HTML:
$result = mysql_query("SELECT cust_id, name, phone FROM customers ORDER BY name ASC");
$customers = mysql_fetch_array($result);
<label for="customer">Customer:</label>
<select name="customer">
<option value="0">Add New Customer</option>
<? foreach ($customers as $customer): ?>
<option value="<?=$customer['cust_id']?>" <?=($customer['cust_id'] == $parts['cust']) ? "selected" : ""?>><?=$customer['name']?></option>
<? endforeach; ?>
</select>
<label for="custphone">Customer Phone:</label>
<input type="text" name="custphone" value="">
Let me know if you need anything else from me and thanks in advance for helping me out on this.
For this answer, I will use the jQuery syntax, jQuery is a free javascript library, and you'll certainly use it in the future, read more.
To resume, we'll use an event triggered by your select element, when his value is changed, we'll process an AJAX request with some parameters to a PHP page (ajax.php) which returns the phone number of the customer previously choosen.
First you need to include in your HTML web page, the jQuery script, with the <script> tag.
<script src="path/to/jquery.js"></script>
In a second time, we'll create a new javascript script (assuming you add some id's to your HTML elements):
<script type="text/javascript">
$(document).ready(function(){ // When the document is ready
$("select#customers").on("change",function(){ // We attach the event onchange to the select element
var customer_id = this.value; // We retirve the customer's id
$.ajax({
url : "path/to/ajax.php", // path to you php file which returns the phone number
method : "post", // We want a POST request
data : "customer_id="+customer_id, // You'll retrieve this data in your $_POST variable in ajax.php : $_POST['customer_id']
success: function(response) { // The function to execute if the request is a -success-, response will be the customer phone number
$("input#custphone").value(response); // Fill the phone number input
}
});
});
});
</script>
Now, you've all the gear to continue, you should read about jQuery and AJAX.
You just have to create the "ajax.php", retrieve your customer id with the $_POST variable, process the SQL query to retrieve the phone number, then, return it with an echo.
Sounds like you want to look into AJAX. jQuery.ajax() makes it pretty easy.
Basically, you have a page on the server that queries the database and returns a JSON encoded string that the javascript can convert (using jQuery.parseJSON)back into an array and populate the list!
Use .change() to bind an event to the dropdown's change event. This will fire whenever the selection changes. Inside, you want to get the value (see demo on that page) and send an AJAX request to the server.
The PHP script on the server will query the database and return a JSON string. In the success function of the jQuery AJAX block you can populate the new list with the decoded information. See this page for a tutorial on how to add items to a select.

Change input background color if the value of the input is valid in database

The logic i am trying to do is:
input field starts white (Normal);
after somebody finish typing, if the email does not exists, the input gets light red;
if the email exists in the database, the input becomes white again;
I have my code like this:
index.php
<?php
include 'my database connection page';
include 'page that return me an array with all the emails';
?>
<form method="POST">
<input type="text" name="email" id="email_field" onFocus="changeColorEmail(this)">
<input type="submit">
</form>
scripts.js
function changeColorEmail(which) {
which.value = which.value.split(' ').join('')
if (which.value == "<? echo $user_data['user_email'] ?>") {
which.style.background = '#ffffff';
}else {
which.style.background = "#ffebe8";
}
}
Any ideas are appreciated!
user.php (contain a function that verify if the email exists in database)
function email_exists($email){
return (mysql_result(mysql_query("SELECT COUNT(user_id) FROM user WHERE user_email = '$email'"), 0) == 1) ? true : false;
}
ok, two ways to do this:
Hard way:
You're going to need to capture the onblur event - which will fire when they leave the email box, you're also going to need a bit of AJAX to send that value back to your script to test if it's valid or not.
jQuery:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"/>
<script>
function ValidateEmail(email)
{
var url = 'validateemail.php?email=' + email;
$.getJSON( url, function(data) {
var result = jQuery.parseJSON(data);
var ctrl = $("#email_field");
if(result.isValid == "true") {
ctrl.addClass("valid").removeClass("inValid");
}
else {
ctrl.addClass("inValid").removeClass("valid");
}
});
}
$(document).ready(function() {
// change blur to keyup if you want it to validate as they type (bad idea)
$("#email_field").bind("blur", function(){
ValidateEmail($(this).val());
});
});
</script>
(not tested, but should give you the general idea)
you'll need a script called validateemail.php on your server - it should pick up the email parameter and then return either:
{"isValid": "true"} or {"isValid": "false"}
depending on the value of email.
Easy way:
Add two css classes to your page (valid and inValid) - when the page is submitted, if the email exists add the valid class to the input control, if it doesn't add the invalid class instead.
CSS:
.valid { color: #ffffff; }
.invalid { color: #ffebe8; }
PHP:
<input type="text"
name="email"
id="email_field"
onFocus="changeColorEmail(this)"
<?echo 'class="'.(email_exists($_GET['email']) ? 'valid': 'inValid').'"';?>
>
try the second one first
UPDATED: bug fixes
You should change onFocus to onkeyup, because you seem to want to validate the e-mail address while the user is typing.
From an interaction design point of view I would advice you to change the color to red only when the final input is invalid, and change the timing of your validation process.
Although red is indeed easily associated with "wrong", it might be confusing for the user when giving the field focus is already considered wrong. I would advice you to start validating when the onblur event fires - when the user is obviously done typing - and/or when the user still has focus but hasn't pressed a key for a certain amount of time.
If I would be the user, that would be the behavior I would feel most comfortable with, and also the behavior I would directly interpret as "I've entered an invalid e-mail address".
First off, your use case seems to have some usability issues. Typically, a field will not give indication of validation results until it has lost focus. This way, you aren't interrupting the user with validation errors when they haven't finished inputting their data.
Concerning how to accomplish asynchronous validation, you're going to use an XMLHttpRequest (e.g. using jQuery's $.ajax()).
In your use case, the input is valid only if the email address already exists. In that case, you could make a separate PHP page (e.g. email_exists.php) that simply echoes the text true or false depending on whether or not the passed email exists.
E.g.
Request: http://example.com/email_exists.php?email=me#awesome.com
Response: true or false as it may be.
Finally, register an "onChange" or "onBlur" event listener to your input. When it fires, you $.ajax() the email address to the PHP page as described above and check the response. You can then add/remove classes based on the response to give the input element the desired look.

update plain text after change it to a textbox

I have some records from a database that are shown in table rows and columns.
I show this information in plain text. But I want change them to a text box whenever a user clicks them, and update the contents as the cursor is blurred.
I hope I could give my mean.
Is there anybody to help me ?
Here are references to sites and/or projects to help you accomplish your task.
http://www.mysqlajaxtableeditor.com/
http://www.phpclasses.org/package/3104-PHP-Edit-data-in-an-HTML-table-using-AJAX.html
http://www.9lessons.info/2011/03/live-table-edit-with-jquery-and-ajax.html
If you are looking for inline editing, there are plenty of plugins available.
This one looks promising http://www.appelsiini.net/projects/jeditable (haven't tried it)
To turn the contents of a table cell into a test input:
//bind event handler to click event for all table cells
$('td').on('click', function () {
//cache this table cell in a variable
var $table_cell = $(this);
//add a text input with the text of this table cell,
//then select that text input, focus it (so the user doesn't have to click on the text box to gain focus),
//then add an event handler to the text input for the blur event
$table_cell.html('<input type="text" value="' + $table_cell.text() + '" />').children('input').focus().bind('blur', function () {
//run your code to update the text within this <td> element
//sent a POST request to your server-side script with the value of the text-input
$.post('path_to/server/script.php', $(this).serialize(), function (response) {
//here you get the response from the server and you can update the table cell
//if the response from the server is the new text for the cell then you can do this...
$table_cell.text(response);
});
});
});

Categories