Autocomplete: populate multiple fields based on selection - php

I have a form, and there are 5 fields. The first field is an autocomplete field. I'd like to have the other 4 fields populated based on the autocomplete field selection. The docs in github ajax.autocompleter page reference setting an id and using a js function to call the id value, but this doesn't seem efficient if using multiple fields/need multiple values in addition to the ac value.
I'm using scriptaculous, and php. I have the autocompleter functioning, but am not sure on the rest of it. I'm also not clear on how to set the additional field parameters on the php end. I suppose that I could set the id="field1Val='blah'&field2Val='blah2'" then use js to parse and populate fields, but something about that just doesn't feel right.
Any idears?

this is what we use: a jquery plugin. The good thing about this one is that you can add a callback function that allow you to change the "current" behavior.
about the line 385 you have function that parses the result:
function parse(data) {
var parsed = [];
var rows = data.split("\n");
for (var i=0; i < rows.length; i++) {
var row = $.trim(rows[i]);
if (row) {
row = row.split("|");
parsed[parsed.length] = {
data: row,
value: row[0],
result: options.formatResult && options.formatResult(row, row[0]) || row[0]
};
}
}
return parsed;
};
you can create your own function that depending on what you get (you can send a json from the server) and then execute javascript and drive the form controls.
hope help you

Related

Autocomplete in the text box in PHP, Ajax and MySQL

Using Autocomplete text box to retrieve the data from the MySQL database table. my Ajax coding is working to retrieve the small amount of data. In my database table, I have more 300,000 records. The coding is not working when I used large data.
Please give suggestion about to retrieve a large data.
Which method is best to retrieve the data.
See my coding. It works fine to retrieve a small amount of data
<input type="text" name="protein_name" id="protein_name">
$("#protein_name").keypress(function (e){
var protein_name = $("#protein_name").val();
if(protein_name != "") {
$.ajax({
url: '<?php echo base_url(); ?>/index.php/Protein_Main/protien_search',
data: {protein_name: protein_name},
dataType: "json",
type: "POST",
success: function (res) {
$("#protein_name").autocomplete({
source: res
});
}
});
} });
PHP Coding
$query = $this->db->query("SELECT `Name_of_the_Protein` FROM `protein` WHERE Name_of_the_Protein Like '".$protein_name."%'");
$protein = $query->result();
echo json_encode($protein);
Autocomplete requires a few things.
An input element
<input type="text" id="nmRecipientSearch">
A couple of local javascript arrays:
(One containing a list of potential selections, and another with numeric unique ids corresponding to each selection)
var aryRecipientsFull=["Aaron","Adon","Andrew"];
var aryLrId=["1","2","3"];
A javascript .autocomplete handler bound to the input element:
$( "#nm_recipient_search" ).autocomplete({ source: aryRecipientsFull,
select: function( event, ui )
{
var numPosition,numLrId = 0;
//Find the index position within the array for the selected item (e.g. Adon)
numPosition=aryRecipientsFull.indexOf(ui.item.label);
//Set a variable to the numeric value corresponding to the selected item (e.g. 2)
numLrId=aryLrId[numPosition];
//Populate a hidden input field (nm_lr_id) to the numeric value
$('#nm_lr_id').val(numLrId);
//Set the focus to the next field once a selection has been made
$('#nm_text').focus();
}
});
A CSS style to ensure the autocomplete results appear above everything else:
ul.ui-autocomplete
{
z-index: 1100;
}
A couple of things to consider:
I'd recommend starting off using static arrays just to ensure that the UI looks okay
If you need to (re)populate the arrays dynamically then you may need to bind a .keyup event to the search field, perform an AJAX call to a PHP page which then does a query as you've suggested, but make sure that you limit the number of resulting records (perhaps 10 or 20 records).
Simply add "LIMIT 20" to the end of your SELECT query to achieve this.
I hope that helps.

array of same id using getElementById error

