text field autopopulate from database using javascript - javascript

I want to get data from database to text field by using autopopulate when i type data in text field using javascript can any one help to me please

One of the way to solve that is for instance to use autocomplete control from jquery.ui and create service using language/server of your choose to get data from your db.
Configuring jquery.ui autocomplete is as simple as
var availableOptions = ["apple", "pear", "pineapple"]
$( "#auto" ).autocomplete({
source: availableOptions
});
just having input control
<div>
<label for="auto">Fruits: </label>
<input id="auto" />
</div>
So if you dont have thousands of data items above is one of the easiest ways.
Alternatively, having implemented web service you can query it ajax-style, configuring autocomplete plugin right way
$('#auto').autocomplete({
source: function( request, response ) {
$.getJSON( "/api/search", {
term: request.term
}, response );
},
search: function() {
var term = this.value
if ( term.length < 2 ) {
return false;
}
}
})

Related

fetch db mysql value in search input field and modifying in dropdown

I cannot find a solution for my problem because for me it is an advanced level of programming.
I have a custom search field, but I need to 'convert it' in a dropdown menu that fetching some users values in mysql, avoiding writing hundreds of selection options.
This is the registration form field Im working it
<tr class="user-luogo-wrap">
<th><label for="luogo">
Luogo: </label></th>
<td><input type="text" name="luogo" id="luogo" value="Treviso" class="regular-text"></td>
</tr>
Created with a function
function my_user_contactmethods( $user_contactmethods ){
$user_contactmethods['luogo'] = 'Luogo:';
return $user_contactmethods;
}
add_filter('user_contactmethods', 'my_user_contactmethods', 5);
and this is the field where I need to fetch the 'luogo' mysql values and modifying it in dropdown
<div class="um-search-filter um-text-filter-type "> <input type="text" autocomplete="off" id="luogo" name="luogo" placeholder="Luogo" value="" class="um-form-field" aria-label="Luogo"></div>
I hope I have explained it well. Can someone help me?
In Console I have found the Form data , Request payload generated after a search action:
directory_id=3f9fc&page=1&search=&sorting=display_name&gmt_offset=8&post_refferer=61&nonce=f47827a450&luogo=boston&action=um_get_members
So Im trying to modify this function
function field_choices( $field ) {
// reset choices
$field['luogo'] = array();
// get the textarea value from options page without any formatting
$choices = get_field('my_select_values', 'option', false);
// explode the value so that each line is a new array piece
$choices = explode("\n", $choices);
// remove any unwanted white space
$choices = array_map('trim', $choices);
// loop through array and add to field 'choices'
if( is_array($choices) ) {
foreach( $choices as $choice ) {
$field['luogo'][ $choice ] = $choice;
}
}
// return the field
return $field;
}
add_action('um_get_members', 'field_choices');
Is my intuition correct?

Issues with search bar filter, using JS/JQuery in laravel blade template

