AutoSuggest field2 based on field1 selection - javascript

JS is still a little unnatural to me. I can read it alright, but writing it is something I seldom get the chance to do.
I have this form (simplified)
<form>
<div class="form_element">
<label for="co">Cust Company:</label>
<input type="text" name="co" value="" id="co" />
</div>
<div class="form_element">
<label for="contact">Cust Name:</label>
<input type="text" name="contact" value="" id="contact" />
</div>
</form>
I got the auto-complete working just fine for the #co input, but I can use a little guidance getting the next step working.
I need to auto-suggest Names for the #contact input based on the #co selection.
My JS currently looks like this
<script type="text/javascript">
$('input#co').autocomplete({
minLength: 2,
source: function( request, response1 ) {
url_1 = 'company/get_names/'+ request.term +'/name/json'
$.getJSON(url_1, function(companies) {
response1(companies);
});
},
select: function(event, company){
$('input#co' ).val( company.item.value );
//alert(company.item.id); // For testing
url_2 = 'contact/persons_list/'+ company.item.id +'/json'
$('input#contact').autocomplete({
source: function( request, response2 ) {
$.getJSON(url_2, function(people) {
response2(people);
});
}
})
}
});
</script>
How do I get the suggestion-list of people/contacts to show up for the #contact input once a value/suggestion is selected for the #co input?

Well ... I ended up taking a completely different approach, and I think it's much better than my first line of thought.
<script type="text/javascript">
var co_id;
$('input#co').autocomplete({
minLength: 2,
source: function( request, response ) {
url = 'company/get_names/'+ request.term +'/name/json',
$.getJSON(url, function(companies) {
response(companies);
});
},
select: function(event, company){
$('input#co' ).val( company.item.value );
co_id = company.item.id;
}
});
$('input#contact').autocomplete({
//minLength: 2,
source: function( request, response ) {
url = 'contact/persons_list/'+co_id+'/json',
$.getJSON(url, function(companies) {
response(companies);
});
}
});
</script>
It works great!

Related

jQuery UI AutoComplete - How to handle multiple values ,when user removes a value in between the selected values

