I want to customize auto suggestion result. I want to add more two addresses at the top of the result. Is it possible using google api?
for more understanding I stick here my app screen. there I am entering address. it showing predicted addresses, How can I add 2 more address at top of the result.
You can't do much with the Autocomplete class, at least not with any documented method. You can use the Autocomplete Service class and the getPlacePredictions method to mimic the behavior of the standard Autocomplete.
What that means is that you will have to build your own UI and behaviors, but it also gives you more flexibility to style it the way you want, and it will allow you to add your custom addresses easily.
Here is a quick example. It just adds two custom addresses on top. You will have to implement the logic behind the 2 custom addresses as currently nothing will happen when you click on them. But that's not the trickiest part, and this example shows already a lot of what you can do with it.
var autocompleteService, placesService, results, map;
function initialize() {
results = document.getElementById('results');
var mapOptions = {
zoom: 5,
center: new google.maps.LatLng(50, 50)
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
// Bind listener for address search
google.maps.event.addDomListener(document.getElementById('address'), 'input', function() {
results.style.display = 'block';
getPlacePredictions(document.getElementById('address').value);
});
// Show results when address field is focused (if not empty)
google.maps.event.addDomListener(document.getElementById('address'), 'focus', function() {
if (document.getElementById('address').value !== '') {
results.style.display = 'block';
getPlacePredictions(document.getElementById('address').value);
}
});
// Hide results when click occurs out of the results and inputs
google.maps.event.addDomListener(document, 'click', function(e) {
if ((e.target.parentElement.className !== 'pac-container') && (e.target.parentElement.className !== 'pac-item') && (e.target.tagName !== 'INPUT')) {
results.style.display = 'none';
}
});
autocompleteService = new google.maps.places.AutocompleteService();
placesService = new google.maps.places.PlacesService(map);
}
// Get place predictions
function getPlacePredictions(search) {
autocompleteService.getPlacePredictions({
input: search,
types: ['establishment', 'geocode']
}, callback);
}
// Get place details
function getPlaceDetails(placeId) {
var request = {
placeId: placeId
};
placesService.getDetails(request, function(place, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
var center = place.geometry.location;
var marker = new google.maps.Marker({
position: center,
map: map
});
map.setCenter(center);
// Hide autocomplete results
results.style.display = 'none';
}
});
}
// Place search callback
function callback(predictions, status) {
// Empty results container
results.innerHTML = '';
// Place service status error
if (status != google.maps.places.PlacesServiceStatus.OK) {
results.innerHTML = '<div class="pac-item pac-item-error">Your search returned no result. Status: ' + status + '</div>';
return;
}
// Build output with custom addresses
results.innerHTML += '<div class="pac-item custom"><span class="pac-icon pac-icon-marker"></span>My home address</div>';
results.innerHTML += '<div class="pac-item custom"><span class="pac-icon pac-icon-marker"></span>My work address</div>';
// Build output for each prediction
for (var i = 0, prediction; prediction = predictions[i]; i++) {
// Insert output in results container
results.innerHTML += '<div class="pac-item" data-placeid="' + prediction.place_id + '" data-name="' + prediction.terms[0].value + '"><span class="pac-icon pac-icon-marker"></span>' + prediction.description + '</div>';
}
var items = document.getElementsByClassName("pac-item");
// Results items click
for (var i = 0, item; item = items[i]; i++) {
item.onclick = function() {
if (this.dataset.placeid) {
getPlaceDetails(this.dataset.placeid);
}
};
}
}
google.maps.event.addDomListener(window, 'load', initialize);
body,
html {
font-family: Arial, sans-serif;
padding: 0;
margin: 0;
height: 100%;
}
#map-canvas {
height: 130px;
margin-bottom: 10px;
}
table {
border-collapse: collapse;
margin-left: 20px;
}
table td {
padding: 3px 5px;
}
label {
display: inline-block;
width: 160px;
font-size: 11px;
color: #777;
}
input {
border: 1px solid #ccc;
width: 170px;
padding: 3px 5px;
box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-shadow: 0 2px 6px rgba(0, 0, 0, .1);
}
.pac-container {
background-color: #fff;
z-index: 1000;
border-radius: 2px;
font-size: 11px;
box-shadow: 0 2px 6px rgba(0, 0, 0, .3);
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
overflow: hidden;
width: 350px;
}
.pac-icon {
width: 15px;
height: 20px;
margin-right: 7px;
margin-top: 6px;
display: inline-block;
vertical-align: top;
background-image: url(https://maps.gstatic.com/mapfiles/api-3/images/autocomplete-icons.png);
background-size: 34px;
}
.pac-icon-marker {
background-position: -1px -161px;
}
.pac-item {
cursor: pointer;
padding: 0 4px;
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
line-height: 30px;
vertical-align: middle;
text-align: left;
border-top: 1px solid #e6e6e6;
color: #999;
}
.pac-item.custom {
background-color: #FFF9C4;
}
.pac-item:hover {
background-color: #efefef;
}
.pac-item-error,
.pac-item-error:hover {
color: #aaa;
padding: 0 5px;
cursor: default;
background-color: #fff;
}
<!-- Replace the value of the key parameter with your own API key. -->
<script src="//maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map-canvas"></div>
<table>
<tr>
<td>
<label for="address">Address:</label>
</td>
</tr>
<tr>
<td>
<input id="address" placeholder="Enter address" type="text" tabindex="1" />
</td>
</tr>
<tr>
<td colspan="2">
<div id="results" class="pac-container"></div>
</td>
</tr>
</table>
Most of the code is commented so it should speak for itself.
JSFiddle demo
In case anyone needs to move through the results with arrow keys, I've written something like this in addition to the example provided by MrUpsidown.
Functions nextAll and prevAll can be probably simplified to next and prev, but I had to use these as I have some dividing elements of different classes (than .pac-item) in the results.
// move through options on key down or up
$(input).keydown(function(e) {
switch (e.which) {
case 40: // move down
e.preventDefault(); // prevent moving the cursor
if(document.querySelector('.pac-item-selected') == null)
$('.pac-item').first().addClass('pac-item-selected');
else {
var i = $('.pac-item:not(:last-child).pac-item-selected').nextAll('.pac-item');
if(i.length > 0){
$('.pac-item:not(:last-child).pac-item-selected').removeClass('pac-item-selected');
i[0].classList.add('pac-item-selected');
}
}
break;
case 38: // move up
e.preventDefault(); // prevent moving the cursor
var i = $('.pac-item:not(:first-child).pac-item-selected').prevAll('.pac-item');
if(i.length > 0){
$('.pac-item:not(:first-child).pac-item-selected').removeClass('pac-item-selected');
i[0].classList.add('pac-item-selected');
}
break;
case 13: // submit when enter is pressed
e.preventDefault();
if(document.querySelector('.pac-item-selected') == null)
$('.pac-item').first().click();
else
$('.pac-item-selected').click();
break;
}
});
$(document).on({ // remove selected class on hover
mouseenter: function () {
$('.pac-item-selected').removeClass('pac-item-selected');
}
}, ".pac-item");
Related
I have recently taken up programming and my first task is to create a queue at the post office. The code kind of works and does everything I need, except, I need the input array elements to be displayed with some style, more like separate squares with names (similarly to the way the buttons are styled), not only in line separated by commas - see the demo below please.
var guests = new Array();
for (var i=0;i<10;i++){
guests[i] = prompt("Enter your name");
if (guests[0] == null) {
alert("No guests in a queue");
break;
} else if (guests[i] == null) {
break;
} else {
document.getElementById("queue").innerHTML=guests;
}
}
function removePeople() {
guests.shift();
document.getElementById("queue").innerHTML=guests;
}
function reversePeople() {
guests.reverse();
document.getElementById("queue").innerHTML=guests;
}
button:hover {
background-color:beige;
color:black;
}
.button {
background-color: green;
border: 2px solid black;
border-radius:4px;
color: white;
padding: 5px 15px;
text-align: center;
font-size: 16px;
margin: 4px 2px;
}
<body>
<p id="queue"></p>
<button class="button" onclick ="removePeople()">Next</button>
<button class="button" onclick ="reversePeople()">Reverse</button>
</body>
I tried hard to find some hints here but everything seems too complicated for my level of understanding. So, if there is no easy way, I would rather ask for some specific materials where I could find how to deal with it. I am learning through W3Schools and also reading Eloquent Javascript publication, but coulnd't find anything concerning my problem. I hope my question makes sense.
Also, if you have any idea how to logically improve the code, I am open to any discussion.
I've tried to keep your code mostly the same.
To be able to change the css of a single queue item you need to wrap that item in something (in this example i've used a span)
I've created a function createQueueItemsHtml() that returns the array items wrapped in a span now you can use the following css selector to add css to each item #queue span
var guests = new Array();
for (var i = 0; i < 3; i++) {
var guestInput = prompt("Enter your name");
if(guestInput != "") {
guests[i] = guestInput;
}
if (guests[0] == null) {
alert("No guests in a queue");
break;
} else if (guests[i] == null) {
break;
} else {
document.getElementById("queue").innerHTML = createQueueItemsHtml();
}
}
function removePeople() {
guests.shift();
document.getElementById("queue").innerHTML = createQueueItemsHtml();
}
function reversePeople() {
guests.reverse();
document.getElementById("queue").innerHTML = createQueueItemsHtml();
}
function createQueueItemsHtml() {
let queueString = "";
for (var ii = 0; ii < guests.length; ii++) {
queueString += "<span>" + guests[ii] + "</span>";
}
return queueString;
}
button:hover {
background-color: beige;
color: black;
}
.button {
background-color: green;
border: 2px solid black;
border-radius: 4px;
color: white;
padding: 5px 15px;
text-align: center;
font-size: 16px;
margin: 4px 2px;
}
#queue span {
background-color: green;
border: 2px solid black;
border-radius: 4px;
color: white;
padding: 5px 15px;
}
<p id="queue"></p>
<button class="button" onclick ="removePeople()">Next</button>
<button class="button" onclick ="reversePeople()">Reverse</button>
You can make your guests into <div> elements and then style those in any way you want or need. (I haven't touched the rest of your code, only the part that was needed for this particular thing)
Just change this bit
else {
document.getElementById("queue").innerHTML=guests;
}
To this:
} else {
var guest = document.createElement('div');
guest.classList.add('guest');
guest.innerHTML = guests[i];
document.getElementById("queue").appendChild(guest);
}
What it does is create a <div> element for each item in your guests array, add class="guest" to the element and add the name from your prompt to it. Then it appends this element to the #queue.
Your HTML would then look like this:
<p id="queue">
<div class="guest">john</div>
<div class="guest">doe</div>
</p>
I would suggest changing the <p> to <section> or something like that, just for the sake of semantics.
You can then style these elements like this:
.guest {
}
var guests = new Array();
for (var i=0;i<10;i++){
guests[i] = prompt("Enter your name");
if (guests[0] == null) {
alert("No guests in a queue");
break;
} else if (guests[i] == null) {
break;
} else {
var guest = document.createElement('div');
guest.classList.add('guest');
guest.innerHTML = guests[i];
document.getElementById("queue").appendChild(guest);
}
}
guest:hover {
background-color:beige;
color:black;
}
.guest {
background-color: green;
border: 2px solid black;
border-radius:4px;
color: white;
padding: 5px 15px;
text-align: center;
font-size: 16px;
margin: 4px 2px;
display: inline-block
}
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
<p id="queue"></p>
</body>
</html>
I am creating a "Keep Lines containing" project. I almost completed this task. But "Search Lines for" is working only 1 line. Multiple "Search
Lines for" is not working. I need "Search Lines for" in multiple lines.
All used HTML, CSS & javascript codes are here
I created a Codepen page for it. Please check : https://codepen.io/coderco/pen/LYGQyqr
function loadfile(fileid, loadid) {
document.getElementById(loadid).value = 'Loading...';
setTimeout(function() {
loadfile2(fileid, loadid)
}, 1000);
}
function loadfile2(fileid, loadid) {
if (!window.FileReader) {
document.getElementById(loadid).value = 'Your browser does not support HTML5 "FileReader" function required to open a file.';
} else {
fileis = document.getElementById(fileid).files[0];
var fileredr = new FileReader();
fileredr.onload = function(fle) {
var filecont = fle.target.result;
document.getElementById(loadid).value = filecont;
}
fileredr.readAsText(fileis);
}
}
function savefile(saveasid, saveid) {
if (!window.Blob) {
alert('Your browser does not support HTML5 "Blob" function required to save a file.');
} else {
var txtwrt = document.getElementById(saveid).value;
if (document.getElementById('dos').checked == true) txtwrt = txtwrt.replace(/\n/g, '\r\n');
var textblob = new Blob([txtwrt], {
type: 'text/plain'
});
var saveas = document.getElementById(saveasid).value;
var dwnlnk = document.createElement('a');
dwnlnk.download = saveas;
dwnlnk.innerHTML = "Download File";
if (window.webkitURL != null) {
dwnlnk.href = window.webkitURL.createObjectURL(textblob);
} else {
dwnlnk.href = window.URL.createObjectURL(textblob);
dwnlnk.onclick = destce;
dwnlnk.style.display = 'none';
document.body.appendChild(dwnlnk);
}
dwnlnk.click();
}
}
function destce(event) {
document.body.removeChild(event.target);
}
function cleartext() {
document.getElementById('input_output').value = '';
document.getElementById('removed').innerHTML = '';
document.getElementById('removed_box').value = '';
}
function SelectAll(id) {
document.getElementById(id).focus();
document.getElementById(id).select();
}
var fieldnum = 0;
var fieldtype = '';
var cacherem = 'no';
var enableregex = 'no';
function makeregexp() {
var regexpoutarr = new Array();
for (var x = 0; x < (fieldnum + 1); x++) {
regexpoutarr[x] = document.getElementById('addfield' + x).value.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1');
}
var regexpout = '';
if (fieldtype == 'AND') regexpout = '((?=.*' + regexpoutarr.join(')(?=.*') + ').*)';
if (fieldtype == 'OR') regexpout = '(' + regexpoutarr.join('|') + ')';
if (fieldtype == '') regexpout = document.getElementById('addfield0').value.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1');
return regexpout;
}
function removelines(whatlines) {
var textin = document.getElementById('input_output').value.replace(/\r/g, '');
var toremove = makeregexp();
var textinarr = textin.split('\n');
var textinarrcnt = textinarr.length;
var textoutarr = new Array();
var textoutarrcnt = 0;
var linesremovedcnt = 0;
var casen = 'i';
if (document.getElementById('case_sen').checked == true) casen = '';
if (enableregex == 'yes') toremove = document.getElementById('addfield0').value;
else toremove = makeregexp();
var killfun = 'no';
try {
var toremoveregx = new RegExp(toremove, casen);
} catch (err) {
alert('Something is incorrect (' + err + ') within your regular expression.\nBe sure special characters .*+?^=!:${}()|\\ used as literals have been escaped with a backslash.');
killfun = 'yes';
}
if (killfun == 'no') {
if (whatlines == 'containing' && cacherem == 'no') {
for (var x = 0; x < textinarrcnt; x++) {
if (toremoveregx.test(textinarr[x]) == false) {
textoutarr[textoutarrcnt] = textinarr[x];
textoutarrcnt++;
} else linesremovedcnt++;
}
}
if (whatlines == 'notcontaining' && cacherem == 'no') {
for (var x = 0; x < textinarrcnt; x++) {
if (toremoveregx.test(textinarr[x]) == true) {
textoutarr[textoutarrcnt] = textinarr[x];
textoutarrcnt++;
} else linesremovedcnt++;
}
}
var removedcachearr = new Array();
if (whatlines == 'containing' && cacherem == 'yes') {
for (var x = 0; x < textinarrcnt; x++) {
if (toremoveregx.test(textinarr[x]) == false) {
textoutarr[textoutarrcnt] = textinarr[x];
textoutarrcnt++;
} else {
removedcachearr[linesremovedcnt] = textinarr[x];
linesremovedcnt++;
}
}
}
if (whatlines == 'notcontaining' && cacherem == 'yes') {
for (var x = 0; x < textinarrcnt; x++) {
if (toremoveregx.test(textinarr[x]) == true) {
textoutarr[textoutarrcnt] = textinarr[x];
textoutarrcnt++;
} else {
removedcachearr[linesremovedcnt] = textinarr[x];
linesremovedcnt++;
}
}
}
var textout = textoutarr.join('\n');
document.getElementById('input_output').value = textout;
if (cacherem == 'yes') {
var removedcache = removedcachearr.join('\n');
document.getElementById('removed_box').value = removedcache;
}
document.getElementById('removed').innerHTML = '' + linesremovedcnt + ' removed / ' + textoutarrcnt + ' remain.';
}
}
function addfield(field) {
if (field == 'reset') {
document.getElementById('inputfields').innerHTML = '<input type="text" id="addfield0" value="" style="width:100%;" />'
document.getElementById('andbttn').style.display = 'inline-block';
document.getElementById('orbttn').style.display = 'inline-block';
fieldnum = 0;
fieldtype = '';
} else {
fieldnum++;
if (fieldnum == 1) {
if (field == 'andfield') {
document.getElementById('orbttn').style.display = 'none';
fieldtype = 'AND';
} else {
fieldtype = 'OR';
document.getElementById('andbttn').style.display = 'none';
}
}
var newfield = fieldtype + '<input type="text" id="addfield' + fieldnum + '" value="" style="width:100%;" />';
var newdiv = document.createElement('div');
newdiv.innerHTML = newfield;
document.getElementById('inputfields').appendChild(newdiv);
}
resizepage();
}
function disrem() {
var chkedstate = document.getElementById('dremoved').checked;
if (chkedstate == true) {
document.getElementById('removed_box').style.display = 'inline-block';
cacherem = 'yes';
} else {
cacherem = 'no';
document.getElementById('removed_box').value = '';
document.getElementById('removed_box').style.display = 'none';
}
resizepage();
}
function selectele(eleid) {
if (document.selection) {
var range = document.body.createTextRange();
range.moveToElementText(document.getElementById(eleid));
range.select();
} else {
var range = document.createRange();
range.selectNode(document.getElementById(eleid));
window.getSelection().addRange(range);
}
}
function regexsrch() {
var chkedstate = document.getElementById('regex_srch').checked;
if (chkedstate == true) {
addfield('reset');
enableregex = 'yes';
document.getElementById('addfielddiv').innerHTML =
'<div style="padding:3px 0px 3px 0px;"><input type="checkbox" id="regex_srch" onclick="regexsrch();" CHECKED />Enable regular expression search. ' +
'Use <span id="catordog" style="color:#990000;" onclick="selectele(this.id)">(cat|dog|bird)</span> for cat OR dog OR bird. Use <span id="catanddog" style="color:#990000;" onclick="selectele(this.id)">((?=.*cat)(?=.*dog)(?=.*bird).*)</span> for cat AND dog AND bird. ' +
'Remember to escape special characters .*+?^=!:${}()|\\ with a backslash when used as literals within a regular expression. Use the <a target="_blank" href="" style="color:#0000FF;">Escape Literal Characters</a> tool. ' +
'Learn more about regular expressions visit <a rel="nofollow" target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions" style="color:#0000FF;">developer.mozilla.org</a>.</div>';
} else {
document.getElementById('addfield0').value = '';
enableregex = 'no';
document.getElementById('addfielddiv').innerHTML =
'Add <input type="button" id="andbttn" value="AND" onClick="addfield(\'andfield\');" /> ' +
'<input type="button" id="orbttn" value="OR" onClick="addfield(\'orfield\');" /> search field. ' +
'<input type="button" value="Reset" onClick="addfield(\'reset\');" /> ' +
'<input type="checkbox" id="regex_srch" onclick="regexsrch();" />Enable regular expression search.';
}
resizepage();
}
html {
height: 100%;
}
body {
height: 100%;
margin: 0px;
padding: 0px;
font-family: arial;
font-size: 16px;
line-height: 1.7;
}
h1 {
display: block;
font-size: 18px;
font-weight: bold;
margin: 0px;
padding: 0px;
}
.se-for {
font-size: 27px;
font-weight: bold;
color: #b93207;
padding-top: 54px;
}
.contentt,
.wordd {
display: block;
margin: 0px;
padding: 8px 10px 8px 10px;
overflow: scroll;
font-family: arial;
font-size: 16px;
line-height: 1.7;
color: #000000;
background-color: #FFFFFF;
border: 1px solid #000000;
outline: none;
resize: none;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
border-radius: 4px 4px 4px 4px;
width: 100%;
font-size: 18px;
}
.contentt {
height: 400px;
overflow: auto;
}
.wordd {
height: 99px;
overflow: auto;
}
input {
display: inline-block;
height: 33px;
line-height: 1;
vertical-align: middle;
font-size: 16px;
outline: none;
resize: none;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
input::-moz-focus-inner {
border: 0;
padding: 0
}
input[type='radio'] {
width: 20px;
height: 20px;
vertical-align: middle;
margin: 0px;
padding: 0px;
font-size: 16px;
}
input[type='checkbox'] {
width: 20px;
height: 20px;
vertical-align: middle;
margin: 0px;
padding: 0px;
font-size: 16px;
}
input[type='text'] {
width: auto;
margin: 3px 0px 3px 0px;
padding: 0px 10px 0px 10px;
font-family: arial;
color: #000000;
background-color: #FFFFFF;
border: 1px solid #000000;
border-radius: 12px;
}
input[type='button'] {
width: auto;
margin: 3px 0px 3px 0px;
padding: 0px 10px 0px 10px;
font-family: arial;
font-weight: bold;
color: #000000;
border: 1px solid #000000;
background-color: #FFFFFF;
cursor: pointer;
border-radius: 5px;
background: #b93207;
color: #fff;
border: #b93207;
}
input[type='button']:hover {
color: #f9f900;
}
input[type='button']:hover {}
input[type='file'] {
width: 92px;
border-radius: 12px;
overflow: hidden;
padding: 0px;
margin: 0px 0px 0px -92px;
-moz-opacity: 0;
opacity: 0;
cursor: pointer;
}
input[type='file']::-webkit-file-upload-button {
cursor: pointer;
}
div {
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
table {
border-collapse: collapse;
}
table,
td {
padding: 0px;
}
.buttonz {
width: 100%;
display: inline-block;
}
#menu {
position: absolute;
z-index: -1;
left: 0px;
top: 0px;
width: 0px;
height: 0%;
margin: 0px;
overflow: auto;
background-color: #E1E1D2;
border-right: 1px solid #000000;
}
div.navcat {
padding: 10px 0px 5px 12px;
font-size: 18px;
font-weight: bold;
font-style: italic;
}
div.navdiv {
height: 2px;
padding: 0px;
margin: 18px 10px 13px 10px;
background-color: #000000;
}
a.nav {
display: inline-block;
padding: 0px;
margin: 10px 0px 10px 10px;
text-decoration: underline;
color: #000000;
}
#toolpadding {
padding: 10px 10px 10px 10px;
}
#tool {
width: 1100px;
margin: 0px;
padding: 0px;
background-color: #fff;
margin: 0 auto;
}
<div id="tool">
<div id="toolpadding">
<div id="topdiv">
<div class="se-for">Search lines for:</div>
<div id="inputfields" style="padding-top:4px;">
<textarea type="text" id="addfield0" class="wordd">Three</textarea>
</div>
<div class="buttonz">
<input type="button" value="Keep Lines Containing" onClick="if(document.getElementById('addfield0').value!='') {removelines('notcontaining');}" />
<input type="checkbox" id="case_sen" />Case sensitive.
</div>
</div>
<div id="middiv" style="height:120px;">
<textarea id="input_output" class="contentt" wrap="off">
One One One One One One One One One One One One One One One
Three Three Three Three Three Three Three Three Three Three
Two Two Two Two Two Two Two Two Two Two Two Two Two Two Two
Two Two Two Two Two Two Two Two Two Two Two Two Two Two Two
Three Three Three Three Three Three Three Three Three Three
Three Three Three Three Three Three Three Three Three Three
Four Four Four Four Four Four Four Four Four Four Four Four
Five Five Five Five Five Five Five Five Five Five Five Five
Three Three Three Three Three Three Three Three Three Three
Five Five Five Five Five Five Five Five Five Five Five Five
Three Three Three Three Three Three Three Three Three Three
</textarea>
</div>
<div id="btmdiv">
<textarea id="removed_box" rows="4" style="display:none; width:100%; margin-top:10px;" wrap="off">
Removed Line Box - Removed/extracted lines will display here.</textarea>
</div>
</div>
</div>
/**
* Created by Malal91 and Haziel
* Select multiple email by jquery.email_multiple
* **/
(function($){
$.fn.email_multiple = function(options) {
let defaults = {
reset: false,
fill: false,
data: null
};
let settings = $.extend(defaults, options);
let email = "";
return this.each(function()
{
$(this).after(
"<div class=\"all-mail\"></div>\n" +
"<input type=\"text\" name=\"email\" class=\"enter-mail-id\" placeholder=\"Enter Email ...\" />"
);
let $orig = $(this);
let $element = $('.enter-mail-id');
$element.keydown(function (e) {
$element.css('border', '');
if (e.keyCode === 13 || e.keyCode === 32) {
let getValue = $element.val();
if (/^[a-z0-9._-]+#[a-z0-9._-]+\.[a-z]{2,6}$/.test(getValue)){
$('.all-mail').append('<span class="email-ids">' + getValue + '<span class="cancel-email">x</span></span>');
$(".cancel-email").attr("id", getValue);
$element.val('');
email += getValue + ','
} else {
$element.css('border', '1px solid red')
}
}
$orig.val(email.slice(0, -1))
});
$(document).on('click','.cancel-email',function(){
//crucial part
var valueToDelete = $(this).attr('id');
//alert(valueToDelete);
var current_value = $('#employee_email').val();
var new_value = current_value.replace(valueToDelete, '');
$('#employee_email').val(new_value);
$(this).parent().remove();
});
if(settings.data){
$.each(settings.data, function (x, y) {
if (/^[a-z0-9._-]+#[a-z0-9._-]+\.[a-z]{2,6}$/.test(y)){
$('.all-mail').append('<span class="email-ids">' + y + '<span class="cancel-email">x</span></span>');
$element.val('');
email += y + ','
} else {
$element.css('border', '1px solid red')
}
})
$orig.val(email.slice(0, -1))
}
if(settings.reset){
$('.email-ids').remove()
}
return $orig.show()
//return $orig.hide()
});
};
})(jQuery);
span.email-ids {
float: left;
/* padding: 4px; */
border: 1px solid #ccc;
margin-right: 5px;
margin-bottom: 5px;
background: #f5f5f5;
padding: 3px 10px;
border-radius: 5px;
}
span.cancel-email {
border: 1px solid #ccc;
width: 18px;
display: block;
float: right;
text-align: center;
margin-left: 20px;
border-radius: 49%;
height: 18px;
line-height: 15px;
margin-top: 1px; cursor: pointer;
}
.email-id-row {
border: 1px solid #ccc;
}
.email-id-row input {
border: 0; outline:0;
}
span.to-input {
display: block;
float: left;
padding-right: 11px;
}
.email-id-row {
padding-top: 6px;
padding-bottom: 7px;
/*margin-top: 23px;*/
}
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<input class="input_link" id="employee_email" type="text" placeholder="test field - see result" />
<script type="text/javascript">
//let user insert multiple emails
$(document).ready(function($){
let data = []
$("#employee_email").email_multiple({
data: data
})
});
</script>
</body>
</html>
I am currently facing some issues removing a certain part of a string of multiple emails. My current approach is to replace the value of the deleted email with an empty value; thus, I assigned each created delete button a unique id value in order to delete only this specific value. However, this does only work for the last inserted email.
The code is mainly from a js plugin which makes it easier to insert multiple emails in an input field (credits: multiple email plugin Created by Malal91 and Haziel).
i want to no repeat the tags that i will writing in field i try but the console appears the span value repeat like this in image how can i fix that to not repeat the tags. i used JQuery
s://i.stack.imgur.com/dIVP1.jpg
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<input class="add-tags" type="text" placeholder="Type Your Tags">
<div class="tags"></div>
</div>
<script>
$('.add-tags').on('keyup', function(e) {
var tagsKey = e.keyCode || e.which;
if (tagsKey === 188) {
var thisValue = $(this).val().slice(0, -1); //remove last letter
$('.tags').append('<span class="tags-span"><i class="fa fa-times"></i>' + thisValue + '</span>');
var spanvalue = $('.tags-span').text();
console.log(spanvalue);
if (thisValue === spanvalue) {
console.log('good');
} else {
console.log('bad');
}
$(this).val('');
}
$('.tags').on('click', '.tags-span i', function() {
$(this).parent('.tags-span').remove();
});
});
</script>
Voila!
I have a gift for you, but first I would like to point out, that next time you should invest more time into the preparation of your question. Don't cry, don't beg, start from doing your homework first and get as much information as you can. Stackoverflow is not a place were people will do you job for you.
Right now, one can only guess what you are really trying to achieve.
After some harsh treatment let's go to the good parts:
In the following example (https://jsfiddle.net/mkbctrlll/xb6ar2n1/95/)
I have made a simple input that creates a tag on a SPACE key hit. Each tag could be easily removable if X is clicked.
HTML:
<form class="wrapper">
<label for="test">
<span id="tags">
Tags:
</span>
<input id="test" type="text" >
</label>
</form>
JS:
var tagsCollection = []
document.body.onkeyup = function(e){
if(e.keyCode == 32){
var content = getContent('#test')
console.log(tagsCollection.indexOf(content))
if(tagsCollection.indexOf(content) === -1) {
console.log('Spacebar hit! Creating tag')
createTag(content)
tagsCollection.push(content)
console.log(tagsCollection)
} else {
console.log('We already have this one sir!')
displayError('Whoops! Looks like this tag already exists... )')
}
}
}
$('.wrapper').on('click', function(event) {
$(event.target).closest('.tag').remove()
})
function displayError(content) {
var error = document.createElement('p')
error.classList.add('error')
error.innerHTML = content
document.querySelector('.wrapper').append(error)
}
function getContent(target) {
var value = $(target).val().replace(/\W/g, '')
$(target).val("")
return value
}
function createTag(content) {
var $tags = $('#tags')
var tag = document.createElement('span')
var closeIcon = '×'
var iconHTML = document.createElement('span')
iconHTML.classList.add('remove')
iconHTML.innerHTML = closeIcon
tag.classList.add('tag')
tag.append(iconHTML)
tag.append(content)
$tags.append(tag)
}
function removeTag(target) {
target.remove()
}
CSS:
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
.wrapper {
background: #fff;
border-radius: 4px;
padding: 20px;
font-size: 25px;
transition: all 0.2s;
margin: 0 auto;
width: 300px;
}
#tags {
display: block;
margin-bottom: 10px;
font-size: 14px;
}
#test {
display: block;
width: 100%;
}
.tag {
border-radius: 16px;
background-color: #ccc;
color: white;
font-size: 12px;
padding: 4px 6px 4px 16px;
position: relative;
}
.tag:not(:last-child) {
margin-right: 4px;
}
.remove {
font-weight: 600;
position: absolute;
top: 50%;
left: 6px;
cursor: pointer;
transform: translateY(-50%);
}
.remove:hover {
color: red;
}
It is just a quick and dirty example, not a production lvl code.
I'm appending a Search Results to the google places javascript api autocomplete.
So far I'm doing this:
var autocomplete;
function initialize() {
var myLatlng = new google.maps.LatLng(40.738793, -73.991402);
autocomplete = new google.maps.places.Autocomplete(document.getElementById('autocomplete'));
}
later on I have this:
$('.pac-container').append( '<div class="j-search pac-item-refresh">Search Results</div>' );
$(document.body).on('click', '.pac-container .j-search', function(e) {
console.log('click fired');
});
The problem? The click event never fires...
Any idea why? Anything wrong with my code?
It seems that the click-event for .pac-container is cancelled by the Autocomplete-instance. Use mousedown instead.
You can follow the this article.
Implement and Optimize Autocomplete with Google Places API
Specifically Autocompletion using the AutocompleteService:
link: JS Filddle Of AutocompletionService
function debounce(func, wait, immediate) {
let timeout;
return function() {
let context = this,
args = arguments;
let later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
let callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
}
function initAutocomplete() {
let map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 48,
lng: 4
},
zoom: 4,
disableDefaultUI: true
});
// Create the search box and link it to the UI element.
let inputContainer = document.querySelector('autocomplete-input-container');
let autocomplete_results = document.querySelector('.autocomplete-results');
let service = new google.maps.places.AutocompleteService();
let serviceDetails = new google.maps.places.PlacesService(map);
let marker = new google.maps.Marker({
map: map
});
let displaySuggestions = function(predictions, status) {
if (status != google.maps.places.PlacesServiceStatus.OK) {
alert(status);
return;
}
let results_html = [];
predictions.forEach(function(prediction) {
results_html.push(`<li class="autocomplete-item" data-type="place" data-place-id=${prediction.place_id}><span class="autocomplete-icon icon-localities"></span> <span class="autocomplete-text">${prediction.description}</span></li>`);
});
autocomplete_results.innerHTML = results_html.join("");
autocomplete_results.style.display = 'block';
let autocomplete_items = autocomplete_results.querySelectorAll('.autocomplete-item');
for (let autocomplete_item of autocomplete_items) {
autocomplete_item.addEventListener('click', function() {
let prediction = {};
const selected_text = this.querySelector('.autocomplete-text').textContent;
const place_id = this.getAttribute('data-place-id');
let request = {
placeId: place_id,
fields: ['name', 'geometry']
};
serviceDetails.getDetails(request, function(place, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
if (!place.geometry) {
console.log("Returned place contains no geometry");
return;
}
var bounds = new google.maps.LatLngBounds();
marker.setPosition(place.geometry.location);
if (place.geometry.viewport) {
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
map.fitBounds(bounds);
}
autocomplete_input.value = selected_text;
autocomplete_results.style.display = 'none';
});
})
}
};
let autocomplete_input = document.getElementById('my-input-autocomplete');
autocomplete_input.addEventListener('input', debounce(function() {
let value = this.value;
value.replace('"', '\\"').replace(/^\s+|\s+$/g, '');
if (value !== "") {
service.getPlacePredictions({
input: value
}, displaySuggestions);
} else {
autocomplete_results.innerHTML = '';
autocomplete_results.style.display = 'none';
}
}, 150));
}
document.addEventListener("DOMContentLoaded", function(event) {
initAutocomplete();
});
#map {
height: 100%;
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
.autocomplete-input-container {
position: absolute;
z-index: 1;
width: 100%;
}
.autocomplete-input {
text-align: center;
}
#my-input-autocomplete {
box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.16), 0 0 0 1px rgba(0, 0, 0, 0.08);
font-size: 15px;
border-radius: 3px;
border: 0;
margin-top: 10px;
width: 290px;
height: 40px;
text-overflow: ellipsis;
padding: 0 1em;
}
#my-input-autocomplete:focus {
outline: none;
}
.autocomplete-results {
margin: 0 auto;
right: 0;
left: 0;
position: absolute;
display: none;
background-color: white;
width: 320px;
padding: 0;
list-style-type: none;
margin: 0 auto;
border: 1px solid #d2d2d2;
border-top: 0;
box-sizing: border-box;
}
.autocomplete-item {
padding: 5px 5px 5px 35px;
height: 26px;
line-height: 26px;
border-top: 1px solid #d9d9d9;
position: relative;
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
}
.autocomplete-icon {
display: block;
position: absolute;
top: 7px;
bottom: 0;
left: 8px;
width: 20px;
height: 20px;
background-repeat: no-repeat;
background-position: center center;
}
.autocomplete-icon.icon-localities {
background-image: url(https://images.woosmap.com/icons/locality.svg);
}
.autocomplete-item:hover .autocomplete-icon.icon-localities {
background-image: url(https://images.woosmap.com/icons/locality-selected.svg);
}
.autocomplete-item:hover {
background-color: #f2f2f2;
cursor: pointer;
}
.autocomplete-results::after {
content: "";
padding: 1px 1px 1px 0;
height: 18px;
box-sizing: border-box;
text-align: right;
display: block;
background-image: url(https://maps.gstatic.com/mapfiles/api-3/images/powered-by-google-on-white3_hdpi.png);
background-position: right;
background-repeat: no-repeat;
background-size: 120px 14px
}
<div class="autocomplete-input-container">
<div class="autocomplete-input">
<input id="my-input-autocomplete" placeholder="AutocompleteService" autocomplete="off" role="combobox">
</div>
<ul class="autocomplete-results">
</ul>
</div>
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=places&callback"></script>