javascript Alert to confirm if value entered twice - javascript

I have a form:
// 10 times
<input type="text" name="cityname" class="autocompletecity">
<input type="text" name="cityID" class="autocompletecityID">
When I enter the city name, it autocompletes the city name and the cityID from database with this code:
<?php for ($i = 0; $i < 10; $i++) { /*in the field class add $i */ ?>
$(function() {
function log( message ) {
$( "<div>" ).text( message ).prependTo( "#log" );
$( "#log" ).scrollTop( 1 );
}
$( ".autocompletecity<?php echo $i ?>" ).autocomplete({
source: "/*path to json*/",
select: function( event, ui ) {
var item = ui.item;
if(item) {
$(".autocompletecityID<?php echo $i ?>").val(item.cityID);
$(this).val(item.value +' ' + item.country);
return false;
}
}
//code from J.D.
select: function( event, ui ) {
var item = ui.item;
if(item) {
$('input[name="cityID"]').each(function(index, element) {
var $element = $(element);
if ($element.value() == item.cityID) {
alert('This city has already been selected');
}
});
}
}
})
.autocomplete( "instance" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<a>" +item.value + " " +item.country + "</a>" )
.appendTo( ul );
};
});
<?php } ?>
After it autocompletes the cityID, I would like to show an alert box if same cityID has alredy been entered: Click OK to confirm or Cancel to clear the cityname and cityID with repeated entry.
I tried to search in the jqueryui, but no luck...
Thanks!!

Try this:
select: function( event, ui ) {
var item = ui.item;
if(item) {
$('input[name="cityID"]').each(function(index) {
var $element = $(this);
if ($element.value() == item.cityID) {
alert('This city has already been selected');
}
});
}
}

Related

Uncaught SyntaxError: Invalid or unexpected token on Inline JS. JS script breaks on browser