This is What I have :
I have a text box input element as below for loading cities autoloaded and a hidden field to list its ids:
<label class="col-sm-2 control-label" for="city_disp"> City</label>
<div class="col-sm-5">
<div class="input-group">
<input type="hidden" class="hidden_value" name="city" id="city" value="" />
<input type="text" name="city_disp" placeholder="City"
id="city_disp" data-request_type="cities" value=""
class="form-control autocomplete-input-field" autocomplete="off" />
</div>
</div>
jQuery UI AutoComplete which I use, the data array comes from Ajax response :
function split( val ) {
return val.split( /,\s*/ );
}
function extractLast( term ) {
return split( term ).pop();
}
$(".autocomplete-input-field").autocomplete({
source: function (request, response) {
$this = this.element;
var term = extractLast(request.term);
$.ajax({
url: myHome+'/my_ajax',
dataType: "json",
type: "POST",
data: {
term: term,
action_type: "getdata"
},
success: function (data) {
response(data);
}
});
},
minLength: 2,
select: function (event, ui) {
var tempval = $(this).val() ;
var terms = split( this.value );
var split_string = split(
$(this).closest('div').find('.hidden_value').val() );
split_string.pop();
terms.pop();
terms.push( ui.item.label );
split_string.push( ui.item.value );
terms.push( "" );
split_string.push( "" );
var labels = terms.join( ", " );
var new_vals = split_string.join( "," );
$(this).val(labels);
$(this).closest('div').find('.hidden_value').val(new_vals);
return false;
},
focus: function (event, ui) {
event.preventDefault();
}
});
Output I am getting currently:
Currently,autocomplete is working fine when I type atleast 2 characters in the text box name="city_disp" . If user selects 3 values from the autocomplete cities list: 'New York,Washington,London' and the ids corresponding to these cities '45,56,78' gets appended to the hidden html input field name="city".
Modification which I am trying to implement :
Suppose if user selects 'New York,Washington,London' and its id gets '45,56,78' gets appended to the hidden html input field name="city". and the user removes a Washington from the selected values . Then the hidden value must also change accordingly to '45,78'. Also when a user omits Washington to some absurd characters like 'dasdsad' ,then how to handle such situations with this jQuery UI AutoComplete?
There is not a good way to do this with two unique lists of text. there becomes no relationship between the two except for the positioning. When the User removes and item from List A, how do you identify in List B the change, and align the lists.
Consider moving the selected items to a new User interface with the ID attached.
Example: https://jsfiddle.net/Twisty/m3vfk0hg/
HTML
<label class="col-sm-2 control-label" for="city_disp"> City</label>
<div class="col-sm-5">
<div class="input-group">
<input type="hidden" class="hidden_value" name="city" id="city" />
<input type="text" name="city_disp" placeholder="City" id="city_disp" data-request_type="cities" class="form-control autocomplete-input-field" autocomplete="off" />
</div>
<div class="selected"></div>
</div>
Mostly the same HTML, yet now we have a section to display the Selected items, after they have been selected.
CSS
.selected {
margin: 3px;
}
.selected-item {
border: 1px solid #00f;
border-radius: 6px;
padding: 3px;
background: #ccf;
margin: 3px;
}
.selected-item .btn-close {
margin-left: 6px;
}
Giving us some Style.
JavaScript
$(function() {
var myAutoData = [{
label: "New York",
value: "45"
}, {
label: "Washington",
value: "56"
},
{
label: "London",
value: "78"
}
];
function newItem(it) {
var item = $("<span>", {
class: "selected-item",
"data-id": it.value
}).html(it.label);
$("<span>", {
class: "btn-close"
}).appendTo(item);
if ($("#city").val().length > 0) {
$("#city").val($("#city").val() + "," + it.value);
} else {
$("#city").val(it.value);
}
return item;
}
$(".autocomplete-input-field").autocomplete({
source: function(request, response) {
var term = request.term;
$.ajax({
url: "/echo/json/",
dataType: "json",
type: "POST",
data: {
json: JSON.stringify(myAutoData),
term: term
},
success: function(data) {
response(data);
}
});
},
minLength: 2,
select: function(event, ui) {
$(this).parent().parent().find(".selected").append(newItem(ui.item));
$(this).val("");
return false;
},
focus: function(event, ui) {
event.preventDefault();
}
});
$(".selected").on("click", ".btn-close", function() {
var id = $(this).parent().data("id");
$(this).parent().remove();
var sel = $("#city").val().split(",");
sel = sel.splice(sel.indexOf(id), 1);
$("#city").val(sel.join(","));
});
});
The example uses the JSFiddle options to Echo back JSON data Posted to it. You will want to use your own url and data. I also setup some basinc exmaple items based on your post.
When the User types in a option, wash, they get options they can select. When they click on a selection a new item is created.
<span class="selected-item" data-id="56">Washington<span class="btn-close"></span></span>
This element is appended to the .selected element. This help prevent the user from entering dasdsad, this would return no results, and they cannot select anything.
If the User decides to remove a previously selected item, they click the x and it is removed. Behind the scene, as they make selections, the value of #city is updated to a list of IDs, 56,45. When the User removes an item, the list is updated, and that entry is removed. This is done by converting the list into an Array and using Splice to remove the matching element.

Searchbar website : search by page title instead of page link Javascript

So i'v found this code to search other pages from the main page of my website, and it works great, but the autocomplete shows the link of the page instead of the title of the page , can anyone help me to modify the code ?
<form id="form1" runat="server" class="online-form">
<div class="ui-widget">
<input id="tags" class="form-control" placeholder="Rechercher un serviceā€¦" required="" />
</div>
</form>
<script>
$(function () {
var availableTags = ["page1.html","page2.html","page3.html"];
$("#tags").autocomplete({
source: availableTags,
select: function (e, ui) {
var value = ui.item.value;
window.location.href = "../" + value;
},
});
});
</script>
The best way to make what you want and still continuing using jQuery's autocomplete is to create an additional array with the links. On select we will check the position of the AvailableTags array and then use the new array for the redirect.
<script>
$(function () {
var availableTags = ["Page 1", "Page 2"];
var availableTagsLinks = ["page1.htm", "page2.htm"];
$("#tags").autocomplete({
source: availableTags,
select: function (e, ui) {
var value = ui.item.value;
var indexPos = $.inArray(ui.item.value, availableTags);
window.location.href = "../" + availableTagsLinks[indexPos];
},
});
});
</script>

