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('');
}
});
}
});
});
Related
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.
I have an HTML form with dynamically add more fields. For example company name. I am trying to use the jQuery validate method to validate. It is working fine with the existing company name field. Here is the code.
<script>
$("#company_creation_form").validate({
rules:{
company_name: {
required: true,
minlength: 3
}
},
submitHandler: function (form) {
$.ajax({
type: "POST",
url: "<?php echo BASE_URL;?>crm/thankyou/",
data: $(form).serialize()+"&company_count="+company_count,
success: function () {
alert("thanks");
}
});
return false; // required to block normal submit since you used ajax
}
});
</script>
When I click on add more button another company name field will create on the form. The below code is failed to validate the dynamically generated field. Here I am getting the field count globally in this variable company_count
<script>
$("#company_creation_form").validate({
rules:{
company_name: {
required: true,
minlength: 3
},
I tried like below, but this is giving me error
if(company_count> 0){
var new_field = jQuery("#company_name"+company_count);
new_field : {
required: true,
minlength: 3
},
}
The above block code is showing error in the text editor it self
},
submitHandler: function (form) {
$.ajax({
type: "POST",
url: "<?php echo BASE_URL;?>crm/thankyou/",
data: $(form).serialize()+"&company_count="+company_count,
success: function () {
alert("thanks");
}
});
return false; // required to block normal submit since you used ajax
}
});
</script>
Can anyone help me with how to make validation for these dynamically generated fields? Any help would be greatly appreciated. I am using form submission by using Ajax.
Code to add company fields dynamically
var company_room = 0;
var company_room1 = 0;
function add_another_company() {
company_room++;
company_room1++;
var objTo = document.getElementById('company_field')
var divtest = document.createElement("div");
divtest.setAttribute("class", "form-group removeclass2" + company_room);
//var rdiv = 'removeclass2' + company_room;
divtest.innerHTML = '<div class="form-row"><div class="col-sm-5"> <div class="form-group pad-tp-5"><input type="text" class="form-control aj4" id="company_name" name="company_name" placeholder="Company Name"></div></div><div class="col-sm-2"> <div class="form-group"> <button class="btn btn-danger bdr-rds-100 btn-pad" type="button" onclick="remove_another_company(' + company_room + ');"> <i class="fa fa-minus"></i> </button> </div></div></div>';
objTo.appendChild(divtest);
var E_fields = $('.aj4');
var E_count = 1;
$.each(E_fields, function() {
jQuery(this).attr('id','company_name' + E_count);
jQuery(this).attr('name','company_name' + E_count);
E_count++;
});
}
function remove_another_company(rid2) {
company_room1--;
$('.removeclass2' + rid2).remove();
var E_fields = $('.aj4');
var E_count = 1;
$.each(E_fields, function() {
jQuery(this).attr('id','company_name' + E_count);
jQuery(this).attr('name','company_name' + E_count);
E_count++;
});
}
OK, so I didn't have your HTML so I had to mock some up. You will obviously have to tweak this a little to work with your ID's. I tried to keep it as close as possible to the ID's/classes you were already using.
I removed the pure javascript functions and the onclick events in favor of jquery since you were already using it. Hopefully this kind of simplifies things a bit and makes it more manageable.
NOTE: I added a hidden input field to keep track of company count. This way it will be included when you $(form).serialize in your ajax options (as you are adding it with a variable now). I included code to preserve the company_count variable also, so basically you will have 2 company counts. I did this just to show you an easier way to keep track of this without having to micro manage it. :)
Try out this code and let me know what your getting in console if it is not working. Thanks
MOCK HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="form-wrapper">
<p>Dynamic Form</p>
<button id="addField">Add Dynamic Field</button>
<form id="dynForm">
Static Field: <input id="company_name" name="company_name" minlength="3" type="text" value="Static Company Name" required>
<br>
<input type="hidden" id="companyCount" name="companyCount" value="1">
<div id="company_field">
</div>
</form>
</div>
JQUERY/JS
$(function() { // <---- Document Ready!
$("#addField").on("click", () => {
var count = parseInt($("#companyCount").val(), 10);
count += 1;
$("#companyCount").val(count.toString());
var thisId = "company_name" + count.toString();
var html = '<div class="form-row"><div class="col-sm-5"> <div class="form-group pad-tp-5"><input type="text" class="form-control aj4" id="'+thisId+'" name="'+thisId+'" minlength="3" placeholder="Company Name" required></div></div><div class="col-sm-2"> <div class="form-group"> <button class="btn btn-danger bdr-rds-100 btn-pad" type="button"> <i class="fa fa-minus"></i> </button> </div></div></div>';
var ele = $.parseHTML(html);
$("#company_field").append(ele);
});
$("#company_field").on("click", "button", () => $(this).closest(".form-row").remove());
$("#company_creation_form").validate({
submitHandler: function(form) {
var company_count = parseInt($("#companyCount").val(), 10);
$.ajax({
type: "POST",
url: "<?php echo BASE_URL;?>crm/thankyou/",
data: $(form).serialize() + "&company_count=" + company_count,
success: function() {
alert("thanks");
}
});
return false;
}
});
});
i am facing issue in autocomplete on dynamically created fields.
as in attached picture i created dynamic fields by clicking on plus sign, and on first row autocomplete is working but on the rest that are generated dynamically autocomplete is not working.
code is for autocomplete is
$(".account_code").dropdown({
onChange: function (val) {
var id=val;
var dataString = 'id='+ id +'&type=account_code';
alert(dataString);
$.ajax
({
type: "POST",
url: "include/ajax_data.php",
data: dataString,
dataType: 'json',
cache: false,
success: function(data)
{
console.log(data);
$("#account_description").val(data.value);
}
});
}
});
dynamic row insertion code is
function add_row()
{
$rowno=$("#bank_payment_voucher tr").length;
$rowno=$rowno+1;
$("#bank_payment_voucher tr:last").after('<tr id="row'+$rowno+'"><td><div class="field"><select class="ui search dropdown account_code" id="account_code'+$rowno+'" name="account_code[]"><option value="">Select Code</option><?php foreach (get_lookups($data_code) as $key => $value){ ?><option value="<?php echo $value['code']; ?>"><?php echo $value['code']." | ".$value['description']; ?></option><?php } ?></select></div></td><td><div class="field"><input type="text" name="account_description[]" id="account_description'+$rowno+'" placeholder="Account Description" autocomplete="" value="" required=""></div></td><td><div class="required field"><input type="text" name="remarks[]" id="remarks'+$rowno+'" placeholder="Remarks" autocomplete="off" value="" required=""></div></td><td><div class="required field"><input type="text" name="cheque_number[]" id="cheque_number'+$rowno+'" placeholder="Cheque Number" autocomplete="off" value="" required=""></div></td><td><div class="field"><div class="ui fluid action input"><input type="number" name="amount[]" id="amount'+$rowno+'" placeholder="Amount" autocomplete="off" value=""><div class="ui green icon button"><i class="pk flag"></i> PKR</div></div></div></td><td><div class="field"><div class="ui fluid action input"><i class="minus circle icon red" onclick=delete_row("row'+$rowno+'") style="font-size: 2.5em; cursor: pointer;"></i></div></div></td></tr>');
}
console is also not showing any error.
requirements are: on every dynamic row, there is a fixed drop down and on the basis of that values selected from drop down, rest of the form fields filled automatically
please help me out in this
When you run this:
$(".account_code").dropdown({
...
});
You're finding all the elements with class account_code in the DOM and assigning a behavior to them, an event, that will be triggered when the dropdown functionality is used.
That code probably runs first.
So, when you add MORE elements with that same class, they never got the assignment of that behavior.
So what you need to do, in the add_row function, is not only creating the element and appending it, but also attaching the event you want to run on dropdown.
You could use this method to reassign the behavior: https://api.jquery.com/on/#on-events-selector-data-handler
Or you could also encapsulate the first snippet (assigning behavior) in a function, so you can trigger it again every time a new dynamic element is added.
Hope this helps.
See if this helpful.
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
var availableAttributes = [
"account_address",
"account_address_city",
"account_address_country",
"account_address_state",
"account_address_street1",
"account_address_street2",
"account_address_zip",
"account_email",
"account_login",
"account_name",
"account_number",
"account_telephone"
];
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div><input type="text" name="mytext[]"/>Remove</div>');
$(wrapper).find('input[type=text]:last').autocomplete({
source: availableAttributes
});
//add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
$("input[name^='mytext']").autocomplete({
source: availableAttributes
});
});
// autocomplete enablement
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div><input type="text" name="mytext[]"></div>
</div>
i just achieved it by following code
$(document).ready(function(){
$(document).on('keydown', '.account_code', function() {
var id = this.id;
var splitid = id.split('_');
var index = splitid[1];
// Initialize jQuery UI autocomplete
$( '#'+id ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "include/ajax_data.php",
type: 'POST',
dataType: "json",
cache: false,
data: {search: request.term,request:1},
success: function( data ) {
//console.log(data);
response( data );
}
});
},
select: function (event, ui) {
$(this).val(ui.item.code); // display the selected text
var bank_code_id = ui.item.id; // selected value
//console.log(bank_code_id);
// AJAX
$.ajax({
url: 'include/ajax_data.php',
type: 'post',
cache: false,
data: {bank_code_id:bank_code_id,request:2},
dataType: 'json',
success:function(response){
var len = response.length;
if(len > 0){
var id = response[0]['id'];
var description = response[0]['description'];
// Set value to textboxes
document.getElementById('lookupcodeid_'+index).value = id;
document.getElementById('accountdescription_'+index).value = description;
}
}
});
return false;
}
});
});
});
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>
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!