I am facing an issue that has baffled and actually exhausted me for hours.
I have tried so many different things, have done and still doing various debugging techniques but I am very tired and would seek for some help of any kind.
I will post the very basics for start, in case someone has any helpful idea/suggestion to unstack me, and I might be adding further information or more code as we go if needed.
I am working on a Joomla site and on a custom component view I place an inline jQuery script at some point of my html output.
The problem is that while everything works well on my localhost, when I upload it online the javascript breaks in whatever point I try to create variables that contain html. Then the browser will auto-close the script tag with </script> and the rest of the js code will be output as html.
So for example, the following script:
<script>
(function($)
{
$(document).ready(function()
{
var loader = '<div id="loader"><div>';
});
})(jQuery);
</script>
will end up to something like below:
<script>
(function($)
{
$(document).ready(function()
{
var loader = '<div id="loader">';
</div></script>
});
})(jQuery);
</script>
*Another clue that I just got is that the issue seems to be when I upload this on Litespeed server.
I tested this on 2 different servers with Litespeed and then on 1 Apache.
The one on the Apache server works fine (like on my localhost).
This is my complete inline script, just in case anyone is in place to catch anything that I am missing.
(function($)
{
$(document).ready(function()
{
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
var obj = <?php echo json_encode($availableTags); ?>;
var searchForm = $('#adminForm');
var predefinedTags = $('.tags-cloud.popular-tags .li-item');
var searchTermId = '';
var oldSearchTermId = '';
var categories = <?php echo json_encode( $search_categories ); ?>;
var categoriesAction = '<?php echo (int)$sel_categories_option; ?>';
var list_limit = '<?php echo (int)$list_limit; ?>';
var list_limitstart = 0;
var list_order_by = '<?php echo $list_order_by; ?>';
var list_order_dir = '<?php echo $list_order_dir; ?>';
var menuItem = '<?php echo (int)$menuItem; ?>';
var show_image = '<?php echo (int)$show_image; ?>';
var show_date = '<?php echo (int)$show_date; ?>';
var which_date = '<?php echo $which_date; ?>';
var show_category = '<?php echo (int)$show_category; ?>';
var searchResults;
var loadMore = false;
var loader = "";
// Form submit
$(searchForm).on('submit', function(e) {
searchTermId = $('#sm-search-term-id').val();
e.preventDefault();
ajaxSearchArticles();
});
$('.search-order-selects').on('change', function(e) {
searchTermId = $('#sm-search-term-id').val();
list_order_by = $('#search-order').val();
list_order_dir = $('#search-order-dir').val();
list_limitstart = 0;
ajaxSearchArticles();
});
$(predefinedTags).on('click', function(e) {
searchTermId = $(this).attr('data-tagid');
$( "#sm-search" ).val( $(this).text() );
$( "#sm-search-term-id" ).val( searchTermId );
$( "#sm-search-description" ).html( '(' + $(this).attr('total_articles') + ' Total Articles)');
ajaxSearchArticles();
return false;
});
$('#search-results').on('click','#load-more-div', function() {
searchTermId = $('#sm-search-term-id').val();
list_limitstart = parseInt(list_limitstart) + parseInt(list_limit);
loadMore = true;
ajaxSearchArticles();
});
function appendResults() {
var html = '';
oldSearchTermId = searchTermId;
var l = parseInt(list_limit);
$(searchResults).each(function(i, e) {
var itemi = list_limitstart + i;
if (i < l) {
html += '<div id="artid-'+e.id+'" class="sm-search-result g-block s-item-'+itemi+'">';
html += '<div class="sm-search-result-content">';
if (show_image == '1') {
html += '<a href="'+ e.url +'" title="'+e.title+'" target="_blank">';
html += '<div class="smrc-image-holder"><img src="' + e.images + '" alt="'+e.title+'" /></div></a>';
}
html += '<div class="smrc-text-block"><h3>'+e.title+'</h3><p>'+e.introtext+'</p>';
if (show_date || show_category) {
html += '<div class="item-meta">';
if (show_date) {
var date = e.modified;
if (which_date === 'created') {
var date = e.created;
}
html += '<span class="item-date"><i class="fa fa-calendar-o" aria-hidden="true"></i> '+ date +'</span>';
}
if (show_category) {
html += '<span class="item-cat">in '+e.category +'</span>';
}
html += '</div>';
}
html += '</div></div></div>';
}
if (i === l) {
html += '<div id="load-more-div" class="sm-search-result load-more g-block">';
html += '<div class="sm-search-result-content" style="display: flex;align-items: flex-end;justify-content: center;height: 100%;">';
html += '<div class="load-more-results flex-item"><span>Load More...</span></div>';
html += '</div></div>';
}
});
html += '<div class="clear clearfix"></div>';
if (loadMore) {
$('#search-results').append(html);
} else {
$('#search-results').html(html);
}
loadMore = false;
}
// Autocomplete
$( function() {
var results = true;
$( "#sm-search" ).autocomplete({
minLength: 3,
source: obj,
focus: function( event, ui ) {
if (results) {
$( "#sm-search" ).val( ui.item.label );
}
event.preventDefault();
return false;
},
select: function( event, ui ) {
if (results) {
$( "#sm-search" ).val( ui.item.label );
$( "#sm-search-term-id" ).val( ui.item.value );
$( "#sm-search-description" ).html( '(' + ui.item.total_articles + ' Total Articles)');
}
event.preventDefault();
$(searchForm).submit();
return false;
},
response: function(event, ui) {
if (ui.content.length === 0) {
results = false;
var res = { label: "no results", value: 0 };
ui.content.push(res);
} else {
results = true;
}
}
}).autocomplete( "instance" )._renderItem = function( ul, item ) {
if (results) {
return $( "<li>" )
.append( "<div><strong>" + capitalizeFirstLetter(item.label) + "</strong> <small>(" + item.total_articles + " articles)</small></div>" )
.appendTo( ul );
} else {
return $( "<li>" )
.append( "<div>" + item.label + "</div>" )
.appendTo( ul );
}
};
});
// Ajax call
function ajaxSearchArticles() {
if (!searchTermId) {
$('#empty-message').text('No Tags Defined!');
setTimeout(function() {
$('#empty-message').text('');
}, 3000);
return false;
}
$('body').append(loader);
if (searchTermId !== oldSearchTermId) {
list_limitstart = 0;
}
var xhrRequest = {
'option' : 'com_rabattdatabase',
'task' : 'RabattAjax.ajaxReceiver',
'action' : 'customSearch',
'tagid' : searchTermId,
'orderby' : list_order_by,
'orderdir': list_order_dir,
'limit' : list_limit,
'limitstart' : list_limitstart,
'cats' : categories,
'itemid' : menuItem,
'catswhat': categoriesAction,
'<?php echo JSession::getFormToken();?>' : 1,
};
$.ajax({
context : this,
type : 'POST',
data : xhrRequest,
success : function(response) {
var response = $.parseJSON(response);
searchResults = response.data;
if (response.success == true) {
appendResults();
} else {
$('#search-results').html("<h4>We couldn't process your request!</h4>");
}
}
}); // End Ajax
}
})
})(jQuery);

