How to do '#somename' like twitter functionality? [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I am trying to do a functionality like which happens on Twitter.
If I write #J in text box, a list should appear show with autocomplete starting names "Javascript", "Java", "JQuery".
When I select Jquery, it should display in a TextBox. I got the autocomplete code from Jquery. But I am unable to do this '#' functionality.
Below is the code which I have done till now:
<html lang="en">
<head>
<meta charset="utf-8">
<title>autocomplete demo</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>
</head>
<body>
<label for="autocomplete">Select a programming language: </label>
<input id="autocomplete">
<script>
var tags = [ "Javascript", "Jquery", "Java" ];
document.getElementById('autocomplete').onkeypress = function (e) {
if (e.keyCode === 64 ) {
$( "#autocomplete" ).autocomplete({
source: function( request, response ) {
var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( request.term ), "i" );
response( $.grep( tags, function( item ){
return matcher.test( item );
}) );
}
});
}
else
{
return false;
}
};
</script>
</body>
</html>

Try this:
http://jsfiddle.net/gtnf41co/5/
It checks input value starts with #:
if (this.value.search("#") == 0)
then takes out the # in the request term
request.term.replace("#", "")

You can do this with the autocomplete functionality by adding the # symbol to your tags:
<script>
var tags = [ "#Javascript", "#Jquery", "#Java" ];
$( "#autocomplete" ).autocomplete({
source: tags
});
</script>

Related

Overriding datatables.js search behavior [duplicate]

This question already has an answer here:
Odd behavior of datatables.search function after modifying it
(1 answer)
Closed 4 years ago.
There are already several questions here on SO on this subject, however none is about my exact situation.
I have a datatable with 2 columns, one contains text input field and the other a select. The current behavior of datatables' search functionality is to search in the entire select HTML. The behvior I want is search only the chosen option.
I'm aware we can override/intercept the search/filter events, ie
$('#mapping-table_filter input', data_table.table().container())
.off('.DT')
.on('keyup.DT cut.DT paste.DT input.DT search.DT', function (e) {
data_table.search(...).draw();
});
// or
data_table.on('search.dt', function () {
});
But this does not help since .search does not accept a callback.
JSFiddle
https://jsfiddle.net/0oabx2mr/
If you search for any of "first", "second" or "third" both rows are still visible. I want to be able to search for "second" and "third" and only get the relevant row.
With slight architecture changes, your example may look like that:
var srcData = [
['firstOption', 'secondOption', 'thirdOption'],
['firstOption', 'secondOption', 'thirdOption'],
['firstOption', 'secondOption', 'thirdOption'],
['firstOption', 'secondOption', 'thirdOption']
];
var dataTable = $('#mytable').DataTable({
sDom: 't',
data: srcData,
columns: [{
title: 'Options',
render: (data, type, row) => '<select>'+row.reduce((options, option) => options += `<option value="${option}">${option}</option>`,'')+'</select>'
}]
});
var needle = null;
$.fn.DataTable.ext.search.push(
(settings, row, index) => $(dataTable.cell(`:eq(${index})`,':eq(0)').node()).find('select').val().match(needle) || !needle
);
$('#search').on('keyup', event => {
needle = $(event.target).val();
dataTable.draw();
});
<!doctype html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
</head>
<body>
<input id="search"></input>
<table id="mytable"></table>
</body>
</html>

