I'm using jQuery auto-complete, bundled with jquery-ui. Any way, I need to customize this little bit to pop-up links instead of just texts.
I have a multi dimensional PHP array which contains some texts and corresponding id of that text in MYSQL database.
$js_array = json_encode($php_array);
echo "var javascript_array = ". $js_array . ";\n";
So, now I have a multidimensional js array. But I have no idea how to use those values to create links.
The text items in the array should be the text part of the links, and the IDs should be the URL of the links.
This is my existing code. How to customize this to achive my puurpose...
$("#search_query").autocomplete( {
source: javascript_array
});
$(function() {
var projects = [
{
value: "jquery",
label: "jQuery",
desc: "the write less, do more, JavaScript library",
icon: "jquery_32x32.png"
},
{
value: "jquery-ui",
label: "jQuery UI",
desc: "the official user interface library for jQuery",
icon: "jqueryui_32x32.png"
},
{
value: "sizzlejs",
label: "Sizzle JS",
desc: "a pure-JavaScript CSS selector engine",
icon: "sizzlejs_32x32.png"
}
];
$( "#project" ).autocomplete({
minLength: 0,
source: projects,
focus: function( event, ui ) {
$( "#project" ).val( ui.item.label );
return false;
},
select: function( event, ui ) {
$( "#project" ).val( ui.item.label );
$( "#project-id" ).val( ui.item.value );
$( "#project-description" ).html( ui.item.desc );
$( "#project-icon" ).attr( "src", "images/" + ui.item.icon );
return false;
}
})
.autocomplete( "instance" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<a>" + item.label + "<br>" + item.desc + "</a>" )
.appendTo( ul );
};
});
you can use any custom attributes value,labels are must remaining all are as per your requirement(here we are using desc and icon).
Use the _renderItem option:
Method that controls the creation of each option in the widget's menu.
The method must create a new <li> element, append it to the menu, and
return it.
_renderItem: function( ul, item ) {
return $( "<li data-value='"+item.value+"'><a href='#'>"+item.label+"</a></li>" )
.appendTo( ul );
}
1) Remove this:
.autocomplete( "instance" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<a>" + item.label + "<br>" + item.desc + "</a>" )
.appendTo( ul );
};
2) Add it up here instead. Make sure you have a href parameter or most browsers won't knowledge it as a link.
$( "#project" ).autocomplete({
minLength: 0,
source: projects,
focus: function( event, ui ) {
$( "#project" ).val( ui.item.label );
return false;
},
select: function( event, ui ) {
$( "#project" ).val( ui.item.label );
$( "#project-id" ).val( ui.item.value );
$( "#project-description" ).html( ui.item.desc );
$( "#project-icon" ).attr( "src", "images/" + ui.item.icon );
return false;
},
_renderItem: function( ul, item ) {
return $( "<li data-value='"+item.value+"'><a href='#'>"+item.label+"</a></li>" )
.appendTo( ul );
}
});
Related
I am using Autocomplete jquery UI and autocomplete is working fine.
But Now i want to customize listing view(like: when i press j in textbox related data from j keyword will show customized div container).
Code what i have done :
$(document).ready(function() {
var projects = [{
value: "jquery",
label: "jQuery",
desc: "the write less, do more, JavaScript library"
}, {
value: "jquery-ui",
label: "jQuery UI",
desc: "the official user interface library for jQuery"
}, {
value: "sizzlejs",
label: "Sizzle JS",
desc: "a pure-JavaScript CSS selector engine"
}];
$("#search").autocomplete({
minLength: 0,
source: projects,
focus: function(event, ui) {
console.log(ui.item.label);
$("#project").val(ui.item.label);
return false;
},
select: function(event, ui) {
console.log(ui);
$("#search").val(ui.item.label);
$("#project-id").val(ui.item.value);
$("#project-description").html(ui.item.desc);
return false;
}
})
.autocomplete( "instance" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<a>" + item.label + "<br>" + item.desc + "</a>" )
.appendTo( ul );
};
});
And This function is not working at my end :
.autocomplete( "instance" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<a>" + item.label + "<br>" + item.desc + "</a>" )
.appendTo( ul );
};
I want to show a another div and in this i want to show listing of data and when mouse over on this right hand another div and open this data.
Like this :
<div class="left_div">
<ul>
<li>Android</li>
<li>Java</li>
</ul>
</div>
<div class="right_div">
<p>Android is a mobile operating system (OS) currently developed by Google</p>
</div>
EDIT: Doh! I should have placed my code here too! Here it is:
My code to call the combobox:
jQuery( "#select_performance" ).combobox();
jQuery( "#select_state" ).combobox();
jQuery( "#select_postcode" ).combobox();
jQuery( "#select_install" ).combobox();
jQuery( "#select_customer" ).combobox();
jQuery( "#select_address" ).combobox();
My code (as is from JQuery ui) to define the fields:
/*** Set up multiselect drop down lists ***/
(function( $ ) {
$.widget( "custom.combobox", {
_create: function() {
this.wrapper = $( "<span>" )
.addClass( "custom-combobox" )
.insertAfter( this.element );
this.element.hide();
this._createAutocomplete();
this._createShowAllButton();
},
_createAutocomplete: function() {
var selected = this.element.children( ":selected" ),
value = selected.val() ? selected.text() : "";
this.input = $( "<input>" )
.appendTo( this.wrapper )
.val( value )
.attr( "title", "" )
.addClass( "custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left" )
.autocomplete({
delay: 0,
minLength: 0,
source: $.proxy( this, "_source" )
})
.tooltip({
tooltipClass: "ui-state-highlight"
}).on('mouseup', function() {
$(this).select();
});
this._on( this.input, {
autocompleteselect: function( event, ui ) {
ui.item.option.selected = true;
this._trigger( "select", event, {
item: ui.item.option
});
},
autocompletechange: "_removeIfInvalid"
});
},
_createShowAllButton: function() {
var input = this.input,
wasOpen = false;
$( "<a>" )
.attr( "tabIndex", -1 )
.attr( "title", "Show All Items" )
.tooltip()
.appendTo( this.wrapper )
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass( "ui-corner-all" )
.addClass( "custom-combobox-toggle ui-corner-right" )
.mousedown(function() {
wasOpen = input.autocomplete( "widget" ).is( ":visible" );
})
.click(function() {
input.focus();
// Close if already visible
if ( wasOpen ) {
return;
}
// Pass empty string as value to search for, displaying all results
input.autocomplete( "search", "" );
});
},
_source: function( request, response ) {
var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
response( this.element.children( "option" ).map(function() {
var text = $( this ).text();
if ( this.value && ( !request.term || matcher.test(text) ) )
return {
label: text,
value: text,
option: this
};
}) );
},
_removeIfInvalid: function( event, ui ) {
// Selected an item, nothing to do
if ( ui.item ) {
return;
}
// Search for a match (case-insensitive)
var value = this.input.val(),
valueLowerCase = value.toLowerCase(),
valid = false;
this.element.children( "option" ).each(function() {
if ( $( this ).text().toLowerCase() === valueLowerCase ) {
this.selected = valid = true;
return false;
}
});
// Found a match, nothing to do
if ( valid ) {
return;
}
// Remove invalid value
this.input
.val( "" )
.attr( "title", value + " didn't match any item" )
.tooltip( "open" );
this.element.val( "" );
this._delay(function() {
this.input.tooltip( "close" ).attr( "title", "" );
}, 2500 );
this.input.data( "ui-autocomplete" ).term = "";
},
_destroy: function() {
this.wrapper.remove();
this.element.show();
}
});
})( jQuery );
I have 6 jQuery autocomplete comboboxes on a page. Each has selected a default item set up on load (first item of the list). When a user types in an invalid entry, (or blanks the input box) I get the tooltip saying "invalid entry". Is there a way to have the value be re-set to the initially selected / default entry (first list item)?
I cannot seem to find the answer to this (or perhaps I am asking the wrong way).
Thanks!
I don't know how you're setting your default value but here's a clue of how to go about it.
change: function (event, ui) {
if (ui.item === null) { // if value typed in the box doesn't exist then
$(this).val(""); // set value to empty string
$(this).val(list[0]).data('autocomplete')._trigger('select'); set new value here and then trigger reset. Assuming list is your array of items, select the first item
}
}
Working on a Rails tutorial as part of an online course. They suggest using this gem for implementing a live markdown editor. I couldn't get the gem to work so I started inspecting it. The repository is two years old, so I'm not surprised the gem isn't working right off. I followed the installation instructions and the appropriate files are loading, I just don't understand why it's not working.
It would be really convenient if it did work because installation is really simple. The way it's set up, all you have to do after installing the gem, running the rake task and adding uses_markdown_preview to the appropriate controller is add a class "markdown_preview" to the textarea you want to preview.
What should happen is, once you've added the "markdown_preview" class to your text area, a jQuery file executes the function markdownPreview on that class, which creates a kind of control bar with three buttons. An editing button, which is on at default so you can edit the textarea. A preview button, which once you click it should take the input text and render a preview of the text, applying the markdown on the text. And a help button, which once you click, will reveal instructions for how to use markdown.
The first thing I noticed was that the jQuery was using out of date selectors, i.e. .live(). When I changed those to .on(), the jQuery file loaded the buttons I described above, but still none of the events work. I'll post the file below:
(function( $ ){
$.fn.markdownPreview = function( type ) {
return this.each(function() {
var $this = $(this);
$this.wrap( '<div class="markdown_wrap editing"></div>' );
$this.before( '<div class="markdown_wrap_menu"><div class="markdown_wrap_menu_help">Help</div><div class="markdown_wrap_menu_edit">Write</div><div class="markdown_wrap_menu_preview">Preview</div></div>' );
var help_text = [
'<div class="content cheatsheet">',
'<h2>Markdown Cheat Sheet</h2>',
'<div class="cheatsheet-content">',
'<div class="mod">',
'<div class="col">',
'<h3>Format Text</h3>',
'<p>Headers</p>',
'<pre># This is an <h1> tag',
'## This is an <h2> tag',
'###### This is an <h6> tag</pre>',
' <p>Text styles</p>',
' <pre>*This text will be italic*',
'_This will also be italic_',
'**This text will be bold**',
'__This will also be bold__',
'',
'*You **can** combine them*',
'</pre>',
'</div>',
'<div class="col">',
'<h3>Lists</h3>',
'<p>Unordered</p>',
'<pre>* Item 1',
'* Item 2',
' * Item 2a',
' * Item 2b</pre>',
' <p>Ordered</p>',
' <pre>1. Item 1',
'2. Item 2',
'3. Item 3',
' * Item 3a',
' * Item 3b</pre>',
'</div>',
'<div class="col">',
'<h3>Miscellaneous</h3>',
'<p>Images</p>',
'<pre>![GitHub Logo](/images/logo.png)',
'Format: ![Alt Text](url)',
'</pre>',
'<p>Links</p>',
'<pre>http://github.com - automatic!',
'[GitHub](http://github.com)</pre>',
'<p>Blockquotes</p>',
'<pre>As Kanye West said:',
'> We\'re living the future so',
'> the present is our past.',
'</pre>',
'</div>',
'</div>',
'<div class="rule"></div>',
'</div>',
'</div>' ].join( "\n" );
$this.before( '<div class="markdown_wrap_help">' + help_text + '</div>' );
$this.wrap( '<div class="markdown_wrap_content"></div>' );
$this.after( '<div class="markdown_wrap_preview"></div>' );
$this.wrap( '<div class="markdown_wrap_editor"></div>' );
/*
if ( !type || type == 'width' ) {
$this.width( $this.width() );
}
if ( !type || type == 'height' ) {
$this.height( $this.height() );
}*/
});
};
$( '.markdown_wrap_menu_help' ).live( 'click', function(){
//console.log( 'Clicked Help' );
$( this ).closest( '.markdown_wrap' ).toggleClass( 'helping' );
$( this ).closest( '.markdown_wrap' ).find( '.markdown_wrap_help' ).slideToggle( 'fast' );
});
$( '.markdown_wrap_menu_edit' ).live( 'click', function(){
//console.log( 'Clicked Edit' );
$( this ).closest( '.markdown_wrap' ).removeClass( 'previewing' ).addClass( 'editing' );
$( this ).closest( '.markdown_wrap' ).find( '.markdown_wrap_preview' ).hide();
$( this ).closest( '.markdown_wrap' ).find( '.markdown_wrap_editor' ).show();
});
$( '.markdown_wrap_menu_preview' ).live( 'click', function(){
//console.log( 'Clicked Preview' );
$( this ).closest( '.markdown_wrap' ).removeClass( 'editing' ).addClass( 'previewing' );
var editor = $( this ).closest( '.markdown_wrap' ).find( '.markdown_wrap_editor' );
var preview = $( this ).closest( '.markdown_wrap' ).find( '.markdown_wrap_preview' );
preview.html( 'Loading...' );
editor.hide();
preview.show();
var editor_content = editor.find( 'textarea' ).val();
$.ajax({
type: 'POST',
url: '/markdown_preview/convert',
data: { 'format' : 'json', 'markdown_text' : editor_content },
success: function( data, textStatus, jqXHR ){
preview.html( data['html'] );
},
error: function(jqXHR, textStatus, errorThrown){
//console.log( "ERROR" );
//console.log( jqXHR );
//console.log( textStatus );
//console.log( errorThrown );
},
dataType: 'text json'
});
});
})( jQuery );
$( document ).ready( function(){
$( '.markdown_preview' ).markdownPreview();
});
Besides the .live() selectors, what else is wrong with this file? And why does it seem like the code works until it gets to these events, i.e.:
$( '.markdown_wrap_menu_help' ).live( 'click', function(){
//console.log( 'Clicked Help' );
$( this ).closest( '.markdown_wrap' ).toggleClass( 'helping' );
$( this ).closest( '.markdown_wrap' ).find( '.markdown_wrap_help' ).slideToggle( 'fast' );
});
I can add code above that first event, like an alert() function, and I've confirmed that will execute, but when I click on any of the buttons, nothing happens.
Figured it out. This:
$( '.markdown_wrap_menu_help' ).live( 'click', function(){
//console.log( 'Clicked Help' );
$( this ).closest( '.markdown_wrap' ).toggleClass( 'helping' );
$( this ).closest( '.markdown_wrap' ).find( '.markdown_wrap_help' ).slideToggle( 'fast' );
});
Should be:
$( document ).on('click', '.markdown_wrap_menu_help', function(){
$( this ).closest( '.markdown_wrap' ).toggleClass( 'helping' );
$( this ).closest( '.markdown_wrap' ).find( '.markdown_wrap_help' ).slideToggle( 'fast' );
});
I've been focusing mostly on Rails and my jQuery's lacking. If anyone could actually explain why the old code worked in the previous jQuery library and why this change works for the current version, that'd be helpful.
I have folders with tooltips such as '0 entries' or '5 entries' and so on. I need this tooltip number to update by 1 every time something is dropped into the folder. The title doesn't always start at zero, and I need $(this) drop div updated, as I have many. Here is the working fiddle http://jsfiddle.net/4ehSG/3
jQuery
$(document).tooltip();
var dropped =0;
$( ".draggable" ).draggable();
$( ".droppable" ).droppable({
drop: function( event, ui ) {
dropped++;
$( this )
.attr('title',dropped+' entries')
.addClass( "ui-state-highlight" )
.find( "p" )
.html( "Dropped!" );
$( ".draggable" ).fadeOut();
}
});
HTML
<div class="draggable ui-widget-content">
<p>Drag me to my target</p>
</div>
<div class="droppable ui-widget-header" title='2 entries'>
<p>Drop here</p>
</div>
Here is an example of what you can do: http://jsfiddle.net/4ehSG/9/
drop: function( event, ui ) {
var dropped = parseInt($(this).attr('title')) + 1;
$( this )
.attr('title',dropped+' entries')
.addClass( "ui-state-highlight" )
.find( "p" )
.html( "Dropped!" );
$( ".draggable" ).fadeOut();
}
You could increase a variable every time an element is dropped
try this
$(document).tooltip();
var num = 0;
$( "#draggable" ).draggable();
$( "#droppable" ).droppable({
drop: function( event, ui ) {
$( this )
.addClass( "ui-state-highlight" )
.find( "p" )
.html( "Dropped!" );
num++;
$( "#draggable" ).fadeOut();
$( "#droppable" ).attr("title", num + " entries");
}
});
your updated example: http://jsfiddle.net/4ehSG/4/
If you have multiple instances of droppable and draggable, you may want to give each droppable an array associated with it. That way you don't need to rely on a count object and you could drop the same draggable on multiple droppable objects.
DEMO
$(document).tooltip();
$( ".draggable" ).draggable();
$( ".droppable" ).droppable({
drop: function( event, ui ) {
if(!$(this).data('droplist')){ //check for array
$(this).data('droplist', []); //if doesn't exist, create array
}
var droplist = $(this).data('droplist'),
drag = $(ui.draggable)[0];
if(droplist.indexOf(drag) === -1) //check if element exists in array
droplist.push(drag);
$( this )
.addClass( 'ui-state-highlight' )
.find( 'p' )
.html( 'Dropped!' )
.end()
.attr('title', droplist.length + ' entries');
$(this).data('droplist', droplist); //set list
}
});
DEMO
$(document).tooltip();
var count = 0;
$("#draggable").draggable();
$("#droppable").droppable({
drop: function (event, ui) {
count++;
$(this)
.attr('title', count + ' entries')
.addClass("ui-state-highlight")
.find("p")
.html("Dropped!");
$("#draggable").fadeOut();
}
});
You can use:
document.getElementById('droppable').title = value;
The above line of code is without using jQuery.
If you want to use jQuery, use the following:
$("#droppable").attr( 'title', value );
I have standard select which is turned into a combobox using jQuery.
<select name="Searchby" id="Searchby">
<option value="all" >All Departments</option>
<option value="music" >Music</option>
<option value="dvd" >DVD</option>
<option value="bluray" >Bluray</option>
<option value="Artist" >Artist</option>
</select>
Then I have an input which has jQuery's autocomplete on it with categories. When a person types into the input, it returns options to choose from in different categories. If they click on a option I want it to change what is selected in the select above. Here is my code that I tried.
$("#Search").catcomplete({
delay: 1000,
source: "Drop_Down_Search.php",
select: function(event, ui) {
if (ui.item.category = 'Artist') {
$('#Searchby').val('Artist');
console.log(ui.item.category);
}
}
});
The console is logging that it is working and it posts correctly to the search results page but doesn't change before you move off the page. It just stays as 'all departments'. I need it to change so a person who is searching can see they will only search for 'Artist' or 'Blu-Rays' before they move to the search results page.
EDIT:
Ok so as it turns out without the jquery combobox set on the select it does change the value, but when you use jquery's combobox it doesn't change.
What should I be using to change the value once a select has been changed into a combobox?
Here is the combobox code:
(function( $ ) {
$.widget( "ui.combobox", {
_create: function() {
var input,
that = this,
wasOpen = false,
select = this.element.hide(),
selected = select.children( ":selected" ),
value = selected.val() ? selected.text() : "",
wrapper = this.wrapper = $( "<span>" )
.addClass( "ui-combobox" )
.insertAfter( select );
function removeIfInvalid( element ) {
var value = $( element ).val(),
matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( value ) + "$", "i" ),
valid = false;
select.children( "option" ).each(function() {
if ( $( this ).text().match( matcher ) ) {
this.selected = valid = true;
return false;
}
});
if ( !valid ) {
// remove invalid value, as it didn't match anything
$( element )
.val( "" )
.attr( "title", value + " didn't match any item" )
.tooltip( "open" );
select.val( "" );
setTimeout(function() {
input.tooltip( "close" ).attr( "title", "" );
}, 2500 );
input.data( "ui-autocomplete" ).term = "";
}
}
input = $( "<input>" )
.appendTo( wrapper )
.val( value )
.attr( "title", "" )
.addClass( "ui-state-default ui-combobox-input" )
.autocomplete({
delay: 0,
minLength: 0,
source: function( request, response ) {
var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
response( select.children( "option" ).map(function() {
var text = $( this ).text();
if ( this.value && ( !request.term || matcher.test(text) ) )
return {
label: text.replace(
new RegExp(
"(?![^&;]+;)(?!<[^<>]*)(" +
$.ui.autocomplete.escapeRegex(request.term) +
")(?![^<>]*>)(?![^&;]+;)", "gi"
), "<strong>$1</strong>" ),
value: text,
option: this
};
}) );
},
select: function( event, ui ) {
ui.item.option.selected = true;
that._trigger( "selected", event, {
item: ui.item.option
});
},
change: function( event, ui ) {
if ( !ui.item ) {
removeIfInvalid( this );
}
}
})
.addClass( "ui-widget ui-widget-content ui-corner-left" );
input.data( "ui-autocomplete" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<a>" + item.label + "</a>" )
.appendTo( ul );
};
$( "<a>" )
.attr( "tabIndex", -1 )
.attr( "title", "Select A Critera to Search In " )
.appendTo( wrapper )
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass( "ui-corner-all" )
.addClass( "ui-corner-right ui-combobox-toggle" )
.mousedown(function() {
wasOpen = input.autocomplete( "widget" ).is( ":visible" );
})
.click(function() {
input.focus();
// close if already visible
if ( wasOpen ) {
return;
}
// pass empty string as value to search for, displaying all results
input.autocomplete( "search", "" );
});
},
_destroy: function() {
this.wrapper.remove();
this.element.show();
}
});
})( jQuery );
$(function() {
$( "#Searchby" ).combobox();
$( "#toggle" ).click(function() {
$( "#Searchby" ).toggle();
}); });
mistake i found..
$( "#Search" ).catcomplete({
delay: 1000,
source: "Drop_Down_Search.php",
select: function( event, ui ) {
if (ui.item.category == 'Artist') {
-----^^-- missing `=` in if since your are comparing this
$('#Searchby').val('Artist');
console.log(ui.item.category);
}
}
});
//}); extra brakets..
I found what I was looking for in this answer
How to define selected value for jQuery UI combobox?
After some editing I came to this which worked.
$('.ui-autocomplete-input').val($("#Searchby").val("Artist").val());
The value you select is 'Artist' and Searchby is the select id