jQuery - the autocomplete properties not getting applied to dynamically created combobox? - javascript

Below is the code in which the autocomplete works fine with the first combobox. if i just copy paste the combobox it is working but when the second combobox is created dynamically on button click the autocomplete is not working ?
current code :
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Autocomplete - Combobox</title>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<style>
.custom-combobox {
position: relative;
display: inline-block;
}
.custom-combobox-toggle {
position: absolute;
top: 0;
bottom: 0;
margin-left: -1px;
padding: 0;
height:17px;
background:transparent;
border-radius:0px;
}
.custom-combobox-input {
margin: 0;
padding: 0px 0px;
width:150px;height:17px;
background:transparent;
border-radius:0px;
}
.ui-menu .ui-menu-item {
position: relative;
margin: 0;
padding: 0px 0em 0px 0em;
cursor: pointer;
min-height: 0;
background:transparent;
}
</style>
<script>
function sendvalues()
{
alert();
}
function combo()
{
alert();
$( ".combobox" ).combobox();
}
(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"
});
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 ) {
sendvalues();
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.autocomplete( "instance" ).term = "";
},
_destroy: function() {
this.wrapper.remove();
this.element.show();
}
});
})( jQuery );
$(function() {
$( ".combobox" ).combobox();
$( "#toggle" ).click(function() {
$( ".combobox" ).toggle();
});
});
</script>
</head>
<body>
<script>
function loada()
{
document.getElementById("two").innerHTML=document.getElementById("one").innerHTML;
}
</script>
<div id="one">
<select class="combobox" id="one" onchange="sendvalues()" onload="combo()">
<option value="">Select one...</option>
<option value="abc">abc</option>
<option value="kkk">kkk</option>
<option value="sd">asf</option>
<option value="abdfac">abasdfsac</option>
<option value="kgfjkgkk">kkyk</option>
<option value="sghkd">asgyjf</option>
<option value="abyuic">abftfjvhjc</option>
<option value="kkkgyjhk">kkgjk</option>
<option value="sml,hud">asnjmf</option>
</select>
</div>
<br><br><br><br>
<button onclick="loada()" >click</button>
<div id="two" onload="">
</div>
</body>
</html>

There are certain points which I observed in your code which are little bit not correct to do with html. Chances are there you would have written in hurry so please ignore the points
Div Id is 'one' and in side selector also having id as one make sure ids are unique.
your loada() function is just doing a copy paste job auto complete binding is missing .
So here I have changed your loada() function replace then it will work.
var counter = 0;
function loada() {
// document.getElementById("two").innerHTML = document.getElementById("one").innerHTML;
$("#one").clone().find('select').addClass('newControl' + counter).appendTo("#two");
$('.newControl' + counter).combobox();
counter++;
}

Related

Headhensive missing dropdown menu when cloning

I have a website which uses Headhesive, superfish and i18next. I have a header which has a navigation bar. On this navigation bar, the 2nd navItem has a drop-down menu.
The Headhensive clones the whole header but missing the drop-down menu.
This is the main menu
<nav id="main-menu" data-easing="easeInOutExpo" data-speed="1250">
<ul>
<li>
<a href="#home">
<div data-i18n="nav.home">Home</div>
</a>
</li>
<li>
<a href="#service">
<div data-i18n="nav.services.title">Title</div>
<ul>
<li>
<a href="#service">
<div data-i18n="nav.services.ourservices">Our Services</div>
</a>
</li>
<li>
<a href="#how">
<div data-i18n="nav.services.howwework">How We Work</div>
</a>
</li>
</ul>
</a>
</li>
</ul>
</nav>
As you can see that the ul is the drop-down menu.
And here is the code to use Headhensive:
initHeadhesive: function() {
if( headerEl.hasClass( 'sticky' ) ) {
var options = {
offset: 200,
offsetSide: 'top',
classes: {
clone: 'header-clone',
stick: 'header-stick',
unstick: 'header-unstick'
},
onInit: function () {
main_menu_clone = $( '#header.header-clone #main-menu' );
menu_trigger_clone = $( '#header.header-clone #menu-trigger' );
main_menu_clone.superfish({
popUpSelector : 'ul',
delay : 250,
speed : 350
});
if( menu_trigger_clone.length > 0 ) {
menu_trigger_clone.on( 'click', ( function() {
$( this ).toggleClass( 'open' );
main_menu_clone.toggleClass( 'display-menu' );
}));
}
$( main_menu_clone ).find( 'ul' ).on( 'click', function( e ) {
if ( $( e.target.tagName.toLowerCase() ).is( 'div' ) ) {
var element = $( main_menu_clone ),
divScrollToAnchor = $( e.target ).parent().attr('href'),
divScrollSpeed = element.attr('data-speed'),
divScrollOffset = SPHERE.header.topScrollOffset(),
divScrollEasing = element.attr('data-easing');
if( !divScrollSpeed ) { divScrollSpeed = 1250; }
if( !divScrollEasing ) { divScrollEasing = 'easeInOutExpo'; }
if( $( divScrollToAnchor ).length > 0 ) {
element.find( 'li' ).removeClass( 'current' );
element.find( 'a[href="' + divScrollToAnchor + '"]' ).parent( 'li' ).addClass( 'current' );
$( 'html,body' ).stop( true ).animate({
'scrollTop': $( divScrollToAnchor ).offset().top - Number( divScrollOffset )
}, Number( divScrollSpeed ), divScrollEasing );
}
if( windowWidth < 991 ) {
menu_trigger_clone.toggleClass( 'open', false );
main_menu_clone.toggleClass( 'display-menu', false );
}
return false;
}
});
},
};
// Initialise with options
var stickyHeader = new Headhesive( '#header', options );
}
},
I have seen my submenu which has "Our Services" and "How We Work" in the original header, but not in the cloned header.