I have a blade template with a search bar, which has no submit button and is used for filtering. However, I can't seem to get it to filter appropriately, as the page was originally using angular (which has been removed completely).
My page displays all of my products using foreach loops and displays the info from variables in my page controller (pulling everything from the database and storing as variables). Anyway, everything displays fine but I need help getting this to filter properly.
Basically, if a term entered in the search bar is anywhere in the JSON object gathered by the controller, then I want it to only display those objects. I may even need another foreach loop.
Here's the html/blade code:
<!--Search bar div-->
<div class="uk-width-5-10">
<div class="md-input-wrapper search-form">
<form id="searchProducts">
<input type="text" class="md-input label-fixed" name="srch-term" id="srch-term" autofocus placeholder="Search Products"/>
<span class="md-input-bar"></span>
</form>
</div>
<!--foreach loops around the wrapper that shows products, for reference-->
#foreach ($orderFormData->pgroups as $pgroup)
#foreach ($pgroup->image_names as $image_name)
#foreach ($pgroup->pskus as $psku)
Javascript for the search (see the variable for the JSON object, that's what I need to search within)
<script>
var orderFormData = <?php echo json_encode ($tempdata);?>;
</script>
<script>
var orderData = orderFormData // default value
var search = function (e) {
var term = e.currentTarget.value
orderData = Object.entries(orderFormData).reduce(function (data, entry) {
if (entry[0].match(term) || entry[1].match(term)) {
data[entry[0]] = entry[1]
}
return data
}, {})
console.log(orderData)
}
document.querySelector('#srch-term').addEventListener('keyup', search)
</script>
Is there a better way I should be doing this? I may even need to do a foreach loop around the search bar
It kind of sounds like you're looking for an auto complete. Have you looked at the jquery-ui-autocomplete library? It's pretty easy to implement, and might add more functionality more easily than writing loops yourself.
https://jqueryui.com/autocomplete/
I'll get into why I named the function below, but here's my implementation:
monkeyPatchAutocomplete();
$("#your_searchbox_selector").autocomplete({
source: // http://Your_Search_URL_endpoint_here,
delay: 500, // prevents search from running on *every* keystroke
minLength: 1, // default is 2, change or remove as you like
// open page after selecting (with enter key).
select: function( event, ui )
{
var qval = ui.item.id // this pulls whatever field you're looking for in your JSON that you want to use to direct your user to the new page, in my case "id";
var url = 'http://whereever_you_want_your_user_to_go?';
window.location = url + qval;
}
});
For my implementation, I wanted to color code the results in my autocomplete list with active and inactive entries, so my search controller JSON result includes 3 fields:
'value' => $searchable_values, 'id' => $id_mapping_of_whatever, 'class' => $css_classes_to_use
My search controller plugs in emails, names, and phone numbers to the value field, which is searchable, then maps an id, and plugs in css classes that I use to change the text color of the results through a monkeypatch on jQuery's autocomplete:
function monkeyPatchAutocomplete()
{
$.ui.autocomplete.prototype._renderItem = function( ul, item)
{
var re = new RegExp(this.term, 'i');
var t = item.label.replace(re,"<span class='autocomplete-span'>" + this.term + "</span>");
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a class='text-" + item.class + "'>" + t + "</a>" )
.appendTo( ul )
};
};
If you're interested in formatting your results, check out dev.e.loper's answer to: How can I custom-format the Autocomplete plug-in results?.

Javascript populates input, but not span?

I am using Select2 dropdown menu to get data from database threw ajax and json/php.
The option i make will then populate some input fileds for editing the database.
I use (This field get´s populated ok):
<input type="text" class="form-control" name="valt_element_id" id="valt_element_id" placeholder="Objekt ID" />
But on some field i just want to show the data, not to be edited.
I figured to use:
<span id="valt_element_id"></span>
But this span code won´t work!
Why?
JS:
$(document).ready(function(){
var valtObjektElement = $('#valj_objekt_element');
$('#valj_objekt_element').select2({
ajax: {
url: "valj_objekt_element.php",
dataType: 'json',
data: function (term, page) {
return {
q: term
};
},
results: function (data, page) {
return { results: data };
}
} // Ajax Call
}); // Select2
// Start Change
$(valtObjektElement).change(function() {
var ElementId = $(valtObjektElement).select2('data').id;
var ObjektNummer = $(valtObjektElement).select2('data').text;
$('#valt_element_id').val(ElementId);
$('#valt_objekt_nummer').val(ObjektNummer);
}); //Change
}); //Domument Ready
There is no value attribute for span. You should either use text or html.
Replace
$('#valt_element_id').val(ElementId);
with
$('#valt_element_id').text(ElementId);
Using javascript:
document.getElementById("valt_element_id").innerHTML = ElementId;
Or jQuery:
$('#valt_element_id').html(ElementId);
You mentioned:
But on some field i just want to show the data, not to be edited . Why not use readonly attribute in input rather than replacing it with a span ?

Predictive Dropdown Input

I have a table called contacts, where each user stores the username of his contacts:
$result = mysql_query("SELECT * FROM contacts WHERE sender='".$_SESSION ["username"]."'");
$row = mysql_fetch_array($result);
My page is used to compose a message to an user. So when a user types in the textfield I need to show a dropdown list matching names from his contacts (as in Gmail).
<input name="reciever" type="text" value="" class="inputs3" placeholder="Enter the username"/>
I searched a lot, but couldn't find any working script.
Take a look at this auto complete sample, Demo / JSFiddle
autocomplete({
minLength: 1,
source: function( request, response ) {
//check if the request string starts with a space
if(request.term===' ')
{
response([{value: "Enter Some text to search"}]);
return false;
}
// delegate back to autocomplete, but extract the last term
response( $.ui.autocomplete.filter(
availableTags, extractLast( request.term ) ) );
}
This will give autocomplete coding idea

Jquery auto complete feature in combo box with unique values

I'm using Jquery ui autocomplete plugin in a combo box and I'm reading the values from a JSON file. The problem is in my JSON file. I have fields with same value. Like this.
({
name:a
},
{
name:a
},
{
name:b
})
So when I type 'a' in combo box, it gives me 2 'a' s. But I need only one (I need only the unique values from JSON file). How do I do this? I do not have the complete code right now, that's why I cant put it. Sorry about that and thank you.
EDIT: You could use something like this to remove duplicate entries from the json array before sending that data to the jQuery autocomplete plugin.
var names = {};
var param = "name"
$.each(data.people, function() {
if (!names[this[param]])
names[this[param]] = [];
names[this[param]].push(this);
});
Then we can do source: names
try this.... only unique values can be added in input field
select: function( event, ui ) {
var terms = split( this.value );
// remove the current input
terms.pop();
// add the selected item
if(!($.inArray(ui.item.value,terms) > -1))
terms.push( ui.item.value );
// add placeholder to get the comma-and-space at the end
terms.push( "" );
this.value = terms.join( ", " );
return false;
}

Categories

Resources