Javascript array and image [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Okay so I've asked this question before but I didn't get the answer that solved my problem, I'll try to explain it better. So let say I have a array with 3 items and let say it landed on 0 I have a code set up for which it will display in div now I need the image to be displayed right next to the array that is displayed. So another example would be like I have an array of cars, BMW, civic, and Mercedes and let say I have a random number generator and it chooses 1 which is bmw the word will be displayed in the div and if the civic was picked the civic will has a civic logo next to it and if Mercedes was picked Mercedes will have a logo next to it. Also if possible I want the id added in I'll put the CSS of background-image to what ever the pic is(reasoning is I want to add some design in the picture)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<ul id="carList">
</ul>
<button id="getRandomCar">Get Random Car</button>
</body>
<script>
$(document).ready( function(){
var carsArray = [{
brand : 'BMW',
logo : 'link-to-logo.png',
model : 'BMW X7',
},
{
brand : 'Honda',
logo : 'link-to-logo.png',
model : 'Civic',
},
{
brand : 'Mercedez-Benz',
logo : 'link-to-logo.png',
model : 'C-Class Sedan',
}];
function randomNumberGenerator(params) {
return Math.round(Math.random()*params);
}
function randomCar() {
$('#getRandomCar').click( function() {
var selectedCar = randomNumberGenerator(carsArray.length - 1);
console.log(selectedCar);
var template = '<li>';
template += 'Brand: ' + carsArray[selectedCar].brand + '</br>';
template += 'Logo: ' + carsArray[selectedCar].logo + '</br>';
template += 'Model: ' + carsArray[selectedCar].model + '</br>';
$('#carList').html(template);
} );
}
randomCar();
});
</script>
</html>
Try this as a reference.
I've created an array of objects (carsArray). Since it's an object, you can add properties that you think necessary.
The sample generates a random number, then use it as index for the carsArray. The acquired object values will be injected into a DOM.

JavaScript Variables and User Input

Situation:
Currently I have a search box utilizing jQuery’s autocomplete plugin that allows the user to search for a sport’s team and then once found select on a submit button where it appends the team as a list item (preferable functionality would be when the user clicks on the actual team to append the item but at this point I am unsure of how to apply an on click function to the autocomplete drop down – suggestions welcome).
I am looking for a way to associate the newly appended list item to a predefined class or id so that certain formatting and displays are applied to the appended list item as soon as it is appended.Basically the user can search for any team in the NHL, NFL, etc. and I need to pair text colors and logos with them depending on which team they select - but the logos will appear separately in the body not in the list.
Example Code:
<!doctype html>
<html>
<head>
<title>TEST</title>
<meta charset="utf-8" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<style type="text/css">
</head>
<body>
<div class="ui-widget">
<input id="tags" type="text" placeholder="Search Teams"/>
<input id="submit" type="submit"/>
</div>
<ul class="target">
</ul>
<script>
$(function() {
var availableTeams = [
"Boston Red Sox",
"New England Patriots",
"Boston Celtics",
"Boston Bruins",
"New England Revolution"
];
$( "#tags" ).autocomplete({
source: availableTeams
});
});
$('#submit').click(
function() {
var term = $('#tags').val();
$('.target').append("<li>"+term+"</li>");
}
);
</script>
</body>
</html>
I have tried using a combination of if statements and document.getElementById to try and alter the html content but I cannot piece my thoughts together.
My thoughts:
if (tags == "Boston Red Sox") {
Then append "Boston Red Sox" with specific formatting as a list Item and corresponding logo below.
} else {
dont do anything
}
http://jsfiddle.net/kumcav30/ (ideally when appended it would resemble something like the fiddle). Any input is greatly appreciated.
jQuery will let you create elements and alter them before you add them to the document. So you could do something like:
$('#submit').click(
function() {
var term = $('#tags').val();
var newelement = $("<li>"+term+"</li>");
if (term == "Boston Red Sox") {
newelement.addClass("your-class");
//whatever else you need to do
}
$('.target').append(newelement);
}
);
How about a for loop?
$(function(){
var availableTeams = [
"Boston Red Sox",
"New England Patriots",
"Boston Celtics",
"Boston Bruins",
"New England Revolution"
];
$( "#tags" ).autocomplete({
source: availableTeams
});
var availableLogos = [
"redSox",
"patriots",
"celtics",
"bruins",
"englandRevolution"
];
function teamstyle(term){
var l = availableTeams.length;
for (var i = 0; i < l; i++){
if (term == availableTeams[i]){
var newelement = "<li class="+ availableLogos[i] +">"+term+"</li>"
$('.target').append(newelement);
}
}
}
$('#submit').click(function() {
var term = $('#tags').val();
teamstyle(term);
});
});
then you could use css like:
.redSox {color: red; background: url('path/to/logo.png');}
.bruins {color: yellow;}
....
Your question is a bit confusing. consider narrowing it down to what you want to achieve (:

How can I fetch data in autosuggest textbox from server/database?

I have created an autosuggest textbox that is fetching data from defined array.How can I make it fetch data from server?
Following is my code-
HTML code-
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>autocomplete demo</title>
<link rel="stylesheet" href="jquery-ui.css">
<script src="jquery-1.10.2.js"></script>
<script src="jquery-ui.js"></script>
</head>
<body>
<label for="autocomplete">Select a programming language: </label>
<input id="autocomplete">
<script>
var tags = [ "c++", "java", "php", "coldfusion", "javascript", "asp", "ruby" ];
$( "#autocomplete" ).autocomplete({
source: function( request, response ) {
var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( request.term ), "i" );
response( $.grep( tags, function( item ){
return matcher.test( item );
}) );
}
});
</script>
</body>
</html>
Javascript files are of too much length.I can't paste them here.
There are number of ways in which you can populate an autocomplete box with data from your server. One of the easiest way to do so is, retrieve the data from your server and store it locally, and then use it.
var searchData = [];
$.get("ajax/mydata", function( data ) {
searchData.push(data);
});
And then, carry on with the autocomplete part.
$( "#autocomplete" ).autocomplete({
source: searchData,
...
});
Also, have a look at the jQuery UI Autocomplete documentation at http://jqueryui.com/autocomplete/
ps. Don't forget to mark this as the answer if it works for you.

Unexpected end of input, jquery [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I get the following error: Uncaught SyntaxError: Unexpected end of input for line 1.
Here is the code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="./styles/default.css" />
<script src="./scripts/global.js"></script>
<script src="./scripts/jquery.js"></script>
<script>
$( document ).ready(function() {
var array = [ 'body_bg_2','body_bg_3','body_bg_4','body_bg_5' ];
var selected = array[Math.floor(Math.random() * array.length)];
$('<img src="./assets/'+selected+'.gif">').load(function() {
$(this).appendTo('body');
});
}
</script>
<title>Cats!</title>
</head>
I don't understand what the issue is? Anyone know of the solution?
You are missing closing ) of your document-ready handler
Use
<script>
$( document ).ready(function() {
var array = [ 'body_bg_2','body_bg_3','body_bg_4','body_bg_5' ];
var selected = array[Math.floor(Math.random() * array.length)];
$('<img src="./assets/'+selected+'.gif">').load(function() {
$(this).appendTo('body');
});
}); //<== Here you have missed )
</script>
$(document).ready(function () {
var array = [ 'body_bg_2', 'body_bg_3', 'body_bg_4', 'body_bg_5' ];
var selected = array[Math.floor(Math.random() * array.length)];
$('<img src="./assets/' + selected + '.gif">').load(function () {
$(this).appendTo('body');
});
}); /* <--- this is your fail */

Categories

Resources