Disable button after form reload

After I submit an invalid form page it redirects back to the same form page.
I want to be able to disable the "Find address" button and "House No" input field.
At the moment only "House No" input stays disabled and not the "Find address" button.
Please help.
var enableDisableFindAddress = function(postcodeLookupAvailabilityCountries) {
var $this = $( ".find-address-country"),
addressType = $this.data( "addresstype" ),
countryISO = $this.val(),
availableCountries = postcodeLookupAvailabilityCountries;
var foundAvailableISO = false,
HouseNameOrNoFieldId = "#" + addressType + "_house_no_or_name",
searchBtnID = "#" + addressType + "_search_btn";
for( i = 0; i < availableCountries.length; i++ ){
if( countryISO == availableCountries[i] ){
foundAvailableISO = true;
break;
}
}
if ( foundAvailableISO ) {
$( HouseNameOrNoFieldId ).prop( "disabled", false );
$( searchBtnID ).prop( "disabled", false );
} else {
$( HouseNameOrNoFieldId ).prop( "disabled", true );
$( searchBtnID ).prop( "disabled", true );
alert("I am suppose to disable this")
}
}
// THIS IS NOT WORKING
if ( $( ".find-address-country").val() !== "" ) {
enableDisableFindAddress( postcodeLookupAvailabilityCountries );
}
// THIS IS WORKING
$( ".find-address-country" ).change( function() {
enableDisableFindAddress( postcodeLookupAvailabilityCountries );
});

Drag and Drop to a specific area

I have tried to create a game where the user will have to place each card in a specific order. I can drag and drop the names into the dropable area but how will i be able to assign a specific card to a specific slot.
Here is my js code:
var correctCards = 0;
$( init );
function init() {
// Hide the success message
$('#successMessage').hide();
$('#successMessage').css( {
left: '580px',
top: '250px',
width: 0,
height: 0
} );
// Reset the game
correctCards = 0;
$('#cardPile').html( '' );
$('#cardSlots').html( '' );
// Create the pile of shuffled cards
var cards = ["Aiba", "Ninomiya", "Ohno", "Sakurai", "Matsumoto"];
cards.sort( function() { return Math.random() - .5 } );
for ( var i=0; i<cards.length; i++ ) {
$('<div>' + cards[i] + '</div>').data('img',i ).appendTo( '#cardPile' ).draggable( {
containment: '#content',
stack: '#cardPile div',
cursor: 'move',
revert: true
} );
}
// Create the card slots
var slots = [ ' ', ' ', ' ', ' ', ' '];
for ( var i=1; i<=slots.length; i++ ) {
$('<div>' + slots[i-1] + '</div>').data( 'number', i ).appendTo( '#cardSlots' ).droppable( {
accept: '#cardPile div',
hoverClass: 'hovered',
drop: handleCardDrop
} );
}
}
function handleCardDrop( event, ui ) {
var slotNumber = $(this).data( 'name' );
var cardNumber = ui.draggable.data( 'name' );
// If the card was dropped to the correct slot,
// change the card colour, position it directly
// on top of the slot, and prevent it being dragged
// again
if ( slotNumber == cardNumber ) {
ui.draggable.addClass( 'correct' );
ui.draggable.draggable( 'disable' );
$(this).droppable( 'disable' );
ui.draggable.position( { of: $(this), my: 'left top', at: 'left top' } );
ui.draggable.draggable( 'option', 'revert', false );
correctCards++;
}
// If all the cards have been placed correctly then display a message
// and reset the cards for another go
if ( correctCards == 10 ) {
$('#successMessage').show();
$('#successMessage').animate( {
left: '380px',
top: '200px',
width: '400px',
height: '100px',
opacity: 1
} );
}
}
If you give a unique id to each div where a card is (so for example cardSlot1, cardSlot2...), you could use document.getElementById('cardSlot1').value to get the name of the card back.
It would look similar to this:
for ( var i=0; i<cards.length; i++ ) {
$('<div id="cardSlot'+i+'">' + cards[i] + '</div>').data('img',i ).appendTo( '#cardPile' ).draggable( {
containment: '#content',
stack: '#cardPile div',
cursor: 'move',
revert: true
} );
}

How to force text to select in jQuery combobox