Update SQL Server Database On Table Edit/Change

I have a dynamic HTML table that can be edited in multiple ways. There is an edit button where you can edit inline, the information of the rows and then click save to save the information. A deactivate button that grays out the row and an activate button that appears afterwards in order to reactivate it. And also and add row button that brings up a dialog box where you can hit add row again and add another row to the table.
However, while that is all nice...I want to write these changes/updates to a SQL Server database now so it actually saves them. I want to be able to automatically save these changes after each action (save, deactivate/activate, and add row) happens. I have never done this before so any help/advice/code would be appreciated!
JavaScript code:
// ----- Deactivate/Activate Row -----
$(document).on("click", "#html_master .deactivate", function () {
var $this = $(this);
var $tr = $this.closest('tr');
var action = $tr.hasClass('deactivated') ? 'activate' : 'deactivate';
// ------ Confirmation box in order to deactivate/activate row -----
if (confirm('Are you sure you want to ' + action + ' this entry?')) {
$tr.toggleClass('deactivated');
$this.val(function (i, t) {
return t == 'Deactivate' ? 'Activate' : 'Deactivate';
});
}
});
// ----- Edit Row -----
$(document).on("click", "#html_master .edit", function () {
var $this = $(this);
var tds = $this.closest('tr').find('td').not('.mr_id').filter(function () {
return $(this).find('.edit').length === 0;
});
if ($this.val() === 'Edit') {
$this.val('Save');
tds.prop('contenteditable', true);
} else {
var isValid = true;
var errors = '';
$('#myDialogBox').empty();
// changed from here.......
var elements = tds;
if (tds.find('input').length > 0) {
elements = tds.find('input');
}
elements.each(function (index, element) {
var type = $(this).attr('class');
var value = (element.tagName == 'INPUT') ? $(this).val() : $(this).text();
// changed from here....... to here
// ----- Switch statement that provides validation -----
switch (type) {
case "buyer_id":
if (!$.isNumeric(value)) {
isValid = false;
errors += "Please enter a valid Buyer ID\n";
}
break;
case "poc_n":
if (value == value.match(/^[a-zA-Z\s]+$/)) {
break;
}
else {
isValid = false;
errors += "Please enter a valid Name\n";
}
break;
case "poc_e":
if (value == value.match(/^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/)) {
break;
}
else {
isValid = false;
errors += "Please enter a valid Email\n";
}
break;
case "poc_p":
if (value == value.match('^[0-9 ()+/-]{10,}$')) {
break;
}
else {
isValid = false;
errors += "Please enter a valid Phone Number\n";
}
break;
}
})
if (isValid) {
$this.val('Edit');
tds.prop('contenteditable', false);
} else {
alert(errors);
}
}
});
// ----- Dialog Box -----
$( function() {
var dialog, form,
emailRegex = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+#[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,
phoneRegex = /^(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$/,
mr_name = $( "#mr_name" ),
buyer_id = $( "#buyer_id" ),
poc_n = $( "#poc_n" ),
poc_e = $( "#poc_e" ),
poc_p = $( "#poc_p" ),
allFields = $( [] ).add( mr_name ).add( buyer_id ).add( poc_n ).add( poc_e ).add( poc_p ),
tips = $( ".validateTips" );
console.log(allFields);
function updateTips( t ) {
tips
.text( t )
.addClass( "ui-state-highlight" );
setTimeout(function() {
tips.removeClass( "ui-state-highlight", 1500 );
}, 500 );
}
function checkRegexp( o, regexp, n ) {
if ( !( regexp.test( o.val() ) ) ) {
o.addClass( "ui-state-error" );
updateTips( n );
return false;
} else {
return true;
}
}
function addVendor() {
var valid = true;
allFields.removeClass( "ui-state-error" );
valid = valid && checkRegexp( mr_name, /^[a-z]([0-9a-z_\s])+$/i, "Please enter a valid vendor name" );
valid = valid && checkRegexp( buyer_id, /^(0|[1-9][0-9]*)$/, "Please enter a valid Buyer ID" );
valid = valid && checkRegexp( poc_n, /^[a-zA-Z ]*$/, "Please enter a valid name" );
valid = valid && checkRegexp( poc_e, emailRegex, "Please enter a valid email" );
valid = valid && checkRegexp( poc_p, phoneRegex, "Please enter a valid phone number" );
if ( valid ) {
var $tr = $( "#html_master tbody tr" ).eq(0).clone();
$.each(allFields, function(){
$tr.find('.' + $(this).attr('id')).html( $(this).val() );
});
$tr.find('.mr_id').html( $( "#html_master tbody tr" ).length + 1 );
$( "#html_master tbody" ).append($tr);
/*
$( "#html_master tbody" ).append( "<tr>" +
"<td>" + mr_name.val() + "</td>" +
"<td>" + buyer_id.val() + "</td>" +
"<td>" + poc_n.val() + "</td>" +
"<td>" + poc_e.val() + "</td>" +
"<td>" + poc_p.val() + "</td>" +
"</tr>" );
*/
dialog.dialog( "close" );
}
return valid;
}
var dialog = $( "#dialog-form" ).dialog({
autoOpen: false,
height: 400,
width: 350,
modal: true,
buttons: {
"Add Row": addVendor,
Cancel: function() {
dialog.dialog( "close" );
}
},
close: function() {
form[ 0 ].reset();
allFields.removeClass( "ui-state-error" );
}
});
form = dialog.find( "form" ).on( "submit", function( event ) {
event.preventDefault();
addVendor();
});
$( ".create-user" ).button().on( "click", function() {
dialog.dialog( "open" );
});
} );
HTML/PHP code:
<?php
$host="xxxxxxxxx";
$dbName="xxxxx";
$dbUser="xxxxxxxxxxx";
$dbPass="xxxxxx";
$dbh = new PDO( "sqlsrv:server=".$host."; Database=".$dbName, $dbUser, $dbPass);
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "SELECT * FROM Stage_Rebate_Master ORDER BY MR_ID ASC";
?>
<html>
<body>
<div id="dialog-form" title="Add Vendor">
<p class="validateTips">All form fields are required.</p>
<form>
<fieldset>
<label for="mr_name">Vendor</label>
<input type="text" name="mr_name" id="mr_name" class="text ui-widget-content ui-corner-all">
<label for="buyer_id">Buyer ID</label>
<input type="text" name="buyer_id" id="buyer_id" class="text ui-widget-content ui-corner-all">
<label for="poc_n">POC Name</label>
<input type="text" name="poc_n" id="poc_n" class="text ui-widget-content ui-corner-all">
<label for="poc_p">POC Email</label>
<input type="text" name="poc_e" id="poc_e" class="text ui-widget-content ui-corner-all">
<label for="poc_p">POC Phone</label>
<input type="text" name="poc_p" id="poc_p" class="text ui-widget-content ui-corner-all">
<input type="submit" tabindex="-1" style="position:absolute; top:-1000px">
</fieldset>
</form>
</div>
Without Ajax - This can be done with a (PHP/ASP) 'pass-through' window.open - this is a window that you open which processes the passed parameters and writes them to an SQL database and then closes itself. This leaves the original site intact but updates the database with your changes.
So, window.open(saveChanges.php?param1=..&param2=..&etc,....)
The saveChanges.php file should read in the passed params and run the appropriate SQL to save updates.
Once completed, the saveChanges.php file should close itself with window.close()
Your database should now reflect the contents of your web page entries.

How to dynamically get satisfy autocomplete value using .attr() or .on('click', from same source?

I have two input fields.
<input type="text" name="image" />
<input type="text" name="file" />
Javascript
$('input[name=\'image\'], input[name=\'file\']').autocomplete({
minLength: 2,
source: function( request, response ) {
var thisType = $(this).attr('name');
$.getJSON( "files/", {
term: extractLast( request.term ),
type: thisType
}, response );
},
create: function () {
var thisType = $(this).attr('name');
if (thisType == 'image') {
$(this).data("autocomplete")._renderItem = function(ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append('<a><img src="files/' + item.label + '.jpg" />' + item.label + '</a>')
.appendTo( ul );
};
} else {
$(this).data("autocomplete")._renderItem = function(ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append('<a>' + item.label + '</a>')
.appendTo( ul );
};
}
},
});
PHP
<?php
if (empty($_GET['term'])) exit;
$q = strtolower($_GET["term"]);
$type = strtolower($_GET["type"]);
if (get_magic_quotes_gpc()) $q = stripslashes($q);
$files = array();
if ($type == 'image') {
foreach(glob('image/*.jpg*', GLOB_BRACE) as $key=>$file) {
$files[] = substr($file, 0, -4);
}
} else {
foreach(glob('image/*.txt*', GLOB_BRACE) as $key=>$file) {
$files[] = substr($file, 0, -4);
}
}
$files = array_unique($files);
$files = array_combine($files, $files);
$result = array();
foreach ($files as $key=>$value) {
if (strpos(strtolower($key), $q) !== false) {
array_push($result, array("id"=>$value, "label"=>$key, "value" => strip_tags($key)));
}
if (count($result) > 11) break;
}
echo json_encode($result);
I want when i type on the first input, as results it need to show me image files name with preview and when type on the second input, as results it need to show me only text files name.Is there any way to if click on or when type or using attr dynamically get satisfy value for each input from same source? I am trying to do link this but not working..

How to set minLength for jQuery combobox for individual elements

How do I set a minLength for a single element without the others been affected
EDIT:
Heres the plugin code
(function ( $ ) {
$.widget( "ui.combobox", {
_create: function() {
var input,
self = this,
select = this.element.hide(),
selected = select.children( ":selected" ),
value = selected.val() ? selected.text() : "",
wrapper = this.wrapper = $( "<span>" )
.addClass( "ui-combobox" )
.insertAfter( select );
input = $( "<input>" )
.appendTo( wrapper )
.val( value )
.addClass( "ui-state-default ui-combobox-input" )
.autocomplete({
delay: 300,
minLength: 2,
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;
self._trigger( "selected", event, {
item: ui.item.option
});
},
change: function( event, ui ) {
if ( !ui.item ) {
var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( $(this).val() ) + "$", "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
$( this ).val( "" );
select.val( "" );
input.data( "autocomplete" ).term = "";
return false;
}
}
}
})
.addClass( "ui-widget ui-widget-content ui-corner-left" );
input.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.label + "</a>" )
.appendTo( ul );
};
$( "<a>" )
.attr( "tabIndex", -1 )
.attr( "title", "Show All Items" )
.appendTo( wrapper )
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass( "ui-corner-all" )
.addClass( "ui-corner-right ui-combobox-toggle" )
.click(function() {
// close if already visible
if ( input.autocomplete( "widget" ).is( ":visible" ) ) {
input.autocomplete( "close" );
return;
}
// work around a bug (likely same cause as #5265)
$( this ).blur();
// pass empty string as value to search for, displaying all results
input.autocomplete( "search", "" );
input.focus();
});
},
destroy: function() {
this.wrapper.remove();
this.element.show();
$.Widget.prototype.destroy.call( this );
}
});
})( jQuery );
I'm selecting which select tags must be made into comboboxes like this.
$("#tracklisting").combobox({
selected: function(event, ui) {
var tracklisting = $("#tracklisting").val();
var id = $("#id").val();
$.post('writeToDB.php', {
id: id,
tracklisting: tracklisting
});
}
})
Where do I put $("#tracklisting").autocomplete( "option", "minLength", 0 ); to set the length. I've tried multiple things but to no avail.
EDIT:
Here is a jsfiddle link to the project. combox can stay on the default but combobox2 must have a minlegth of 0. http://jsfiddle.net/5cMjk/4/
The .combobox() widget from jQuery UI is a modification of .autocomplete() and doesn't seem to have as many options.
But from its code you can notice that it creates an input tag on the fly, you could try reapplying the .autocomplete() method on it again.
The input is placed in a span after the old select tag, I used .next() to select the span :
var myMinLength = 10;
$("#tracklisting").next().children("input").autocomplete({
delay: 0,
minLength: myMinLength ,
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;
self._trigger( "selected", event, {
item: ui.item.option
});
},
change: function( event, ui ) {
if ( !ui.item ) {
var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( $(this).val() ) + "$", "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
$( this ).val( "" );
select.val( "" );
input.data( "autocomplete" ).term = "";
return false;
}
}
}
})
If your combobox breaks after this, you could also try to add these lines that came after :
$("#tracklisting").next().children("input").addClass( "ui-widget ui-widget-content ui-corner-left" );
$("#tracklisting").next().children("input").data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.label + "</a>" )
.appendTo( ul );
};
Did you try this:
$("#tracklisting").autocomplete({ minLength: 2 });
See also: http://jqueryui.com/demos/autocomplete/#option-minLength
Demo: http://jsfiddle.net/5cMjk/1/