i want to create array of same id or name using getElementById..
i have a "add button", when the user press this button, its generate a dropdown list(dynamic) which the value is get from mysql..
and its looks like this when the user press 3 times..
i want to create an array of this id, and store it to mysql..
this is my JS code :
var menu_paket_array = document.getElementById('menu_paket').value;
alert(menu_paket_array);
the problem is, when i try to create this array(menu_paket_array), the value in this array is just the first id (Test 1) only..
how can i fix this?
thanks...
Using the same id for more than one element is wrong. Id is to uniquely identify certain element. Using it for more elements defeats its -purpose. If you need that for i.e. CSS styling, then use class instead, which is designed just for such scenarios.
An ID must be unique on a page. You can only use it on one element.
Instead, use a CSS class or element type to iterate (here's a fiddle demonstrating this code):
function alertValues() {
var select, selects = document.getElementsByTagName('select');
var out = "";
for (var i = 0; i < selects.length; i++) {
select = selects[i];
if (select.className && select.className.match(/CLASSNAME_TO_INCLUDE/)) {
out += select.options[select.selectedIndex].value;
}
}
alert(out);
}
A better solution, of course, would be to utilize a dom library like jQuery or mootools, with which you could do something like this:
jQuery(function($) {
vals = [];
$('select.CLASSNAME').each(function() { vals.push($(this).val()); });
alert(vals.join(','));
});
document.getElementsByClassName(names);
Where names is the classname u generate for each one.
Instead of assigning each element with id='menu_paket' (for the reasons #WebnetMobile.com explained) assign class='menu_paket'.
Instead of var menu_paket_array=document.getElementById('menu_paket').value;, do
var temp_array = document.getElementsByClassName('menu_paket');
var menu_paket_array = [];
for(i in temp_array){
menu_paket_array[] = temp_array[i].value;
}

Javascript multiple values on the same ID

I have a loop in php that echos out a <input type="hidden" id="lol" value=$id />
Every time the loops go through i get a new value in the hidden input field as you can understand.
Now, im trying to grab the value from each of these items and get grab it with Javascript and SAJAX.
The javascript im using now works, But! It only grabs the first value (because the ID is the same on each input)
Javscript:
function Showbooking() {
id = document.getElementById('lol').value;
x_showBookingForm(id, do_showBookingForm);
}
function do_showBookingForm(html) {
openPopup(600, 550, html);
}
As you can see im opening a POPUP with javascript aswell and exports the value into that popup window.
So on every popup I get the same value (the value from the first input).
How Do I get around this problem?
Change ID to name
Use document.getElementsByName and loop
var lols = document.getElementsByName("lol");
var vals=[];
for (var i=0, n=lols.length;i<n;i++) {
vals.push(lols[i].value);
}
alert(vals.join(","));
getElementById says element rather than elements because it returns only one item. id is supposed to be unique. You could do something to the effect of:
var inputs = document.getElementsByTagName("input");
var values = [];
for(var i=0;i<inputs.length;i++){
if(inputs[i].type === "hidden"){
values.push(inputs[i].value;
}
}

Using one <form>'s selection to feed into another <form>?

From within php, I have a large html <form> filled out with lots rows of patient info from a postgres database. When a doctor double-clicks on a row, it sets a var in $_POST and invokes another php script to read up and display specific info about that row from the database. This all works.
But there are now so many rows of patient data that the doctors don't want to scroll and scroll to find the patient rows they're looking for, they want a patient prefilter <form> so that a click on an element in it will result in the large display filtered to just that patient's rows.
What's a basic approach to doing this? I'm a newb; I'm currently using html, php, and some javascript.
Make a second form with whatever options you'd like to filter on, this part will be specific to your data but you want something like
<form id="search-form">
<label>Name:</label><input type="text" name="patient-name"></input>
</form>
You'll need to build a query string (and make sure you use GET, because that will make things easier for you). This will require tweaking if you want to use radio buttons, or something similar, but here's the general idea:
function getSearchParameters () {
var form = document.getElementById('search-form');
var inputs = form.getElementsByTagName('input');
var result = '';
var i;
for (i = 0; i < inputs.length; i++) {
if (inputs[i].value) {
result += "&" + inputs[i].name + "=" + inputs[i].value;
}
}
return result;
}
In the onClick handler for your patient data links, you'll call this function and append its result to your query string:
element.onclick = function () {
var patientDataUrl = '/patients.php?param1=someValue';
patientDataUrl += getQueryParameters();
/* then do your ajax stuff as normal */
};
Then on the server side, within patients.php simply check for the presence of the search fields i.e.
if(isset($_GET['patient-name'])) {
$patient_name = mysql_real_escape_string($_GET['patient-name']);
$query = "SELECT * FROM `patients` WHERE `patient_name`='$patient_name';";
} else {
$query = "SELECT * FROM `patients`;";
}
(make sure you sanitize the string!)
I'd recommend considering a JS framework to make your life much easier (for instance, jQuery would allow you to send this via POST or easily serialize it into a GET query string via .serialize())

Input show the number of form fields with data (jQuery)

I have a long form and I need to count the number of inputs and textareas that have data inside them. I need an input field that will display a number representing the number of inputs and textareas that have data within my form.
I prefer jquery or PHP.
Are there any examples out there or suggestions?
Thanks.
Erik
With jQuery you can just use this
var number = $('#form').find('input, textarea')
// filter out every empty input/textarea
.filter(function() { return $(this).val() == ''; })
.length;
You could do an onkeypress function that runs and updates your div with the number of fields that have data.
Off the top of my head but maybe:
function tallyFields() {
var totalFilledFields = 0;
var fieldAVal = document.getElementByID("fieldA").value;
// add more fields here the same way
if(fieldAVal.length > 0) {
totalFilledFields++;
}
// check more fields here the same way and increment the same var
document.getElementByID("yourTotalDiv").innerHTML=totalFilledFields;
}
Assigning this function onkeypress of each of your form fields might do the trick.
This should do the trick:
$(".myform :input").length;

Categories