jQuery: Using autocomplete to add values to two fields instead of one - php

I want to use the autocomplete plugin for jQuery to populate not one, but two fields when selecting one of the autocomplete values - the name of a band is entered in the #band input field, but the band url (if exists) should also automatically be added to the #url input field when selecting the band name.
Right now I simply have an un-pretty list in an external php file from which the autocompleter takes it's values:
$bands_sql = "SELECT bands.name, bands.url
FROM bands
ORDER BY name";
$bands_result = mysql_query($bands_sql) or print (mysql_error());
while ($bands_row = mysql_fetch_array($bands_result)) {
$band_name = $bands_row['name'];
$band_url = $bands_row['url'];
echo $band_name."\n"; #needs to be replaced with an array that holds name and url
}
My autocomplete function looks very basic atm, but as I'm an absolute beginner when it comes to jQuery (and also clueless when it comes to PHP arrays), I have no idea how to tell it to populate two fields and not one.
$(document).ready(function() {
$("#band").autocomplete('/autocomplete-bands.php');
});
Is that even possible?!

sure check use result hadler so you can then do what you want once a choice has been made

I don't know about the particular plug-in you are using, but I would use the autocomplete widget for jQuery UI instead of a third party plug-in.

Here is an example of what you are looking for:
$("#band").autocomplete('/autocomplete-bands.php').result(function(event, data, formatted) {
if (data)
$('#url').(data['url']);
else {
// no data returned from autocomplete URL
}
});
I don't know much about php, but whatever the format of your data that is returned should be put where the data['url'] is currently in order to populate the #url input.

Related

Change the value of second select on first select

