Can I use XMLHttpRequest to make a search bar? - javascript

Hi there I am working on a search bar I would like the search box to display p, li and h3 elements of various pages using XMLHttpRequest() ? and how?
I am converting all these elements into an array but I don't know how to make sure that the array displays in the search box so that the user can click and be redirected to the element's page.
I am trying to learn javascript so please vanilla javascript only.
Thank you for your time, hope that makes sense.
const search = document.getElementById("myInput");
const list = document.getElementById("list");
const sections = document.querySelectorAll("li, h3, p");
const filter = Array.prototype.filter;
function setlist(group) {
for (const item of group) {
const it = document.createElement("li");
const text = document.createTextNode(item.name);
it.appendChild(text);
list.appendChild(it);
}
if (group.length === 0) {}
}
function clearList() {
while (list.firstChild) {
list.removeChild(list.firstChild);
}
}
function setNoResults() {
const it = document.createElement("li");
it.classList.add("list-group-item");
const text = document.createTextNode("no results found");
it.appendChild(text);
list.appendChild(it);
}
function getRelevancy(value, searchTerm) {
if (value === searchTerm) {
return 2;
} else if (value.startWith(searchTerm)) {
return 1;
} else if (value.includes(searchTerm)) {
return 0;
} else {
return -1;
}
}
search.addEventListener("input", event => {
let value = event.target.value;
if (value && value.length > 0) {
value = value.toLowerCase();
setlist(
sections
.filter(item => {
return item.name.includes(value);
})
.sort((itemA, itemB) => {
return (
getRelevancy(itemB.name, value) - getRelevancy(itemA.name, value)
);
})
);
} else {
clearList();
}
});
<div class="navbar">
<ul class="navSection">
<li class="collection-item">
Speakers</li>
<li class="collection-item">Headphones</li>
<li class="collection-item">Accessories</li>
<li class="collection-item">Earphones</li>
<li class="collection-item">All</li>
</ul>
</div>
<div class="basketSearch">
<div class="searchBar">
<input type="text" name="search" value="" autocomplete="off" id="myInput" placeholder="" />
</div>
<ul class="listGroup" id="list"></ul>

You should have a Database with the data or use an API to fetch some.
The second option is to have a JSON file locally that will contain the data.
let request = new XMLHttpRequest();
request.open('GET', 'URL*', true);
request.onreadystatechange = function() {
if (request.readyState === 4 && request.status === 200) {
let data = JSON.parse(request.responseText)
}
};
request.send(null);
- Example of data -
[
{name: 'something', ...othervalues},
]
OR
['something', 'item1', 'item2', ...]
*URL = The path to a php file, or url to an API.
After that you can use your
search.addEventListener("input", event => {...})
to filter the data array results.
Have in mind that Ajax requests have an asynchronous nature and you have to handle them properly. You might consider using async functions or promises. Otherwise if you fire the input event before the result is set, the data will be undefined.
An other way is to set your search.addEventListener("input", event => {...}) after the ajax request is finished
request.onreadystatechange = function() {
if (request.readyState === 4 && request.status === 200) {
let data = JSON.parse(request.responseText);
search.addEventListener("input", event => {...})
}
};
So you can have direct access to the data variable.
Also an other option for the dropdown menu for the suggestions is HTML Datalists.
Cheers.

Related

when I manually click on an input linked to a dynamic datalist the values display. When I programmatically click, the datalist value don't display

