How to get element triggering the easyautocomplete - javascript

I'm using easyautocomplete plugin for my project and I can't get the element which triggered that.
Here is the element:
<input class="form-control product-name" type="text" value="" name="item[0][product_name]" id="item_0_product_name" autocomplete="off">
Here is the jquery code:
$(".product-name").easyAutocomplete({
url: function(phrase) {
return base+getCurrentUrl()+"?phrase=" + phrase;
},
getValue: "product_name",
list: {
onChooseEvent: function() {
console.log($(this).prop("name"));
console.log($(this).attr("name"));
}
},
});
The idea is, I would like to get the element which trigger that plugin and get one of its attribute, for example, the "name". But it always return "undefined" every time I choose an item from the list. I tried to log $(this), but only return "Object", not the input element.
How can I do this? Are there any other way to do this? Any help would be appreciated.

got it :)
with the code below i'm able to get the name of triggered input (work fine in case of multiple instance)
check the use of 'elt'.
$(".form-easyautocomplete").each(function(index,elt){
$(elt).easyAutocomplete({
list: {
onChooseEvent: function () {
console.log(elt.getAttribute('name'),$(elt).getSelectedItemData());
}
}
})
})

Related

Ajax / Jquery Add clicked link to text input area

Im new to jquery and even newer to ajax so please bear with me here.
I have the following script which fetches data (branch names) asynchronously via database:
$(document).ready(function () {
$("#pickup").on('keyup',function () {
var key = $(this).val();
$.ajax({
url:'modal/fetch_branch.php',
type:'GET',
data:'keyword='+key,
beforeSend:function () {
$("#results").slideUp('fast');
},
success:function (data) {
$("#results").html(data);
$("#results").slideDown('fast');
}
});
});
});
<input type="text" class="form-control empty" name="keyword" id="pickup" placeholder=""/>
When the user types, S as an example all branches containg S will be returned as can be seen in the image below:
WHAT I WOULD LIKE TO DO
I need to find a way to modify my script, to
allow user to click the link, for desired result (branch)
When link (branch) is clicked it needs to get appended to the form input field as the value of pickup
Any help or advise on how the above can be achieved, much appreciated.
P.S returned data (names) are <a> elements , thus they are links.
As far as I understand data in success:function (data) contains some <a> elements, so you need to add a handler to process click on these elements:
// use `on` as elements are added dynamically
$( "#results" ).on("click", "a", function() {
// take `text` of a clicked element and set it as `#pickup` value
$( "#pickup" ).val( $( this ).text() );
// return false to prevent default action
return false;
});
Add onclick on the link. Try this
<a onclick="func(this);" data-value="Strand">Strand</a>
function func(idn){
var value = $(idn).attr("data-value");
$("#pickup).val(value); //assuming that the pickup field has a "pickup" id
}

jquery function to handle a series of href in div rows

Imagine a table (actually constructed of divs) with rows and in the final cell in each row, I have an input text and a link that look like this:
<input type="text" name="message" id="message_#Model.IncidentId" value="">
Send a Comment
After each row (the parent div), I have a chunk of code like the following to ajaxify the link and text input:
$('#send_#Model.IncidentId').click(function () {
var msg = $('#message_#Model.IncidentId').val();
if (msg != '') { $(this).attr('href', this.href + '?msg=' + msg) }
$.post(this.href, function (json) {
if (json.jsonResult === null) {
$("#msg_#Model.IncidentId").html("Sent...");
} else {
window.location.href = json.jsonResult;
}
});
return false;
});
It works. However, there are at least 10 of these on each page. What I'm trying to do is consolidate the jquery into one function to handle all the links. Can I use jquery "this" or pass the IncidentId to the jquery function or something? It seems like "this" would not work because the input text is outside of the link? How can I do this to have one function for the entire page?
Keep in mind it's not imperative that I splash everything with the IncidentId. So, if I need to make one or more of the ids or names generic, that would be ok. It just needs to not get confused about what pair it's handling. I've seen some comments that a form might help, but 10+ forms on a page is ok? Plus, as it stands, there will never be any other input fields than what is shown above.
I appreciate your help. Thanks.
Update: So, I basically used Søren's recommended html5 data-* (data-id) attribute in my link, gave it a class name, and then moved my url down to the function as well...and then simply replaced all my #Model.IncidentIds. The one catch is that I had to use the following to register my click event:
$(document).on('click', ".ajax-link", function () {
I guess because I'm using handlebars to dynamically generate the page? I hadn't tested the original function since I moved it to my infinite scroll layout mentioned in the comments. Thanks all for replying.
Try this:
<input type="text" name="message" data-input-id="1" value="">
<a class="ajax-link" href="#" data-link-id="1">Send a Comment</a>
$('.ajax-link').click(function () {
var id = $(this).attr('data-link-id');
var msg = $('[data-link-id='+id+']').val();
if (msg != '') { $(this).attr('href', this.href + '?msg=' + msg) }
$.post(this.href, function (json) {
if (json.jsonResult === null) {
$("[data-link-id='+id+']").html("Sent...");
} else {
console.debug(json.jsonResult);
}
});
return false;
});
Make sure the link and field have the same id
First, make sure you have some useful class name's in place. E.g.,
<input type="text" class="incident-message" name="message" id="message_#Model.IncidentId" value="">
Send a Comment
That should allow you to create a nice, row-generic script like this:
$('.incident-link').click(function(e) {
e.preventDefault();
var $this = $(this),
$row = $this.closest('div'),
$msg = $row.find('.incident-message');
var msg = $msg.val();
if (msg != '') {
$this.attr('href', $this.attr('href') + '?msg=' + msg);
}
$.post($this.attr('href'), function (json) {
if (json.jsonResult === null) {
// I didn't see any markup for your #msg element, but assuming
// that you give it a useful classname, you can do something
// similar to this:
$row.find('.some-msg-className').html('Sent...');
} else {
window.location.href = json.jsonResult;
}
});
});
As far as grouping the events to a single handler, just use a class instead of id's.
$('.thisKind').click(function () {
or if the content is dynamic, use a single event for the parent with a selector in the on() method
$('#parentId').on("click", ".thisKind", function() {
As far as the this usage, you should familiarize yourself with jquery's DOM traversal using closest() to go up the tree and find() to go down

How do I detect when a div has lost focus?

Given the following markup, I want to detect when an editor has lost focus:
<div class="editor">
<input type="text"/>
<input type="text"/>
</div>
<div class="editor">
<input type="text"/>
<input type="text"/>
</div>
<button>GO</button>
EDIT: As the user tabs through the input elements and as each editor div loses focus (meaning they tabbed outside the div) add the loading class to the div that lost focus.
This bit of jquery is what I expected to work, but it does nothing:
$(".editor")
.blur(function(){
$(this).addClass("loading");
});
This seems to work, until you add the console log and realize it is triggering on every focusout of the inputs.
$('div.editor input').focus( function() {
$(this).parent()
.addClass("focused")
.focusout(function() {
console.log('focusout');
$(this).removeClass("focused")
.addClass("loading");
});
});
Here is a jsfiddle of my test case that I have been working on. I know I am missing something fundamental here. Can some one enlighten me?
EDIT: After some of the comments below, I have this almost working the way I want it. The problem now is detecting when focus changes to somewhere outside an editor div. Here is my current implementation:
function loadData() {
console.log('loading data for editor ' + $(this).attr('id'));
var $editor = $(this).removeClass('loaded')
.addClass('loading');
$.post('/echo/json/', {
delay: 2
})
.done(function () {
$editor.removeClass('loading')
.addClass('loaded');
});
}
$('div.editor input').on('focusin', function () {
console.log('focus changed');
$editor = $(this).closest('.editor');
console.log('current editor is ' + $editor.attr('id'));
if (!$editor.hasClass('focused')) {
console.log('switched editors');
$('.editor.focused')
.removeClass('focused')
.each(loadData);
$editor.addClass('focused');
}
})
A bit more complicated, and using classes for state. I have also added in the next bit of complexity which is to make an async call out when an editor loses focus. Here a my jsfiddle of my current work.
If you wish to treat entry and exit of the pairs of inputs as if they were combined into a single control, you need to see if the element gaining focus is in the same editor. You can do this be delaying the check by one cycle using a setTimeout of 0 (which waits until all current tasks have completed).
$('div.editor input').focusout(function () {
var $editor = $(this).closest('.editor');
// wait for the new element to be focused
setTimeout(function () {
// See if the new focused element is in the editor
if ($.contains($editor[0], document.activeElement)) {
$editor.addClass("focused").removeClass("loading");
}
else
{
$editor.removeClass("focused").addClass("loading");
}
}, 1);
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/8s8ayv52/18/
To complete the puzzle (get your initial green state) you will also need to also catch the focusin event and see if it is coming from the same editor or not (save the previous focused element in a global etc).
Side note: I recently had to write a jQuery plugin that did all this for groups of elements. It generates custom groupfocus and groupblur events to make the rest of the code easier to work with.
Update 1: http://jsfiddle.net/TrueBlueAussie/0y2dvxpf/4/
Based on your new example, you can catch the focusin repeatedly without damage, so tracking the previous focus is not necessary after all. Using my previous setTimeout example resolves the problem you have with clicking outside the divs.
$('div.editor input').focusin(function(){
var $editor = $(this).closest('.editor');
$editor.addClass("focused").removeClass("loading");
}).focusout(function () {
var $editor = $(this).closest('.editor');
// wait for the new element to be focused
setTimeout(function () {
// See if the new focused element is in the editor
if (!$.contains($editor[0], document.activeElement)) {
$editor.removeClass("focused").each(loadData);
}
}, 0);
});
Here's what worked for me:
$(".editor").on("focusout", function() {
var $this = $(this);
setTimeout(function() {
$this.toggleClass("loading", !($this.find(":focus").length));
}, 0);
});
Example:
http://jsfiddle.net/Meligy/Lxm6720k/
I think you can do this. this is an exemple I did. Check it out:
http://jsfiddle.net/igoralves1/j9soL21x/
$( "#divTest" ).focusout(function() {
alert("focusout");
});

jquery javascript - clear checkboxes on changing autocomplete field

I have the below script:
$("#product1").autocomplete({
source: "get_sku_family",
messages: {
noResults: '',
results: function () {}
},
select: function (event, ui) {
var selectedObj = ui.item;
$.post('get_as_09',
{
data: selectedObj.value
},
function (result) {
if (result[0] > 0) {
$('#h09_1').attr('checked', 'checked');
} else {
$('#h09_1').removeAttr('checked');
}
}
});
}
});
This has an autocomplete field that when text is entered provides options from a database. this works. then on clicking an option from the autocomplete, it queries the database with a function(get_as_09) and checks the checkbox based on the result.
Again this works 100%.
What I do want to change though, is that when I enter a new value on the autocomplete, it must clear the checkboxes before applying the new database lookup logic to check the boxes.
I just don't know where to add the $('#h09_1').removeAttr('checked');
Thanks and Regards...
any help appreciated
UPDATE Ripu
if(data:selectedObj.value.length ==0 ){$('#h09_1').removeAttr('checked');};
$.post('get_as_09', {data:selectedObj.value},function(result) {
if(result[0] > 0) {
$('#h09_1').attr('checked','checked');
} else {
$('#h09_1').removeAttr('checked');
}
});
before this line
$.post('get_as_09', {data:selectedObj.value},function(result) {
check if the value of data:selectedObj.value is empty. If it is empty, then you don't need to make a post request, just simply uncheck the checkbox
try to make it on texbox on change event means when you enter the new value in auto complete make it there to clear any thing you want check
Why dont you clear your checkboxes on focus of the auto-complete field.
Here is the documentation about this event http://api.jqueryui.com/autocomplete/#event-focus
as you said just a $('#h09_1').removeAttr('checked'); should suffice.
focus: function( event, ui ) {
$('#h09_1').removeAttr('checked');
}
what if you put before
$.post('get_as_09', {data:selectedObj.value},function(result) {
so everytime before you put smth inside your $('#h09_1') you clean it?
What if you attach an event listener on the element based on the keypress event? Something like this:
$(selectedObj).one('keypress', function (e) {
var checkbox = $('#h09_1');
if (selectObj.val().length > 0) {
checkbox.attr('checked', false);
}
});
This way you know somebody is typing in the field before you clear it. You could bind the event listener after each database lookup. Just an idea.

jQuery .val() not setting the value of <select>

I would like to know why jQuery's .val() function is not setting the value of the <select> control for me after I called replaceWith, but it is working otherwise.
Please see here for a (not) working example.
<select><option>ABC</option><option>DEF</option></select>
<input type="button" onclick="ControlOff()" value="Turn Off Control" />
<input type="button" onclick="ControlOn()" value="Turn On Control" />
<input type="button" onclick="Test()" value="Value Setting Test" />
function ControlOff() {
$('select').each(function () {
$(this).replaceWith('<span class="select-type">' + $(this).val() + '</span>');
});
}
function ControlOn() {
$('.select-type').each(function () {
var selected = $(this).text();
$(this).replaceWith('<select><option>ABC</option><option>DEF</option></select>');
$(this).val(selected);
});
}
function Test() {
$('select').val('DEF');
}
The problem is, that $(this) in $(this).val(selected) refers to the removed <span> element, not your new element. You need to replace it with:
$('select').val(selected);
to grab the previously inserted new element.
Also, your code is unecessarily complex, this does the same thing, but simpler:
function ControlOn() {
$selectText = $('.select-type');
var selected = $selectText.text();
$selectText.replaceWith('<select><option>ABC</option><option>DEF</option></select>');
$('select').val(selected); // Use an id instead to match: #my-select-id
}
Make sure to give the <select> element an ID, otherwise it's going to mess up once you introduce a new <select> element somewhere else on the page.
See here for a working example.
The problem is that in ControlOn you have an each which is looping over .select-type elements which are span's and spans cannot be set with the val method:
You can fix this by changing the method to this:
function ControlOn() {
$('.select-type').each(function () {
var selected = $(this).text();
var $select = $('<select><option>ABC</option><option>DEF</option></select>');
$(this).replaceWith($select)
$select.val(selected);
});
}
Live example: http://jsfiddle.net/qSYYc/4/
set value of options will solve your problem. jsfiddle
<select><option value='ABC'>ABC</option><option value="DEF">DEF</option></select>
function ControlOn() {
$('.select-type').each(function () {
var selected = $(this).text();
$(this).replaceWith($('<select><option>ABC</option><option>DEF</option></select>').val(selected));
});
}
Rewrite your code like above, it would work!
The element referenced by this won't change to the select element you just created, it will always be the span element inside the scope of that function. Therefore you should set the value to the newly created select instead of the invariant $(this)!
I'd suggest you to use "disabled" attribute to turn select on and off, it, won't mess up the .val() functionality
function ControlOff() {
$("select").attr("disabled", "disabled");
}
function ControlOn() {
$("select").removeAttr("disabled");
}

Categories