jQuery autocomplete to get unused value - javascript

In my ASP.Net MVC application I have a jQuery autocomplete on a text box. I have everything working to display currently used item names and what I want to do is force the user to enter a completely NEW item name. I.e. the autocomplete acts as a guide to what exists but the user must ultimately enter a completely used string value.
I want the UI to signal if a currently used item is selected (there will be anther check on the server side when submit is posted) so for the moment there is just a simple alert().
My script is as follows:
$(document).ready(function() {
$('#combobox').autocomplete('<%= Url.Action("ProjectIdList", "LookUp") %>', {
delay:10,
minChars:1,
matchCase: 0,
matchSubset: 1,
autoFill: true,
maxItemsToShow:10,
cacheLength: 10,
onItemSelect:selectItem,
onFindValue:selectItem
});
});
Please note the markup:
onItemSelect:selectItem, onFindValue:selectItem
I have further script as follows:
function findValue(li) {
if (li != null) return alert("This Project Id cannot be used");
}
function selectItem(li) {
findValue(li);
}
However, I cannot get these events to fire. What am I missing?
Alternatively, is there a better way to do this?

I have used
$("combobox").result(function(item){
if(!item)
{
//no match
}
});
with some success with the official plugin.

Full final code for this to help anyone who needs it was as follows:
$(document).ready(function() {
$('#combobox').autocomplete('<%= Url.Action("ProjectIdList", "LookUp") %>',
{
delay: 10,
minChars: 1,
matchCase: 0,
matchSubset: 1,
autoFill: true,
maxItemsToShow: 10,
cacheLength: 10
}
);
$('#combobox').result(function(item) {
if (item) {
//no match
alert("Not this one!");
}
});
});

Related

Other option to trigger javascript function

I have the following javascript function which works nicely on a single html file.
jQuery.noConflict();
jQuery(function() {
$('#focus-init').click(function() {
$('#map1').vectorMap('set', 'focus', 1, 0, 0);
});
});
The issue appears when I try to integrate the above function into my wordpress theme. It seems that any other page I browse the above function is always called which I don't expect it to happen.
Since the #focus-init only exist on one page how can I specify that the above function should only be called when the element ID is found ?
UPDATE
I am afraid this wordpress theme does not have a concept of page title, since any other page has the same title tag
jQuery(function() {
if ($('#focus-init').length !== 0) {
$('#focus-init').click(function() {
$('#map1').vectorMap('set', 'focus', 1, 0, 0);
});
}
});

how to call alloy ui on click function for all elements with same css class name