I have implemented jQuery Combobox using jQuery UI autocomplete.
But my aim is to achieve the text to select on force, I mean when we type the text should be force to select after full text is matched as shown below:
Below is the code I have implemented using jQuery Combobox. I needed this because I want to use in my project when user types it wont gives the result if the user types mercury and it shows didn't find value.
(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"
});
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.autocomplete("instance").term = "";
},
_destroy: function() {
this.wrapper.remove();
this.element.show();
}
});
})(jQuery);
$(function() {
$("#combobox").combobox();
$("#toggle").click(function() {
$("#combobox").toggle();
});
});
.custom-combobox {
position: relative;
display: inline-block;
}
.custom-combobox-toggle {
position: absolute;
top: 0;
bottom: 0;
margin-left: -1px;
padding: 0;
}
.custom-combobox-input {
margin: 0;
padding: 5px 10px;
<title>jQuery UI Autocomplete - Combobox</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<div class="ui-widget">
<label>Choose Planets</label>
<select id="combobox">
<option value="">Select one...</option>
<option value="Mercury">Mercury</option>
<option value="Venus">Venus</option>
<option value="Earth">Earth</option>
<option value="Mars">Mars</option>
<option value="Jupiter">Jupiter</option>
</select>
</div>
<button id="toggle">Search</button>
To achieve your expected result, check for the exact word instead match by below code
if ( this.value == request.term )
return {
label: text,
value: text,
option: this
};
Codepen URL with working solution
http://codepen.io/nagasai/pen/Lkjyyz

Why does my progress bar shows full progress value before it start loading

I made a progress bar using jQuery UI. here is the link to see it: DEMO
It works well, just there is a problem. At the code I have setTimeout( progress, 2000 ); which means it has to wait 2 seconds before it stars. But during this time it shows the background of .ui-progressbar-value which must be visible when the whole progress is completed. After 2 seconds it hides and to progress stars as normal.
Interestingly when I tried it on JSFiddle, it did not show this class and worked perfectly. So in browsers only have this problem. Here is the JSFiddel link
and this is my js code:
$(function() {
var progressbar = $( "#progressbar" ),
progressLabel = $( ".progress-label" );
progressbar.progressbar({
value: false,
change: function() {
progressLabel.text( progressbar.progressbar( "value" ) + "%" );
},
complete: function() {
progressLabel.text( "100%" );
$(".loader").delay(1000).fadeOut(750);
}
});
function progress() {
var val = progressbar.progressbar( "value" ) || 0;
progressbar.progressbar( "value", val + 1 );
if ( val < 100 ) {
setTimeout( progress, 100 );
}
}
setTimeout( progress, 2000 );
});
And CSS:
.enterance{
position:absolute;
overflow:hidden;
left:0;
top:0;
background-color:black;
width:100%;
height:100%;
z-index:10;
color:rgba(255,255,255,1.00);
}
.enterance .loader{
position:absolute;
width:600px;
height:500px;
top:50%;
left:50%;
margin:-250px 0 0 -300px;
}
.ui-progressbar-value {
background:url(http://goo.gl/V9dAfn) no-repeat;
width:600px;
height:429px;
border:0;
}
.ui-progressbar{
background:url(http://goo.gl/rBH0N1) no-repeat;
background-size:cover;
width:600px;
height:429px;
border:0;
}
.ui-progressbar .ui-progressbar-value{margin:0;}
.progress-label{
font-size:90px;
font-family: 'News Cycle', sans-serif;
color:#FFFFFF;
right:0px;
position:absolute;
}
So how can I NOT show this .ui-progressbar-value while it's waiting for 2 seconds? And Additionally, how can I add a fadeIn effect to this? like when page loads the image fades in ?
Thanks in advance.
Try this (can't be sure unless you had a fiddle of the issue):
$(function() {
var progressbar = $( "#progressbar" ),
progressLabel = $( ".progress-label" );
progressbar.progressbar({
value: false,
change: function() {
progressLabel.text( progressbar.progressbar( "value" ) + "%" );
},
complete: function() {
progressLabel.text( "100%" );
$(".loader").delay(1000).fadeOut(750);
}
});
function progress() {
var val = progressbar.progressbar( "value" ) || 0;
progressbar.progressbar( "value", val + 1 );
if ( val < 100 ) {
setTimeout( progress, 100 );
}
}
progressbar.progressbar( "value", 0 );
setTimeout( progress, 2000 );
});
Try removing the "$(function()" and running just the plain code?
var progressbar = $( "#progressbar" ),
progressLabel = $( ".progress-label" );
progressbar.progressbar({
value: false,
change: function() {
progressLabel.text( progressbar.progressbar( "value" ) + "%" );
},
complete: function() {
progressLabel.text( "100%" );
$(".loader").delay(1000).fadeOut(750);
}
});
function progress() {
var val = progressbar.progressbar( "value" ) || 0;
progressbar.progressbar( "value", val + 1 );
if ( val < 100 ) {
setTimeout( progress, 100 );
}
}
setTimeout( progress, 2000 );
Cant really work on it cuz it doesnt affect the fiddle right?

Categories