jquery Ui Combobox Error on Chrome / IE 7

For some reason the combobox button aint showing on IE or Chrome, so i end up with just a textbox. anyone figured out how to solve?
Using latest jquery/jqueryui/combobox version.
Heres my edited version of ui.combobox (specially coz original version doesnt give an id to the new element), also theres a fix for combobox size:
(function( $ ) {
$.widget( "ui.combobox", {
_create: function() {
var self = this,
id = this.element.attr("id"),
select = this.element,
theWidth = select.width(),
selected = select.children( ":selected" ),
value = selected.val() ? selected.text() : "";
select.hide();
//fix, doesnt let the element beign too short.
if(theWidth < 110) {
theWidth = 110;
}
var input = $('<input id="' + id + '-combo" style="width: ' + theWidth + 'px;">')
//.insertAfter( select )
.val( value )
.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 {
id: this.value,
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;
self._trigger( "selected", event, {
item: ui.item.option
});
},
change: function( event, ui ) {
if ( !ui.item ) {
var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( $(this).val() ) + "$", "i" ),
valid = false;
select.children( "option" ).each(function() {
if ( this.value.match( matcher ) ) {
this.selected = valid = true;
return false;
}
});
if ( !valid ) {
// remove invalid value, as it didn't match anything
$( this ).val( "" );
select.val( "" );
return false;
}
}
}
})
.addClass( "ui-widget ui-widget-content ui-corner-left" );
var span = $('<span style="white-space: nowrap;"></span>')
.append(input).insertAfter( select );
input.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.label + "</a>" )
.appendTo( ul );
};
$("<button id='" + id + '-combo-button' + "> </button>")
.attr( "tabIndex", -1 )
.attr( "title", "Mostrar Todos os itens" )
.insertAfter( input )
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass( "ui-corner-all" )
.addClass( "ui-corner-right ui-button-icon" )
.click(function() {
// close if already visible
if ( input.autocomplete( "widget" ).is( ":visible" ) ) {
input.autocomplete( "close" );
return;
}
// pass empty string as value to search for, displaying all results
input.autocomplete( "search", "" );
input.focus();
});
}
});
})( jQuery );
Heres the fix my friend pointed. This version of ui.combobox got auto width, and few fixes i found # web. works on ie also.
(function( $ ) {
$.widget( "ui.combobox", {
_create: function() {
var self = this,
id = this.element.attr("id"),
select = this.element,
theWidth = select.width(),
selected = select.children( ":selected" ),
value = selected.val() ? selected.text() : "";
select.hide();
//fix, doesnt let the element beign too short.
if(theWidth < 110) {
theWidth = 110;
}
var input = $('<input id="' + id + '-combo" style="width: ' + theWidth + 'px;">')
//.insertAfter( select )
.val( value )
.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 {
id: this.value,
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;
self._trigger( "selected", event, {
item: ui.item.option
});
},
change: function( event, ui ) {
if ( !ui.item ) {
var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( $(this).val() ) + "$", "i" ),
valid = false;
select.children( "option" ).each(function() {
if ( this.value.match( matcher ) ) {
this.selected = valid = true;
return false;
}
});
if ( !valid ) {
// remove invalid value, as it didn't match anything
$( this ).val( "" );
select.val( "" );
return false;
}
}
}
})
.addClass( "ui-widget ui-widget-content ui-corner-left" );
var span = $('<span style="white-space: nowrap;"></span>')
.append(input).insertAfter( select );
input.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.label + "</a>" )
.appendTo( ul );
};
$("<button id='" + id + "-combo-button'> </button>")
.attr( "tabIndex", -1 )
.attr( "title", "Mostrar Todos os itens" )
.insertAfter(input)
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass( "ui-corner-all" )
.addClass( "ui-corner-right ui-button-icon" )
.click(function() {
// close if already visible
if ( input.autocomplete( "widget" ).is( ":visible" ) ) {
input.autocomplete( "close" );
return;
}
// pass empty string as value to search for, displaying all results
input.autocomplete( "search", "" );
input.focus();
});
}
});
})( jQuery );

Categories

Resources