What I want is that I have few links like
sample Link 1 sample Link 2
and I want to call the static html when user clicks the link. For that I have written a code
AUI().ready(
'aui-aria',
'aui-dialog',
'aui-overlay-manager',
'dd-constrain',
function(A) {
A.all('.popup-link').on('click',
function() {
var dialog = new A.Dialog({
bodyContent: 'Loading...',
centered: true,
title: 'Sample Popup Content',
width: 400,
height:600
}
).render();
dialog.plug(
A.Plugin.IO,
{
autoLoad: false,
uri: '/html/sample.html'
}
);
dialog.io.start();
});
});
but this does not work, it simply does not call the function when I click the link, I also tried this, but same thing
AUI().ready(
'aui-aria',
'aui-dialog',
'aui-overlay-manager',
'dd-constrain',
function(A) {
A.all('.sample-popup').each(function() {
this.on('click', function(A){
.....
......
Any idea what is wrong here?
Finally I got why it was not working. I was using the same object "A" in the click function as well.
it should be like this: (have a look at the variable name event)
AUI().ready(
'aui-aria',
'aui-dialog',
'aui-overlay-manager',
'dd-constrain',
function(A) {
A.all('.sample-popup').each(function() {
this.on('click', function(event){
.....
......
I don't know much about AUI but if you want to achieve same task using jQuery you can achieve like this
i.e
<script>
$(document).ready(function() {
$('.popup-link').click(function(){
alert($(this).text());
});
});
</script>
Or
Using Javascript
i.e
Link
<script type="text/javascript">
function theFunction () {
// return true or false, depending on whether you want to allow the `href` property to follow through or not
}
</script>
HTH

Any way to prevent "select_node.jstree" from being called when node closed in the jstree?

When you open nodes, it's fine. The "select_node.jstree" is not called. However, when you select a node and then close its' parent, jstree fires "select_node.jstree" for that parent node for some strange reason. Is there any way around this or is that just a flaw with jstree? I'd appreciate the help! Here's my code:
$("#RequirementsTree")
.bind("select_node.jstree", function(event, data) {
ReqNode = data.rslt.obj;
$("#req_tree_modal").dialog({ height: 400, width: 600, modal: true, closeOnEscape: true, resizable: false, show: "blind" });
$("#RMSDoc_ParentNodeID").val(data.rslt.obj.attr("id").substring(4));
if(is_requirement_node(data))
{
dispEditRequirementView();
var ReqCheck = data.rslt.obj.attr("name");
#* This is a REQUIREMENT *#
if(ReqCheck == "requirement")
{
// Ajax call to Server with requirement id passed in
$.ajax({
type: "POST",
url: '#Url.Content("~/RMS/getRequirementStateByID")',
data: {
ReqID : data.rslt.obj.attr("id").substring(4)
},
success: function(new_data) {
if(new_data == 1){
$("#RMSDoc_ReqEnabled").attr("checked", "checked");
$("#RMSDoc_ReqEnabled").val("true");
}
else if(new_data == 0) {
$("#RMSDoc_ReqEnabled").removeAttr("checked");
$("#RMSDoc_ReqEnabled").val("false");
}
}
});
$("#RMSDoc_RBSRequirement_RequirementsId").val(data.rslt.obj.attr("id").substring(4));
$("#RMSDoc_RBSRequirement_RequirementsText").val($.trim(data.rslt.obj.text()));
$("#ExistingTreeSubmit").val("#Model.RMSDoc.RMSEditReqButton.ConfigurableLabelDesc");
}
else {
alert("Requirement node select error");
}
}
#* This is a TREE BRANCH *#
else
{
dispAddRequirementView();
$("#RMSDoc_TreeBranch_Text").val($.trim($('.jstree-clicked').text()));
$("#RMSDoc_TreeBranch_id").val(data.rslt.obj.attr("id").substring(4));
$("#RMSDoc_TreeBranch_Level").val(data.rslt.obj.attr("name").substring(7));
$("#RMSDoc_RBSRequirement_RequirementsText").val("");
$("#ExistingTreeSubmit").val("#Model.RMSDoc.RMSCreateReqButton.ConfigurableLabelDesc");
}
})
Update:
I found a way to get it to work within the plugin, add the following to the "ui" config section:
"ui": {
"select_limit": 1,
"selected_parent_close":false
},
I believe what was happening is that when a sub-node was selected, collapsing the parent node would cause the parent node to be selected, triggering the event.
---------- Original Answer ---------------------
I'm not sure on the answer working within the bounds of the plugin. But I did find a work-around.
I added a class to each of the anchor () tags inside the tree "an".
<li class='jstree-closed' id="phtml_3" rel="folder">
test node 2
</li>
Then I wired JQuery to look for anchors with this class, and handled my click that way.
instance.on("click", "a.an", function (e) {
alert("click");
});
I still need to add code to find the ID from the parent-container, not optimal... but I don't have to compete with the collapse anymore for my click.

Jquery autosuggest

I am new to jquery.
I am using the below code for showing autosuggest in text box.
$().ready(function() {
function formatItem(row) {
return row[0] + " (<strong>id: " + row[1] + "</strong>)";
}
function formatResult(row) {
return row[0].replace(/(<.+?>)/gi, '');
}
//$("#suggest1").autocomplete(cities);
$("#custName").autocomplete(arrNames, {
multiple: false,
minChars: 0,
width: 190,
matchContains: true,
autoFill: false,
mustMatch: true,
max: 20,
}
});
});
My problem is I want to call a javascript function along with the index of arrNames as parameter when user select one name from autosuggest. Please help me.
Here is how you do it (using jQuery ui autocomplete) :
$("#custName").autocomplete(
source: arrNames,
select: function (event, ui) {
//Do stuff here
}
}
From jqueryUI website :
Select
Triggered when an item is selected from the menu; ui.item refers to
the selected item. The default action of select is to replace the text
field's value with the value of the selected item. Canceling this
event prevents the value from being updated, but does not prevent the
menu from closing.
EDIT :
It seems you are using Autocomplete plugin from http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/
This plugin is deprecated... You should use jQuery ui autocomplete : http://jqueryui.com/demos/autocomplete/

jQuery UI autocomplete with item and id

I have the following script which works with a 1 dimensional array. Is it possible to get this to work with a 2 dimensional array? Then whichever item is selected, by clicking on a second button on the page, should display the id of whichever item is selected.
This is the script with the 1 dimensional array:
var $local_source = ["c++", "java", "php", "coldfusion", "javascript", "asp", "ruby"];
$("#txtAllowSearch").autocomplete({
source: $local_source
});
This is the script for the button to check the id, which is incomplete:
$('#button').click(function() {
// alert($("#txtAllowSearch").someone_get_id_of_selected_item);
});
You need to use the ui.item.label (the text) and ui.item.value (the id) properties
$('#selector').autocomplete({
source: url,
select: function (event, ui) {
$("#txtAllowSearch").val(ui.item.label); // display the selected text
$("#txtAllowSearchID").val(ui.item.value); // save selected id to hidden input
}
});
$('#button').click(function() {
alert($("#txtAllowSearchID").val()); // get the id from the hidden input
});
[Edit] You also asked how to create the multi-dimensional array...
You should be able create the array like so:
var $local_source = [[0,"c++"], [1,"java"], [2,"php"], [3,"coldfusion"],
[4,"javascript"], [5,"asp"], [6,"ruby"]];
Read more about how to work with multi-dimensional arrays here: http://www.javascriptkit.com/javatutors/literal-notation2.shtml
From the Overview tab of jQuery autocomplete plugin:
The local data can be a simple Array
of Strings, or it contains Objects for
each item in the array, with either a
label or value property or both. The
label property is displayed in the
suggestion menu. The value will be
inserted into the input element after
the user selected something from the
menu. If just one property is
specified, it will be used for both,
eg. if you provide only
value-properties, the value will also
be used as the label.
So your "two-dimensional" array could look like:
var $local_source = [{
value: 1,
label: "c++"
}, {
value: 2,
label: "java"
}, {
value: 3,
label: "php"
}, {
value: 4,
label: "coldfusion"
}, {
value: 5,
label: "javascript"
}, {
value: 6,
label: "asp"
}, {
value: 7,
label: "ruby"
}];
You can access the label and value properties inside focus and select event through the ui argument using ui.item.label and ui.item.value.
Edit
Seems like you have to "cancel" the focus and select events so that it does not place the id numbers inside the text boxes. While doing so you can copy the value in a hidden variable instead. Here is an example.
My code only worked when I added 'return false' to the select function. Without this, the input was set with the right value inside the select function and then it was set to the id value after the select function was over. The return false solved this problem.
$('#sistema_select').autocomplete({
minLength: 3,
source: <?php echo $lista_sistemas;?> ,
select: function (event, ui) {
$('#sistema_select').val(ui.item.label); // display the selected text
$('#sistema_select_id').val(ui.item.value); // save selected id to hidden input
return false;
},
change: function( event, ui ) {
$( "#sistema_select_id" ).val( ui.item? ui.item.value : 0 );
}
});
In addition, I added a function to the change event because, if the user writes something in the input or erases a part of the item label after one item was selected, I need to update the hidden field so that I don´t get the wrong (outdated) id. For example, if my source is:
var $local_source = [
{value: 1, label: "c++"},
{value: 2, label: "java"}]
and the user type ja and select the 'java' option with the autocomplete, I store the value 2 in the hidden field. If the user erase a letter from 'java', por exemple ending up with 'jva' in the input field, I can´t pass to my code the id 2, because the user changed the value. In this case I set the id to 0.
Just want to share what worked on my end, in case it would be able to help someone else too. Alternatively based on Paty Lustosa's answer above, please allow me to add another approach derived from this site where he used an ajax approach for the source method
http://salman-w.blogspot.ca/2013/12/jquery-ui-autocomplete-examples.html#example-3
The kicker is the resulting "string" or json format from your php script (listing.php below) that derives the result set to be shown in the autocomplete field should follow something like this:
{"list":[
{"value": 1, "label": "abc"},
{"value": 2, "label": "def"},
{"value": 3, "label": "ghi"}
]}
Then on the source portion of the autocomplete method:
source: function(request, response) {
$.getJSON("listing.php", {
term: request.term
}, function(data) {
var array = data.error ? [] : $.map(data.list, function(m) {
return {
label: m.label,
value: m.value
};
});
response(array);
});
},
select: function (event, ui) {
$("#autocomplete_field").val(ui.item.label); // display the selected text
$("#field_id").val(ui.item.value); // save selected id to hidden input
return false;
}
Hope this helps... all the best!
Assuming the objects in your source array have an id property...
var $local_source = [
{ id: 1, value: "c++" },
{ id: 2, value: "java" },
{ id: 3, value: "php" },
{ id: 4, value: "coldfusion" },
{ id: 5, value: "javascript" },
{ id: 6, value: "asp" },
{ id: 7, value: "ruby" }];
Getting hold of the current instance and inspecting its selectedItem property will allow you to retrieve the properties of the currently selceted item. In this case alerting the id of the selected item.
$('#button').click(function() {
alert($("#txtAllowSearch").autocomplete("instance").selectedItem.id;
});
<script type="text/javascript">
$(function () {
$("#MyTextBox").autocomplete({
source: "MyDataFactory.ashx",
minLength: 2,
select: function (event, ui) {
$('#MyIdTextBox').val(ui.item.id);
return ui.item.label;
}
});
});
The above responses helped but, did not work in my implementation.
The instead of using setting the value using jQuery, I am returning the value from the function to the select option.
The MyDataFactory.ashx page has a class with three properties Id, Label, Value.
Pass the List into the JavaScript serializer, and return the response.
I do not think that there is need to hack around the value and label properties, use hidden input fields or to suppress events. You may add your own custom property to each Autocomplete object and then read that property value later.
Here is an example.
$(#yourInputTextBox).autocomplete({
source: function(request, response) {
// Do something with request.term (what was keyed in by the user).
// It could be an AJAX call or some search from local data.
// To keep this part short, I will do some search from local data.
// Let's assume we get some results immediately, where
// results is an array containing objects with some id and name.
var results = yourSearchClass.search(request.term);
// Populate the array that will be passed to the response callback.
var autocompleteObjects = [];
for (var i = 0; i < results.length; i++) {
var object = {
// Used by jQuery Autocomplete to show
// autocomplete suggestions as well as
// the text in yourInputTextBox upon selection.
// Assign them to a value that you want the user to see.
value: results[i].name;
label: results[i].name;
// Put our own custom id here.
// If you want to, you can even put the result object.
id: results[i].id;
};
autocompleteObjects.push(object);
}
// Invoke the response callback.
response(autocompleteObjects);
},
select: function(event, ui) {
// Retrieve your id here and do something with it.
console.log(ui.item.id);
}
});
The documentation mentions you have to pass in an array of objects with label and value properties. However, you may certainly pass in objects with more than these two properties and read them later.
Here is the relevant part I am referring to.
Array: An array can be used for local data. There are two supported
formats: An array of strings: [ "Choice1", "Choice2" ] An array of
objects with label and value properties: [ { label: "Choice1", value:
"value1" }, ... ] The label property is displayed in the suggestion
menu. The value will be inserted into the input element when a user
selects an item. If just one property is specified, it will be used
for both, e.g., if you provide only value properties, the value will
also be used as the label.
At last i did it Thanks alot friends, and a special thanks to Mr https://stackoverflow.com/users/87015/salman-a because of his code i was able to solve it properly. finally my code is looking like this as i am using groovy grails i hope this will help somebody there.. Thanks alot
html code looks like this in my gsp page
<input id="populate-dropdown" name="nameofClient" type="text">
<input id="wilhaveid" name="idofclient" type="text">
script Function is like this in my gsp page
<script>
$( "#populate-dropdown").on('input', function() {
$.ajax({
url:'autoCOmp',
data: {inputField: $("#populate-dropdown").val()},
success: function(resp){
$('#populate-dropdown').autocomplete({
source:resp,
select: function (event, ui) {
$("#populate-dropdown").val(ui.item.label);
$("#wilhaveid").val(ui.item.value);
return false;
}
})
}
});
});
</script>
And my controller code is like this
def autoCOmp(){
println(params)
def c = Client.createCriteria()
def results = c.list {
like("nameOfClient", params.inputField+"%")
}
def itemList = []
results.each{
itemList << [value:it.id,label:it.nameOfClient]
}
println(itemList)
render itemList as JSON
}
One more thing i have not set id field hidden because at first i was checking that i am getting the exact id , you can keep it hidden just put type=hidden instead of text for second input item in html
Thanks !
I've tried above code displaying (value or ID) in text-box insted of Label text. After that I've tried event.preventDefault() it's working perfectly...
var e = [{"label":"PHP","value":"1"},{"label":"Java","value":"2"}]
$(".jquery-autocomplete").autocomplete({
source: e,select: function( event, ui ) {
event.preventDefault();
$('.jquery-autocomplete').val(ui.item.label);
console.log(ui.item.label);
console.log(ui.item.value);
}
});
This can be done without the use of hidden field. You have to take benefit of the JQuerys ability to make custom attributes on run time.
('#selector').autocomplete({
source: url,
select: function (event, ui) {
$("#txtAllowSearch").val(ui.item.label); // display the selected text
$("#txtAllowSearch").attr('item_id',ui.item.value); // save selected id to hidden input
}
});
$('#button').click(function() {
alert($("#txtAllowSearch").attr('item_id')); // get the id from the hidden input
});
Auto Complete Text box binding using Jquery
## HTML Code For Text Box and For Handling UserID use Hidden value ##
<div class="ui-widget">
#Html.TextBox("userName")
#Html.Hidden("userId")
</div>
Below Library's is Required
<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>
Jquery Script
$("#userName").autocomplete(
{
source: function (request,responce)
{
debugger
var Name = $("#userName").val();
$.ajax({
url: "/Dashboard/UserNames",
method: "POST",
contentType: "application/json",
data: JSON.stringify({
Name: Name
}),
dataType: 'json',
success: function (data) {
debugger
responce(data);
},
error: function (err) {
alert(err);
}
});
},
select: function (event, ui) {
$("#userName").val(ui.item.label); // display the selected text
$("#userId").val(ui.item.value); // save selected id to hidden input
return false;
}
})
Return data Should be below format
label = u.person_full_name,
value = u.user_id

Categories