I want to implement this autocomplete to my page: http://www.bewebdeveloper.com/tutorial-about-autocomplete-using-php-mysql-and-jquery and it works but in my case I use clone() function to copy all <li> elements like here: http://jsfiddle.net/x42c3anw
When I have several inputs autocomplete works only for first input, how I can edit this function? :
function autocomplet() {
var min_length = 0; // min caracters to display the autocomplete
var keyword = $('#country_id').val();
if (keyword.length >= min_length) {
$.ajax({
url: 'ajax_refresh.php',
type: 'POST',
data: {keyword:keyword},
success:function(data){
$('#country_list_id').show();
$('#country_list_id').html(data);
}
});
} else {
$('#country_list_id').hide();
}
}
// set_item : this function will be executed when we select an item
function set_item(item) {
// change input value
$('#country_id').val(item);
// hide proposition list
$('#country_list_id').hide();
}
I undurstand this is because ID is not uniqe, is there possibility to add some increment to id or use class? If yes how I can do that?
Related
Im trying to add and remove class followed by click events to perform ajax calls. later on success retrieve back the old class. Like Im changing a state of input field to enable, change text of edit button to save and adding class at the same time. when i click same button it has to send modified value in input field to api and restore back to original save button. This is happening for first time when I click edit button. After saving if I click the edit button its changing the state to save and edit back again.help needed.
$.each(data, function(key, value) {
if (parseInt(cat_id[i].innerHTML) == value.category.id) {
base_rate[i].value = value.base_rate;
ast[i].innerHTML = value.service_type.name;
airportEditId[i].setAttribute("id",value.id);
newEvent = value.id;
airportEditId[i].classList.add("fireevent"+value.id);
j = true;
base_rate[i].setAttribute("disabled",true);
$('.fireevent'+value.id).on('click',function(){
$(this).attr("id",value.id);
$(this).parents("tr").find("input").prop('disabled',false);
$(this).text("save");
$(this).removeClass().addClass("smokeevent"+value.id).addClass("btn btn-primary");
console.log(this);
$('.smokeevent'+value.id).on('click',function(){
var airport = {
"updated_by":{{user.id}},
"city":parseInt($('#city_list option:selected').val()),
"service_type":parseInt($('#select_service1 option:selected').val()),
"base_rate":parseInt($(this).parents("tr").find("input").val()),
"vehicle_varient":[1,2]
};
console.log(airport);
$.ajax({
url: '/rapido/api/update_airportratecard/'+value.id+'/',
method: 'PUT',
headers:{'X-CSRFToken':'{{ csrf_token }}'},
contentType : 'application/json',
context:this,
data: JSON.stringify(airport),
success:function(res){
console.log(this);
$(this).text("Edit");
$(this).parents("tr").find("input").prop('disabled',true);
$(this).removeClass().addClass("btn btn-success");
}
});
});
});
Try this, In a loop, there are multiple events attached for the same click.
let go off the earlier event and attach again.
$('.airportdata').off('click').on('click', ...
You are binding the event to elements through class selector in a loop.
By the end of the loop you will have multiple event handlers assigned to all the elements belong to that class. As a result of this, one trigger of a click will invoke all those event handlers.
Instead use your own airportEditId[i] to bind the event instead of
$( airportEditId[i] ).on('click',function(){
Note :Judging by this line
$(".airportdata").removeClass().addClass("airport_editid").addClass("btn btn-success");
airport_editid and airportdata are classes of same element. Hence you can replace both by $( airportEditId[i] ).on('click',function(){
Edit
Another approach could be to pull these two click event handlers outside the loop and bind them separately
$.each(data, function(key, value) {
if (parseInt(cat_id[i].innerHTML) == value.category.id) {
base_rate[i].value = value.base_rate;
ast[i].innerHTML = value.service_type.name;
airportEditId[i].setAttribute("id", value.id);
newEvent = value.id;
j = true;
base_rate[i].setAttribute("disabled", true);
}
});
$(".airport_editid").on('click', function() { //notice that this line is outside
$(this).parents("tr").find("input").prop('disabled', false);
$(this).text("save");
$(this).removeClass().addClass("airportdata").addClass("btn btn-primary");
$(this).on('click', function() { //notice that this line is using `this` instead of selector
var airport = {
"updated_by": {
{
user.id
}
},
"city": parseInt($('#city_list option:selected').val()),
"service_type": parseInt($('#select_service1 option:selected').val()),
"base_rate": parseInt($(this).parents("tr").find("input").val()),
"vehicle_varient": [1, 2]
};
$.ajax({
url: api,
method: 'PUT',
headers: {
'X-CSRFToken': '{{ csrf_token }}'
},
contentType: 'application/json',
data: JSON.stringify(airport),
success: function(res) { $(".airportdata").parents("tr").find("input").prop('disabled', true);
$(".airportdata").text("Edit"); $(".airportdata").removeClass().addClass("airport_editid").addClass("btn btn-success");
}
});
});
});
hi guys i have try to make a select data function with jquery with onclick event that have triggering the date from datepicker.
i have try to make a code but seems not work at all.
this is the textboxt id's that contain the datepicker call function. $(#date)
i have try to make a code for selecting my data.
this is the code.
$(document).on('click','#date',function(e) {
var data = $("#form_input10").serialize();
$('#table_s tbody').empty();
$.ajax({
data: data,
type: "Post",
url: "../php/termocouple/get_date.php",
success: function(data){
var list = JSON.parse(data);
for(var i = 0; i < list.length; i++){
$('#date1').val((list[i]['tanggal2']));
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.3/jquery.min.js"></script>
the condition when the datepicker running is like this. when the textbox clicked then the datepicker will be showing. nah when i use my code, the condition like this the 1st click is for show the datepicker that ( from this condition the textbox doesn't have any value of the date) the the datepicker showing and i select the date. i need do one click again on the textbox for showing my data.
please someone help me to solve this
please
Instead of trying to use a click event on the datepicker, you'd want to use one of the datepicker's available options. One is beforeShow, and allows you to have a function run before the datepicker opens up:
$( "#date" ).datepicker({
beforeShow: doThatThing
});
function doThatThing(){
var data = $("#form_input10").serialize();
$('#table_s tbody').empty();
$.ajax({
data: data,
type: "Post",
url: "../php/termocouple/get_date.php",
success: function(data){
var list = JSON.parse(data);
for(var i = 0; i < list.length; i++){
$('#date1').val((list[i]['tanggal2']));
}
}
});
}
I'm having an issue with scope of variables in this function. Basically, when a user focuses on a textbox which will have a jQuery dropdown, I want to save the old value in the textbox, if present in order to restore it if required. I have also tried to declare previous outside the function and as window.previous but without success. The problem is that when I use the previous variable from within the .dropdown function I always get it back as undefined
// Delete option allows a user to delete the value directly from the textbox associated with the dropdown.
// Otherwise he will be warned and always forced to make a choice.
// With value will add an extra value to a textbox that has _val apended to the current id
// Create new, if set will open a new confirmation to add the item to the dropdown list
function acomplete(element, source, deleteoption, withvalue, createnew, createtable, createcolumn, retid) {
var previous;
// Add arrow as this is a dropdown
$(element).addClass("dropdown");
$(element).autocomplete({
source: source,
minLength: 0,
global: false,
select: function (event, ui) {
if (withvalue == true) {
$("#" + $(this).attr("id") + "_val").val(ui.item.thevalue);
//$("#" + $(this).attr("id") + "_val").trigger("change");
}
// Update hidden on select option
$("#" + $(this).attr("id") + "_id").val(ui.item.id);
// For items that have change event bound trigger ot so we are updating data in table.
$("#" + $(this).attr("id") + "_id").trigger("change");
},
focus: function (event, ui) {
// Save old value for backup
previous = this.value;
},
change: function (event, ui) {
//alert($(this).val());
if (!ui.item && $(this).val().length > 0) { // Item not selected in the dropdown list
$.ajax({
url: "ajax/check_dropdown_item_exists.php",
global: false,
method: "POST",
data: {
table: createtable,
colnames: createcolumn,
colvals: encodeURI(String($(this).val().toUpperCase())),
},
success: function (data) {
if (data != "TRUE") {
// Ask confirm to add new item to table
$.confirm('ITEM DOES NOT EXIST! ADD TO LIST?', function (answer) {
if (answer) {
$.ajax({
url: "inc/insert_table_field.php",
global: false,
method:"POST",
data: {
table: createtable,
colnames: createcolumn,
colvals: String($(this).val().toUpperCase()),
retid: retid,
},
success: function (data) {
if ($.isNumeric(data)) {
$("#" + $(element).attr("id") + "_id").val(data);
// Set the newly created value in dropdown
//$(element).val(String($(element).val().toUpperCase()));
// And update DB
$("#" + $(element).attr("id") + "_id").trigger("change");
} else {
$.alert(data);
}
},
error: function () {
$.alert('ERROR CREATING THE NEW ITEM!');
}
})
} else {
alert(previous)
// NO so blank
$(this).val(previous).focus();
}
})
} else {
// Commit change with value that already exists
// fecth item id and trigger select event
$.ajax({
url: "ajax/get_dropdown_item_id.php",
global: false,
method: "POST",
data: {
table: createtable,
colnames: createcolumn,
colvals: String($(element).val().toUpperCase()),
retid: retid,
},
success: function (data) {
if ($.isNumeric(data)) {
$("#" + $(element).attr("id") + "_id").val(data);
$("#" + $(element).attr("id") + "_id").trigger("change");
}
}
})
}
}
})
} else {
$(this).val((ui.item ? ui.item.label : "")); // If empty put back the last one
if (!ui.item) {
if (deleteoption !== true) {
this.value = "";
$.alert('YOU CAN SELECT FROM DROPDOWN ONLY!');
$(element).val(element.oldvalue).focus();
} else {
$("#" + $(this).attr("id") + "_id").val("");
$("#" + $(this).attr("id") + "_id").trigger("change");
}
}
}
}
}).dblclick(function () {
$(this).autocomplete("search", "");
}).click(function () {
$(this).autocomplete("search", "");
})
}
The problem is that focus don't react on focusing the textbox/input, but instead the result from autocomplete.
That means that when you click in the textbox the function focus will not start only if you select a result.
The best solution for you to get previous would be:
$(your element).click(function() {
previous = $(this).val()
}
This is from the documentation of jQueryUi Autocomplete:
focus( event, ui )
Triggered when focus is moved to an item (not selecting). The default action is to replace the text field's value with the value of the focused item, though only if the event was triggered by a keyboard interaction.
Canceling this event prevents the value from being updated, but does not prevent the menu item from being focused.
focus documentation
I want to access the value of #schooSelect inside ajax so i can send some data to php onChange.
$.LoadBooks = function () {
$(document).on('change', '#SchoolSelect', (function (e) {
var SchoolVal = ($(this).val())
$.LoadBooks()
}))
var SchoolVal = ($('#SchoolSelect').val())
$.ajax({
type: "GET",
data: {
data: SchoolVal
},
url: "../php/booksads.php"
}).done(function (feedback) {
$('#booksads').html(feedback)
});
}
$.LoadBooks()
Your code is strangely structured. You are somehow "recursively" calling $.LoadBooks inside the event handler, which will cause a new event handler to be added to the element, which is certainly not what you want.
Just bind the event handler once, outside the function:
var loadBooks = function(schoolVal) {
$.ajax({
type: "GET",
data: {
data: schoolVal
},
url: "../php/booksads.php"
}).done(function (feedback) {
$('#booksads').html(feedback)
});
}
$(document).on('change', '#SchoolSelect', function(e) {
loadBooks($(this).val());
});
You can either pass the value of the select element to the function (as shown here) or call var schoolVal = $('#SchoolSelect').val() inside of it to get the value.
The convention is that only the name of constructor functions start with a capital letter. And if your function is related to jQuery in particular, you shouldn't add it to $.
I'm currently writing a JQuery plugin that loads colors from a JSON web service into a drop down list.
The drop down list background-color changes according to the selected value. For the most part it is working. on any regular change it works as expected, the problem I am having is on the initial page load I am using triggerHandler("change"); and it triggers but I seem to be getting an undefined error on the selected value from the drop down list on page load so it doesn't trigger the color change on the drop down list
My code is:
$.fn.bindColorsList = function (options) {
var defColor = options.defaultColor;
var svcUrl = options.svcurl;
//var f_target = options.filterTarget;
var $this = this;
$.ajax({
url: options.svcurl,
dataType: 'json',
/*data: { filter: src_filt },*/
success: function (fonts) { fillcolors(fonts, $this) },
error: function () { appendError(f_target, "colors failed to load from server") }
});
this.on("change", function (event) {
log($(event.target).attr("id") + " change detected");
//change ddl dropdown color to reflect selected item ;
var hcolor = $this.find('option:selected').attr("name");
$this.attr("style", "background-color:" + hcolor);
});
function fillcolors(colors, target) {
$(target).empty();
$.each(colors, function (i, color) {
$(target).append("<option name='"+color.HexValue+"' value='" + color.Name + "' style='background-color:"+color.HexValue+"'>"+color.Name+"</option>");
});
};
//in a seperate file
$(document).ready(function () {
$("#dd-font-color").bindColorsList({ svcurl: "/home/colors"});
$("#dd-back-color").bindColorsList({ svcurl: "/home/colors" });
});
You are doing an AJAX request to populate your dropdown which, by the way, is an asynchronous one. In this case you need to trigger the event in the success callback of the AJAX request.
var $this = this;
// Bind the onchange event
$this.on("change", function (event) {
..
});
// Populate using AJAX
$.ajax({
...
success: function (fonts) {
// Populate the values
fillcolors(fonts, $this);
// Trigger the event
$this.trigger("change");
},
...
});
That's it.