Glitch in my autocomplete to show jquery validation error?

Hope this question is usefull.
In my autocomplete success I make my input hidden value 1 to avoid
jquery validation and append the current customer name to the
particular input field and all are working fine.
My glitch is if supposed user manually delete the value of input field
which have current customer name, I want to show jquery validation
error. But how can I show that??. Because In my autocomplete success I
made the hidden value 1. So its failed to show the error and I cant check that in keyup or keydown function, Beacuse using that input id I already written the autocomplete.
$(document).ready(function() {
$("#apendexistingCustomer").autocomplete({
autoFocus: true,
source: '{{ url("/getexistingcustomer") }}',
minLength: 2,
select: function(event, ui) {
event.preventDefault();
if (ui.item.label == 'This customer is not in our records.') {
$('#apendexistingCustomer').val('');
$('#existcustomers').val('');
$('#create').valid();
swal("This customer is not in our records.", "", "warning");
} else {
$('#apendexistingCustomer').val(ui.item.label);
$('#existcustomers').val(ui.item.key);
$('#create').valid();
getCustomerDet(ui.item.key);
}
},
focus: function(event, ui) {
selectFirst: true;
event.preventDefault();
},
open: function(event, ui) {
$(this).autocomplete("widget")
.appendTo("#results").css({
'position': 'static',
'width': '100%'
});
$('.ui-autocomplete').css('z-index', '9999999');
$('.ui-autocomplete').addClass('srchuser-dropdown');
}
}).data("ui-autocomplete")._renderItem = function(ul, item) {
return $("<li style='height:60px;'><span class='srchuser-downname'>" + item.label + "</span></li>").data("ui-autocomplete-item", item).appendTo(ul);
};
});
this is my function to fetch customer details using autocomplete
protected function getexistingcustomer() {
if (Request::ajax()) {
$data = Request::all();
$searchVal = $data['term'];
if ($searchVal != '') {
$searchResult = customers::searchCustomerAutoComplete(trim($searchVal));
}
$finalArr = array();
if (!empty($searchResult)) {
foreach($searchResult as $vk => $sf) {
$finalArr[$vk]['label'] = $sf['firstname'].
''.$sf['lastname'];
$finalArr[$vk]['key'] = 1;
}
} else {
$finalArr[0]['label'] = 'This customer is not in our records.';
}
print json_encode($finalArr);
exit;
}
}
customer Input field
<div class="row" id="selectcusDiv">
<div class="col-12 col-sm-6 col-md-4">
<div class="form-group">
<label><sub>*</sub>Customers</label>
<div class="select-container">
<input type="text" id="apendexistingCustomer" name="apendexistingCustomer" class="form-control fieldcls">
<input type="hidden" id="existcustomers" name="existcustomers" value="" class="form-control fieldcls">
</div>
</div>
</div>
</div>
Jquery Validation
$('#create').validate({
ignore: [],
rules: {
existcustomers: 'required'
},
messages: {
existcustomers: 'please enter'
}
});
In your javascript add a change listener to the autocomplete element, and check for an empty value. If the value is empty, set the "avoid validation" flag hidden input to 0, then use a required validation rule on that element.
$("#apendexistingCustomer").on("change", function(){
if($(this).val() == ""){
$("#validateFlag").val(0)
}
});

Grails - jQuery Autocomplete with Multiple Values