I program an angular application and use a dynamic datalist
<input id="inputCodePostalId" type="text" (keyup)="findPostalCode($event)" placeholder="Code Postal" formControlName="codePostal" list="codePostalId" />
<datalist id="codePostalId">
<option *ngFor="let code of postalCodeList" [value]="code">{{code}}</option>
</datalist>
the datalist is alimented with values coming from a request
findPostalCode(event: any) {
let text = event.target.value;
if (event.which != 16 && text != null && text.length > 2) {
this.postalCodeList = [];
this.produitImmobilierService.getPostalCodes(text).subscribe(
result => {
this.postalCodeList = result;
setTimeout( function () {
var elem = document.getElementById("inputCodePostalId");
elem.click();
}, 500)
}
);
}
}
When I enter 595 for example in the input, the request is made, and afterwards, when I manually click in the input, the datalist values appear, but when I programmatically click as above (see in setTimeout function) the datalist values don't appear
UPDATE
I added a click listener on the input
<input id="inputCodePostalId" type="text" (click)="method1();"................
and
method1() {
console.log('ca passe CLICK');
}
I tried also this
findPostalCode(event: any) {
let text = event.target.value;
if (event.which != 16 && text != null && text.length > 2) {
this.postalCodeList = [];
const event1 = new Event('click');
const element = document.getElementById("inputCodePostalId");
this.produitImmobilierService.getPostalCodes(text).subscribe(
result => {this.postalCodeList = result;
setTimeout( function () {element.dispatchEvent(event1); },
500)});
}
}

How to change part of a string to a different value on API return using JS?

I am using the Chuck Norris joke generator API. I was wondering if it would be possible in this situation to change part of the string returned 'Chuck Norris' to something else. I've tried a few different ideas and I'm really stuck.
E.g instead of 'Chuck Norris built the hospital he was born in.' the API could return 'Dalai Lama built the hospital he was born in.' instead.
document.querySelector('.get-jokes').addEventListener('click', getJokes);
function getJokes(e) {
const number = document.querySelector('input[type="number"]').value;
const xhr = new XMLHttpRequest();
xhr.open('GET', `http://api.icndb.com/jokes/random/${number}`, true);
xhr.onload = function() {
if (this.status === 200) {
const response = JSON.parse(this.responseText);
console.log(response);
let output = '';
if (response.type === 'success') {
response.value.forEach(function(getjoke) {
output += `<li>${getjoke.joke}</li>`;
});
} else {
output += '<li>Something went wrong</li>';
}
document.querySelector('.jokes').innerHTML = output;
}
};
xhr.send();
e.preventDefault();
}
<div class="container">
<h2>Chuck Norris Joke Generator</h2>
<form>
<div>
<label for="number">Number of jokes</label>
<input type="number" id="number">
</div>
<div>
<button class="get-jokes">Get Jokes</button>
</div>
</form>
<ul class="jokes"></ul>
</div>
I believe this could be an answer
function replaceall(thejoke, what, towhat) {
while (thejoke.includes(what) == true) {
thejoke = thejoke.replace(what, towhat);
}
return thejoke
}
thejoke Is the string, And the function takes all of what in thejoke and turns it in to towhat
This Is a program I made using this function.

How to perform calculation with values of dynamic input fields?