I'm sorry I haven't included "my attempt" as such with this one, I'm useless with jquery so need some advice!!
I would like to change the value of a second selctor based on the results of the first.
I have a database of builders and regions with the headers builder_name and builder_region. The list ends up looking like this ...
builder_1 region_1
builder_1 region_2
builder_2 region_1
builder_3 region_1
builder_3 region_2
builder_3 region_3
(You get the idea)
I'm using the following in the form I've built to get a list of the builders for the first select box ...
echo '<select class= "ml-select" name="gen_builder">';
echo '<option value=" ">Select Builder</option>';
while($row = mysql_fetch_array($rsBUILDER)) {
if($linebreak !== $row['builder_name']) {
echo '<option value="'.$row['builder_name'].'">'.$row['builder_name'].'</option>';
}
else {echo "";}
$linebreak = $row['builder_name'];
}
echo '</select>';
The $linebreak is to get rid of the duplicate builder names from the list, which works a treat.
What I would like to achieve is a second selector that selects the regions available, dependant upon the builder that has been selected in the first option. I hope this makes sense????
The second query needs to look at the builder selected in the first selector and filter out just the regions that are in rows with the builder name form selector one.
Please do say if you need further information, I'm not great at explaining myself.
As you said you don't have experience with jQuery or Ajax, I'll post my answer with as many comments as possible. I will assume that you have two select dropdowns in your page.
The first one contains the builders, so it will have id="builders".
The second one contains the regions, so it will have id="regions".
From what I understand, the first select will be exactly the one you posted in your question, generated server-side (by PHP). I only ask that you please make a slight change on it, making each option value be equal to the builder's database ID, and not its name (unless the builder's primary key is their name, and not an ID). This will make no difference for the final user but will be important for our jQuery solution. The second one will be empty, as the idea is to fill it dynamically with the regions related to the builder selected in the first dropdown.
Now let's get to the jQuery code:
//Everything that goes below this first line will be ready as soon as the page is fully loaded
$(document).ready(function() {
//The following code defines an event. More precisely, we are defining that the code inside it will run every time our select with id "builders" has its value changed
$('#builders').change(function() {
//$(this) is our builders select. $(this).val() contains the selected value, which is the ID of our selected builder
var currentValue = $(this).val();
//Now, this is our Ajax command that will invoke a script called get_regions.php, which will receive the builder's ID in $_GET['builder_id'] and you can use to query your database looking for all regions related to this builder. Make sure to create an array with the returned regions. Your get_regions.php's last line should be echo json_encode($regions);
$.get("get_regions.php", {'builder_id': currentValue}, function(data) {
//Inside this function is the code that will run when we receive the response from our PHP script. It contains a JSON encoded list of regions, so first of all we need to parse this JSON
var regions = $.parseJSON(data);
//Before filling our second select dropdown with the regions, let's remove all options it already contains, if any
$('#regions').empty();
//Now, all there is left is to loop over the regions, adding each as an option of the regions dropdown. I'll do it the universal way
for (var i = 0; i < regions.length; i++) {
var regionOption = '<option value="'+regions[i]['region_name']+'">';
regionOption += regions[i]['region_name'];
regionOption += '</option>';
$('#regions').append(regionOption);
}
});
});
});
Despite any syntax errors (can't test the code from here) this should do the trick. Hope the comments were clear enough for you to understand how things work in jQuery.

jquery pull textarea values based on which checkboxes were checked

I'm working on a project that involves returning the id of the checkboxes chosen as well as the text in the corresponding textarea fields for those chosen checkboxes. The data is dynamically displayed and so far my jquery pull of both the checkboxes and textareas work:
var noteList = $("textarea[name='revokeNotes']").map(function(){
return this.value;
}).get().join();
var revokeList = $("input[name='revoke']:checked").map(function(){
return this.id;
}).get().join();
but I'm getting back all of the notes fields and I'm uncertain how to best iterate through them to find the proper notes as their ids aren't sequential but rather based on their id in the table they are being pulled from. The last version of the display code is below:
<td><textarea name=\"revokeNotes\" id=\"".$v["id"]."\" cols=\"30\"rows=\"3\">".$v["notes"]."</textarea></td>
<td><input type=\"checkbox\" id=\"".$v["id"]."\" name=\"revoke\" value=\"".$v["id"]."\" /></td>
Is there a way to reach my goal from this state or should I be using another jquery function, similar to .map()? I thought about using the id field from the checkboxes to iterate through the selected notes and pushing them into an array but I'm not sure 1) if that will work and 2) how to do that.
I need the data back in some form either an array or something I can explode on in php to create an array as I'm passing one value in ajax as there is no set maximum or minimum number of rows that will be displayed per user. Map was working until I threw some commas at it. Extra points for that.
var noteList = $.map(
$("textarea[name='revokeNotes']").filter(function() {
return $(this).closest('td')
.next('td')
.find('input[type="checkbox"]')
.is(':checked');
}), function(el) {
return el.value;
}).join();
adeneo's answer is great, I'd just propose the following improvements:
If possible use class selectors (like '.revoke-notes-area') since those are faster than DOM + attr selectors
Assuming this is a table and there is one textarea checkbox combo per row, you can traverse the tree to the closest <tr> a decouple the JS from depending that the checkbox comes after the text area in the DOM.
var filterMethod = function() {
$(this).closest('tr').find('.revoke-checkbox').is(':checked');
};
var mapMethod = function(el) {
return el.value;
};
var nodeList = $.map($('.revoke-notes-area').filter(filterMethod), mapMethod);
There's no reason you cannot or should not put the filter and map methods inline, I just split them out into variables so it's easier to read here.
You can check out my codepen here: http://codepen.io/aaron/pen/eIpby.

jQuery UI autocomplete gets has suggestions but doesn't display them

I have a jQuery autocomplete script in my page, and if I type in the field it works on, and as requested after 3 characters, the drop containing the expected number of suggestions pops down...sort of...as there is no text in the drop down.
If I mouse over the drop down as though I were selecting one of the suggestions, a narrow bar shows a highlight for each row where a suggestion would be, but selection of one of the empty highlights empties the field. This is not surprising. I don't really understand the handling of the return data. I have seen very simple and complex code in autocomplete examples in other posts in these forums, but using the ones I thought I understood has usually broken it to the point where I don't get the drop down at all. Thus I'm unashamedly looking for someone to provide me with the code that works so I can pick it apart and work out how it works.
My basic JS code is:
$("#tf_txt_CLIENTNAME").autocomplete({
source: "search.php",
minLength: 3,//search after three characters
dataType: 'json',
select: function(event,ui){
//do domething
}
It's the do something area I just can't get right. As I said, I've tried too many variations of code in that space to mention here, and all of them broke it completely.
search.php produces the following JSON output for input of 'bra':
[{"txt_CLIENTNAME":"Braedon"},{"txt_CLIENTNAME":"Bradly"}]
from the following PHP source (borrowed and modified from another web source):
<?php
require_once 'includes/dbiconnect.php';
require_once 'includes/sqlfunctions.php';
$term = trim(strip_tags(addslashes($_GET['term']))); //retrieve the search term that autocomplete sends
$qstring = "SELECT `txt_CLIENTNAME` FROM `tbl_client_details` WHERE `txt_CLIENTNAME` LIKE '%".$term."%'";
$result = mysqli_query($db_link,$qstring); //query the database for entries containing the term
while ($row = mysqli_fetch_assoc($result)) {//loop through the retrieved values
$row['txt_CLIENTNAME']=htmlentities(stripslashes($row['txt_CLIENTNAME']));
$row_set[] = $row; //build an array
}
echo json_encode($row_set); //format the array into json data
?>
I simply would like it to display what it finds and plonk the one I select into the value of the text field. I can then update the other fields I want to populate (company, phone # & e-mail) using $.POST triggered by the onchange event for that field (I'm sure there are better ways to do that, but I understand how to do that for the moment).
I'm using jQuery 1.7.2 and jQuery UI 1.8.22. I have the latest jquery toolbox loading as well without the tabs component, but removing it has made no difference.
Thanks in advance,
Braedon
As per Jquery UI guide,
your JSON needs to contain label or value (or both)
You need to change your json as below
while ($row = mysqli_fetch_assoc($result)) {//loop through the retrieved values
$row['txt_CLIENTNAME']=htmlentities(stripslashes($row['txt_CLIENTNAME']));
$row_set[] = array('label'=>'txt_CLIENTNAME','value'=>$row['txt_CLIENTNAME']); //build an array
}

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.

AJAX Controlled Multiple Select Box Strategy

I've done some reading on AJAX, and would like to create a listbox, that controls what is displayed in a separate textbox located within the same form. The backend of the website is handled in php, and the possible values and whatnot is stored within the MySQL database via php. What's the best way of obtaining the listbox values as well as the textbox values, and if your answer is JS, how do I create multiple selects in JS?
Well this is really a wide theme question.
My approach would be to create a listbox with php and put an onchange event that will call an ajax with value parameter, that ajax call will fill textbox.
You should use jquery, read some documentation here http://docs.jquery.com/Main_Page
multiple select listbox
<select id="choices" multiple="multiple" .. >
If you were using jQuery you could do something like:
$("#choices").change(function() {
var choices = {};
$("#choices option:selected").each(function() {
choices[this.id] = $(this).val();
});
$.post("http://example.com/choice_handler.php", choices, function(content) {
$("#textarea").val(content);
});
});
choice___handler.php would look at $_POST to retrieve the id/value pairs and produce content that would be returned and then assgned as the value of a textarea.
Note: i haven't tested/debugged any of this - just some code sketching here

Categories