The single value autocomplete is working fine (thanks to people who helped me with it.) but when I tried the jQuery UI's multiple value example, it is not getting the source I need.
This is my controller.
def courseList = {
def cList = Course.withCriteria {
ilike 'course', params.term +'%'
}
render (cList.'course' as JSON)
}
This is my _form view.
<div class="fieldcontain ${hasErrors(bean: studentInstance, field: 'courses', 'error')} required" >
<label for="course">
<g:message code="student.courses.label" default="Courses" />
<span class="required-indicator">*</span>
</label>
<g:textField name="course" id="coursetags" required="" value="${course?.course}"/>
This is my jQuery script (exactly from jQuery UI demo).
function split( val ) {
return val.split( /,\s*/ );
}
function extractLast( term ) {
return split( term ).pop();
}
var courses = ["English", "Music", "Science"];
$( "#coursetags" )
// don't navigate away from the field on tab when selecting an item
.bind( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB && $( this ).autocomplete( "instance" ).menu.active ) {
event.preventDefault();
}
})
.autocomplete({
minLength: 2,
source: function( request, response ) {
// delegate back to autocomplete, but extract the last term
response( $.ui.autocomplete.filter( courses, 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;
}
});
When I have var courses tag inside the script, the multiple-values-autocomplete works. How would I connect autocomplete's source to my controller?
For the single value, this is what I had in my script.
$("#coursetags").autocomplete({
source: "/myApp/student/courseList",
minLength: 2
});
Thank you in advance.
I found this demo. https://github.com/jquery/jquery-ui/blob/master/demos/autocomplete/multiple-remote.html
source: function( request, response ) {
$.getJSON( "/myApp/student/courseList",
{term: extractLast( request.term )},
response );},
I replaced source part and it works now.

using jquery-ui autocomplete with multiple input fields

good afternoon all!
i spared a lot of time, read all posts on stackoverflow... and i am not able to make autocomplete working with multilpe input fields.
I tried to attrib a 'autoc' class to each input, i use a different id for each field (in fact the inedx of the php loop generating fields).
I do not ask someone to do the job for me.... just a working example.
Thanks in advance.
PS : I apologize for my poor english...
now follows a piece of html :
<input id="search_ctO" class="autoc" type="text" name="search_ct[]">
<input id="search_ct1" class="autoc" type="text" name="search_ct[]">
<input id="search_ct2" class="autoc" type="text" name="search_ct[]">
....
<input id="search_ctn" class="autoc" type="text" name="search_ct[]">
and jquery :
$('.autoc').on("focus", function()
$(this).autocomplete({
minLength: 2,
source: 'liste_contact.php',
select: function( event, ui ) {
$('.autoc #search_ct').val( ui.item.label ); //id="search_ct'.$i.'
$(".autoc #contact_id").val( ui.item.value ); //
$("autoc #contact_description").val( ui.item.desc );
return false;
},
change: function(){
var servi = $("#service_id").val();
var hop = $('#hop').val();
var contact = $("#contact_id" ).val();
$.ajax({
url: 'ajout_contact.php',
data: "serv="+ servi+"&hopit=" + hop+"&contact="+ contact+"",// on envoie la requete d'ajout de contact
success: function() {
$("#search_ct").val('');
// location.reload(true);
}
Without knowing the exact HTML and the object array passed to autocomplete source, it is difficult to make your code exactly.
However, you have asked about working of autocomplete for multiple fields, so here is just a simple example:
HTML
<input id="search_ctO" class="autoc" type="text" name="search_ct[]"/>
<input id="search_ct1" class="autoc" type="text" name="search_ct[]"/>
<input id="search_ct2" class="autoc" type="text" name="search_ct[]"/>
<input id="search_ctn" class="autoc" type="text" name="search_ct[]"/>
JS
var tags = ["abc","def","xyz"];
$('.autoc').on("focus", function(){
$(this).autocomplete({
minLength: 2,
source: tags
});
});
JSFIDDLE DEMO
If there is any other thing you want to be included in answer, feel free to comment.
EDIT
Your code,
$('.autoc').on("focus", function() {
$(this).autocomplete({
minLength: 2,
source: 'liste_contact.php',
select: function( event, ui ) {
$('.autoc #search_ct').val( ui.item.label );
$(".autoc #contact_id").val( ui.item.value );
$(".autoc #contact_description").val( ui.item.desc );
return false;
},
change: function() {
var servi = $("#service_id").val();
var hop = $('#hop').val();
var contact = $("#contact_id" ).val();
$.ajax({
url: 'ajout_contact.php',
data: "serv="+servi+"&hopit="+hop+"&contact="+contact+"",
success: function() {
$("#search_ct").val('');
}
});
}
});
});

Categories