I have a little problem with my html form code...
In my code, there are few input fields which are generated dynamically. In every input field generated dynamically, there is some numerical value. i need to do some Mathematical calculation with them.
="PE+ROCE+(2-SG)-(4-DY/2)"
This is a pattern of my calculation. In this, PE, ROCE etc are the IDs of Dynamic Input fields generated.
Using values of dynamic input fields generated, I need to perform above calculation.
This calculation has to be executed when the user would click on "Calculate" Input Button.
Then, the final calculated value from the above will be shown in the Output Tag present in bottom of my form code.
I tried to solve this problem on my own. But unfortunately, failed in this task.
somebody can now please help me to solve this problem.
I will be very grateful...
here is my full code of form..
// define the headings here, so we can access it globally
// in the app
let headings = []
// appending the created HTML string to the DOM
function initInputs(headingList) {
jQuery(".fields").append(createInputsHTML(headingList))
}
// the HTMLT template that is going to be appended
// to the DOM
function createInputsHTML(headingList) {
let html = ''
headingList.forEach(heading => {
if (heading !== 'Company') {
html += `<label for="${heading}">${heading}: </label>`
html += `<input id="${heading}">`
html += '<br>'
}
})
return html
}
// receiving data
// this data arrives later in the app's lifecycle,
// so it's the best to return a Promise object
// that gets resolved (check JS Promise for more information)
function getJSON() {
return new Promise(resolve => {
jQuery.get("https://cors-anywhere.herokuapp.com/www.coasilat.com/wp-content/uploads/2019/06/data-1.txt", function(data) {
resolve(JSON.parse(data))
});
})
}
// processing raw JSON data
function processRawData(data) {
return new Promise(resolve => {
const companyData = []
// creating data array
// handling multiple sheets
Object.values(data).forEach((sheet, index) => {
sheet.forEach((company, i) => {
companyData.push({ ...company
})
// create headings only once
if (index === 0 && i === 0) {
Object.keys(company).forEach(item => {
headings.push(item.trim())
})
}
})
})
resolve(companyData)
})
}
$(async function() {
let lists = [];
function initAutocomplete(list) {
const thisKey = 'Company'
$("#company").autocomplete('option', 'source', function(request, response) {
response(
list.filter(item => {
if (item[thisKey].toLowerCase().includes(request.term.toLowerCase())) {
item.label = item[thisKey]
return item
}
})
)
})
}
$("#company").autocomplete({
minLength: 3,
source: lists,
focus: function(event, ui) {
// the "species" is constant - it shouldn't be modified
$("#company").val(ui.item.Company);
return false;
},
select: function(event, ui) {
// handling n number of fields / columns
headings.forEach(heading => {
$('#' + heading).val(ui.item[heading])
})
return false;
}
});
// starting data download, processing and usage
getJSON()
.then(json => {
return processRawData(json)
})
.then(data => {
// just so we see what data we are using
console.log(data)
// make the processed data accessible globally
lists = data
initAutocomplete(lists)
initInputs(headings)
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" />
<div class="ui-widget">
<form id="frm1">
<label for="company">Company: </label>
<input id="company"><br />
<div class="fields"></div>
<input type="submit" id="calculate" value="Calculate">
<p>Final Amount <output name="amount" for="calculation">0</output></p>
</form>
</div>
Try each loop of inputs
$("#Calculate").click(function(){
var peVal,roceVal,sgVal,dyVal;
jQuery(".fields input").each(function (){
var idHeading=$(this).attr("id");
if(idHeading=="Your ID for PE input"){
peVal=parseInt($(this).val());
}
if(idHeading=="Your ID for ROCE input "){
roceVal=parseInt($(this).val());
}
if(idHeading=="Your ID for SG input"){
sgVal=parseInt($(this).val());
}
if(idHeading=="Your ID for DY input"){
dyVal=parseInt($(this).val());
}
});
var output=peVal+roceVal+(2-sgVal)-(4-dyVal/2);
});

How do I change this Contact Form's Javascript so that IF a key is something else, perform different action?

I have a Contact Form that utilizes Google Scripts. It successfully sends the email and formats it decently to my inbox, but there are 2 problems:
-I need it so that IF var key is equal to 'Action', then do not display it in the email it sends. Because right now, "Action send_message" is getting included in the email and I don't like that.
For this, I have unsuccessfully tried things like:
for (var idx in order) {
var key = order[idx];
//Skip this entry into the email output if it is the Action
if( key === 'Action') {
continue
}
It seems to not react to this code at all.
-I also need it so that if a city is selected, e.g. Alachua, that the email says 'Alachua' instead of 'Florida_Alachua'. But I can't add a NAME to an option since apparently options don't have that property. I also can't do the quick fix of changing the VALUE of the <option> to resolve this step, because of other code I have that conflicts with this route.
Google Scripts Code:
/******************************************************************************
* This tutorial is based on the work of Martin Hawksey twitter.com/mhawksey *
* But has been simplified and cleaned up to make it more beginner friendly *
* All credit still goes to Martin and any issues/complaints/questions to me. *
******************************************************************************/
// if you want to store your email server-side (hidden), uncomment the next line
var TO_ADDRESS = "myemail#email.com";
// spit out all the keys/values from the form in HTML for email
// uses an array of keys if provided or the object to determine field order
function formatMailBody(obj, order) {
var result = "";
if (!order) {
order = Object.keys(obj);
}
// loop over all keys in the ordered form data
for (var idx in order) {
var key = order[idx];
result += "<h4 style='text-transform: capitalize; margin-bottom: 0'>" + key + "</h4><div>" + sanitizeInput(obj[key]) + "</div>";
// for every key, concatenate an `<h4 />`/`<div />` pairing of the key name and its value,
// and append it to the `result` string created at the start.
}
return result; // once the looping is done, `result` will be one long string to put in the email body
}
// sanitize content from the user - trust no one
// ref: https://developers.google.com/apps-script/reference/html/html-output#appendUntrusted(String)
function sanitizeInput(rawInput) {
var placeholder = HtmlService.createHtmlOutput(" ");
placeholder.appendUntrusted(rawInput);
return placeholder.getContent();
}
function doPost(e) {
try {
Logger.log(e); // the Google Script version of console.log see: Class Logger
record_data(e);
// shorter name for form data
var mailData = e.parameters;
// names and order of form elements (if set)
var orderParameter = e.parameters.formDataNameOrder;
var dataOrder;
if (orderParameter) {
dataOrder = JSON.parse(orderParameter);
}
// determine recepient of the email
// if you have your email uncommented above, it uses that `TO_ADDRESS`
// otherwise, it defaults to the email provided by the form's data attribute
var sendEmailTo = (typeof TO_ADDRESS !== "undefined") ? TO_ADDRESS : mailData.formGoogleSendEmail;
// send email if to address is set
if (sendEmailTo) {
MailApp.sendEmail({
to: String(sendEmailTo),
subject: "Contact form submitted",
// replyTo: String(mailData.email), // This is optional and reliant on your form actually collecting a field named `email`
htmlBody: formatMailBody(mailData, dataOrder)
});
}
return ContentService // return json success results
.createTextOutput(
JSON.stringify({"result":"success",
"data": JSON.stringify(e.parameters) }))
.setMimeType(ContentService.MimeType.JSON);
} catch(error) { // if error return this
Logger.log(error);
return ContentService
.createTextOutput(JSON.stringify({"result":"error", "error": error}))
.setMimeType(ContentService.MimeType.JSON);
}
}
/**
* record_data inserts the data received from the html form submission
* e is the data received from the POST
*/
function record_data(e) {
var lock = LockService.getDocumentLock();
lock.waitLock(30000); // hold off up to 30 sec to avoid concurrent writing
try {
Logger.log(JSON.stringify(e)); // log the POST data in case we need to debug it
// select the 'responses' sheet by default
var doc = SpreadsheetApp.getActiveSpreadsheet();
var sheetName = e.parameters.formGoogleSheetName || "responses";
var sheet = doc.getSheetByName(sheetName);
var oldHeader = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
var newHeader = oldHeader.slice();
var fieldsFromForm = getDataColumns(e.parameters);
var row = [new Date()]; // first element in the row should always be a timestamp
// loop through the header columns
for (var i = 1; i < oldHeader.length; i++) { // start at 1 to avoid Timestamp column
var field = oldHeader[i];
var output = getFieldFromData(field, e.parameters);
row.push(output);
// mark as stored by removing from form fields
var formIndex = fieldsFromForm.indexOf(field);
if (formIndex > -1) {
fieldsFromForm.splice(formIndex, 1);
}
}
// set any new fields in our form
for (var i = 0; i < fieldsFromForm.length; i++) {
var field = fieldsFromForm[i];
var output = getFieldFromData(field, e.parameters);
row.push(output);
newHeader.push(field);
}
// more efficient to set values as [][] array than individually
var nextRow = sheet.getLastRow() + 1; // get next row
sheet.getRange(nextRow, 1, 1, row.length).setValues([row]);
// update header row with any new data
if (newHeader.length > oldHeader.length) {
sheet.getRange(1, 1, 1, newHeader.length).setValues([newHeader]);
}
}
catch(error) {
Logger.log(error);
}
finally {
lock.releaseLock();
return;
}
}
function getDataColumns(data) {
return Object.keys(data).filter(function(column) {
return !(column === 'formDataNameOrder' || column === 'formGoogleSheetName' || column === 'formGoogleSendEmail' || column === 'honeypot');
});
}
function getFieldFromData(field, data) {
var values = data[field] || '';
var output = values.join ? values.join(', ') : values;
return output;
}
Contact Form HTML
<section id="contact-form">
<form id="gform"
class="contact-form" method="post"
action="(Google Scripts URL)"
enctype="text/plain">
<p>
<label for="name">Your Name <font face="Arial" color="red">*</font></label>
<input type="text" style="height:35px;" class="heighttext required" name="name" id="name" class="required" title="* Please provide your name">
</p>
<p>
<label>Your Location <font face="Arial" color="red">*</font></label>
<select name="Location" id="column_select" style="height:35px;" class="required" title=" * Please provide your location">
<option selected value="col00">-- State --</option>
<option value="Alabama">Alabama</option>
<option value="California">California</option>
<option value="Florida">Florida</option>
</select>
<select name="City" id="layout_select" style="height:35px;">
<option disabled selected value="Florida">-- City --</option>
<option name="Alachua" value="Florida_Alachua">Alachua</option>
<option name="Alford" value="Florida_Alford">Alford</option>
</select>
</p>
<p>
<input type="submit" value="Send Message" id="submit" class="pp-btn special">
<img src="images/ajax-loader.gif" id="contact-loader" alt="Loading...">
<input type="hidden" name="action" value="send_message">
</p>
</form>
</section><!-- #contact-form -->
Form Handler Javascript
(function() {
function validEmail(email) { // see:
var re = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
return re.test(email);
}
function validateHuman(honeypot) {
if (honeypot) { //if hidden form filled up
console.log("Robot Detected!");
return true;
} else {
console.log("Welcome Human!");
}
}
// get all data in form and return object
function getFormData() {
var form = document.getElementById("gform");
var elements = form.elements;
var fields = Object.keys(elements).filter(function(k) {
return (elements[k].name !== "honeypot");
}).map(function(k) {
if(elements[k].name !== undefined) {
return elements[k].name;
// special case for Edge's html collection
}else if(elements[k].length > 0){
return elements[k].item(0).name;
}
}).filter(function(item, pos, self) {
return self.indexOf(item) == pos && item;
});
var formData = {};
fields.forEach(function(name){
var element = elements[name];
// singular form elements just have one value
formData[name] = element.value;
// when our element has multiple items, get their values
if (element.length) {
var data = [];
for (var i = 0; i < element.length; i++) {
var item = element.item(i);
if (item.checked || item.selected) {
data.push(item.value);
}
}
formData[name] = data.join(', ');
}
});
// add form-specific values into the data
formData.formDataNameOrder = JSON.stringify(fields);
formData.formGoogleSheetName = form.dataset.sheet || "responses"; // default sheet name
formData.formGoogleSendEmail = form.dataset.email || ""; // no email by default
console.log(formData);
return formData;
}
function handleFormSubmit(event) { // handles form submit without any jquery
event.preventDefault(); // we are submitting via xhr below
var data = getFormData(); // get the values submitted in the form
/* OPTION: Remove this comment to enable SPAM prevention, see README.md
if (validateHuman(data.honeypot)) { //if form is filled, form will not be submitted
return false;
}
*/
if( data.email && !validEmail(data.email) ) { // if email is not valid show error
var invalidEmail = document.getElementById("email-invalid");
if (invalidEmail) {
invalidEmail.style.display = "block";
return false;
}
} else {
disableAllButtons(event.target);
var url = event.target.action; //
var xhr = new XMLHttpRequest();
xhr.open('POST', url);
// xhr.withCredentials = true;
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
console.log( xhr.status, xhr.statusText )
console.log(xhr.responseText);
//document.getElementById("gform").style.display = "none"; // hide form
/*
var thankYouMessage = document.getElementById("thankyou_message");
if (thankYouMessage) {
thankYouMessage.style.display = "block";
}
*/
return;
};
// url encode form data for sending as post data
var encoded = Object.keys(data).map(function(k) {
return encodeURIComponent(k) + "=" + encodeURIComponent(data[k])
}).join('&')
xhr.send(encoded);
}
}
function loaded() {
console.log("Contact form submission handler loaded successfully.");
// bind to the submit event of our form
var form = document.getElementById("gform");
form.addEventListener("submit", handleFormSubmit, false);
};
document.addEventListener("DOMContentLoaded", loaded, false);
function disableAllButtons(form) {
var buttons = form.querySelectorAll("button");
for (var i = 0; i < buttons.length; i++) {
buttons[i].disabled = true;
}
}
})();
finally, this is the extra code that would break if I simply tried changing the value of option to, e.g., 'Alachua' instead of 'Flordia_Alachua'. https://jsfiddle.net/hmatt843/504dgmqy/19/
Thanks for any and all help.
Try console.log(key) before if( key === 'Action'). I think you'll find that key never equals 'Action', exactly. Looks like you'll need if( key === 'action'), instead.
If you wish to remove part of string value, try the replace method: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
It also looks like you're trying to work with elements[k].name when you mean to be working with elements[k].value.
I believe your code should look something like...
function(k) {
if(elements[k].value !== undefined) {
return elements[k].value.replace('Florida_', '');
// special case for Edge's html collection
} else if(elements[k].length > 0){
return elements[k].item(0).value.replace('Florida_', '');
}
}
... or something to that effect.
In the future, you may want to make it easier for folks trying to help you by posting only the portions of code your having trouble with, and breaking your questions into different posts. A lot to sift through up there.
Hope this helped.
The split() method splits a String object into an array of strings by separating the string into substrings, using a specified separator string to determine where to make each split.
Var splitValue = elements[k].item(0).value.split("");
splitValue[1] will give you a string of characters after the delimeter () in this case.

How to list autocomplete suggestions as text instead of links

I got this code from a tutorial that I am following for Elasticsearch and AngularJS.
Trying to figure out how to have the autocomplete function form a list of sugggestions in a dropdown as user input is typed instead of displaying links as suggestions.
Here is the html markup:
<ul class="suggestions" ng-show="showAutocomplete">
<li ng-repeat="suggestion in autocomplete.suggestions" ng-show="suggestion.options.length > 0">
<small>Search for —</small> {{suggestion.options[0].text}}
<li ng-repeat="result in autocomplete.results">
{{result._source.title}}
</li>
Here is the js:
//Autocomplete
$scope.autocomplete = {
suggestions: []
};
$scope.showAutocomplete = false;
$scope.evaluateTerms = function(event) {
var inputTerms = $scope.searchTerms ? $scope.searchTerms.toLowerCase() : null;
if (event.keycode === 13) {
return;
}
if (inputTerms && inputTerms.length > 3) {
getSuggestions(inputTerms);
}
else if (!inputTerms) {
$scope.autocomplete = {};
$scope.showAutocomplete = false;
}
};
$scope.searchForSuggestion = function() {
$scope.searchTerms = $scope.autocomplete.suggestions[0].options[0].text;
$scope.search();
$scope.showAutocomplete = false;
};
var getSuggestions = function(query) {
searchService.getSuggestions(query).then(function(es_return) {
var suggestions = es_return.suggest.phraseSuggestion;
var results = es_return.hits.hits;
if (suggestions.length > 0) {
$scope.autocomplete.suggestions = suggestions;
}
else {
$scope.autocomplete.suggestions = [];
}
if (suggestions.length > 0) {
$scope.showAutocomplete = true;
}
else {
$scope.showAutocomplete = false;
}
});
};
The first list item in the html markup gives 1 suggestion (in the form of a link) and the second list item gives a list of links as suggestions. I like the list idea of multiple suggestions, but just want text phrases instead of links that the user can select. Any ideas?
Something like this should work, but I don't' have you object structure so I had to guess in a few places.
<select class="" style="font-size: 12px"
ng-options="suggestion.options[0].text as suggestion for suggestion in autocomplete.suggestions"
ng-change="searchForSuggestion()"
ng-show="suggestion.options.length > 0">
</select>

Categories