I have a form with 2 inputs, where the 1st input has a datalist attribute.
<div class="col-xs-4">
<input name="description" type="text" id="ajax" list="json-datalist">
<datalist id="json-datalist"></datalist>
</div>
<div class="col-xs-2">
<input type="text" name="product" />
</div>
the JSON file has this format
[ {
"product":"1235",
"description":"description 1"
},
{
"product":"1325",
"description":"description 2"
},
...
]
What I want is when the user selects one of the description, then the product to be added in the 2nd input..
here is the code for the javascript where loads the JSON file to the form
var dataList = document.getElementById('json-datalist');
var input = document.getElementById('ajax');
var request = new XMLHttpRequest();
request.onreadystatechange = function(response) {
if (request.readyState === 4) {
if (request.status === 200) {
// Parse the JSON
var jsonOptions = JSON.parse(request.responseText);
// Loop over the JSON array.
jsonOptions.forEach(function(item) {
// Create a new <option> element.
var option = document.createElement('option');
// Set the value using the item in the JSON array.
option.value = item.description;
//<--
// Add the <option> element to the <datalist>.
dataList.appendChild(option);
});
// Update the placeholder text.
input.placeholder = "e.g. datalist";
} else {
// An error occured :(
input.placeholder = "Couldn't load datalist options :(";
}
}
};
// Update the placeholder text.
input.placeholder = "Loading options...";
// Set up and make the request.
request.open('GET', 'myfile.json', true);
request.send();
How can I add the item.product as a value to the second input, when the item.description is selected?
Set product in the data attribute of datalist like following.
option.value = item.description; //after this line
option.setAttribute('data-product', item.product);
And in description change event set product to second input like following using jquery.
$('#ajax').change(function() {
var description = $(this).val();
var product = $('#json-datalist > option[value="' + description + '"]').data('product');
$('input[name=product]').val(product);
});
Full JS code given below. Hope this helps.
var dataList = document.getElementById('json-datalist');
var input = document.getElementById('ajax');
var request = new XMLHttpRequest();
request.onreadystatechange = function (response) {
if (request.readyState === 4) {
if (request.status === 200) {
// Parse the JSON
var jsonOptions = JSON.parse(request.responseText);
// Loop over the JSON array.
jsonOptions.forEach(function (item) {
// Create a new <option> element.
var option = document.createElement('option');
// Set the value using the item in the JSON array.
option.value = item.description;
option.setAttribute('data-product', item.product);
//<--
// Add the <option> element to the <datalist>.
dataList.appendChild(option);
});
// Update the placeholder text.
input.placeholder = "e.g. datalist";
} else {
// An error occured :(
input.placeholder = "Couldn't load datalist options :(";
}
}
};
// Update the placeholder text.
input.placeholder = "Loading options...";
// Set up and make the request.
request.open('GET', 'myfile.json', true);
request.send();
$(function() {
$('#ajax').change(function() {
var description = $(this).val();
var product = $('#json-datalist > option[value="' + description + '"]').data('product');
$('input[name=product]').val(product);
});
});
You can create your <option> element with some other attribute that indicates the product, and then use that attribut to copy it into the second input.
request.onreadystatechange = function(response) {
if (request.readyState === 4) {
if (request.status === 200) {
// Parse the JSON
var jsonOptions = JSON.parse(request.responseText);
// Loop over the JSON array.
jsonOptions.forEach(function(item) {
// Create a new <option> element.
var option = document.createElement('option');
// Set the value using the item in the JSON array.
option.value = item.description;
$(option).attr('data-product',item.product);//THIS IS THE NEW LINE
//<--
// Add the <option> element to the <datalist>.
dataList.appendChild(option);
});
// Update the placeholder text.
input.placeholder = "e.g. datalist";
} else {
// An error occured :(
input.placeholder = "Couldn't load datalist options :(";
}
}
};
And then, for copying it, if you are using JQuery:
$('input#ajax').change(function(){
$('input[name="product"]').val($('#json-dataList').find('option:selected').attr('data-product'));
});
Related
I am very new to JS and I have a problem to create a searchable movie reviewer html page, it is very basic, I just want to know how to have the input box search the NYT API for the movie I am looking for, I wont have a problem putting the elements onto the page, I just want to know how to search properly. I expect I need a function that when the search button is clicked it requests from the site all movies with the words provided.
<div id="search">
<input type="text" id = "search">
<button onclick="search()">Search</button>
</div>
<textarea id="APIoutput" cols="90" rows="50"></textarea>
const ISFINISHED = 4;
const ISOK = 200;
var searchedMovie = document.getElementById("search").value;
function getJSONSync(url){
var response = "";
var xmlHttp = new XMLHttpRequest();
if(xmlHttp !== null){
xmlHttp.open("GET", url, false);
xmlHttp.send(null);
response = xmlHttp.responseText;
}
return response;
}
function getJSONAsync(url, callback) {
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState === ISFINISHED && request.status === ISOK) {
callback(this);
}
};
request.open("GET", url);
request.send();
}
function search(searchedMovie){
var my_api_url = "https://api.nytimes.com/svc/movies/v2/reviews/search.json?query=" + searchedMovie + "&api-key=" + API;
return my_api_url;
}
function handleAPIresponse(response) {
var textArea = document.getElementById("APIoutput");
textArea.value = response.responseText;
}
getJSONAsync(my_api_url, handleAPIresponse);
ERRORS: Uncaught ReferenceError: my_api_url is not defined
Expected Results: (UNFORMATTED JSON THAT LOOKS LIKE THIS:)
{"status":"OK","copyright":"Copyright (c) 2021 The New York Times
Company. All Rights
Reserved.","has_more":false,"num_results":10,"results":[{"display_title":"The
Black Godfather","mpaa_rating":"TV-MA","critics_pick":0,"byline":"BEN
KENIGSBERG","headline":"‘The Black Godfather’ Review: The Music
Executive Who Made It All Happen"
On submit, I want to send form data to json. I want to use json so I can send the data to Python for processing. I am not using jquery.
I have the following HTML code:
<form id="frm1">
<label for="first">First name: <input type="text" id="first" name="first"></label><br><br>
<label for="last">Last name: <input type="text" id="last" name="last"></label><br>
<input type="submit" value="Submit">
</form>
I attempted to send the data to JSON using the following JS code:
form.addEventListener('submit', sendData)
function sendData(event){
//retreives form input
const first = form.querySelector('input[name="first"]');
const last = form.querySelector('input[name="last"]');
var xhr = new XMLHttpRequest();
var url = "formResults.json";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
console.log(json.first+ ", " + json.last);
}
};
var data = JSON.stringify({first, last});
xhr.send(data);
}
I am running the code in a local server and am seeing no output to the json file or any error code.
How do I get my form data to json?
Novice coder
This really is quite an open question. You have provided no details on the model in which the data needs to be provided as. I'm going to assume you need an object similar to the below.
{
first: 'John',
last: 'Smith'
}
If this is the case, you could use the below code.
var serializeForm = function (form) {
// Setup our serialized data
var serialized = {};
// Loop through each field in the form
for (var i = 0; i < form.elements.length; i++) {
var field = form.elements[i];
// Don't serialize fields without a name, submits, buttons, file and reset inputs, and disabled fields
if (!field.name || field.disabled || field.type === 'file' || field.type === 'reset' || field.type === 'submit' || field.type === 'button') continue;
// If a multi-select, get all selections
if (field.type === 'select-multiple') {
for (var n = 0; n < field.options.length; n++) {
if (!field.options[n].selected) continue;
serialized[field.name] = field.options[n].value
}
}
// Convert field data to a query string
else if ((field.type !== 'checkbox' && field.type !== 'radio') || field.checked) {
serialized[field.name] = field.value
}
}
return serialized;
};
Then you could use your code ...
form.addEventListener('submit', sendData)
function sendData(event){
//retreives form input
const formData = serializeForm(form);
var xhr = new XMLHttpRequest();
var url = "YOUR_ENDPOINT_NEEDS_TO_GO_HERE";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
console.log(json);
}
};
var data = JSON.stringify(formData);
xhr.send(data);
}
You can see the above using the codepen linked here. In the example, the object is created immediately, so right-click anywhere in the preview window, view console and you'll see the output of the serializeForm method.
Credit goes to: https://gomakethings.com/how-to-serialize-form-data-with-vanilla-js/ where I got the initial code from and modified it to your (assumed) needs.
i'm trying to make auto complete with pure javascript.
Scenario is when type to input some letters it will search movies from omdbapi.
I make it like that:
i have input which users can search movies, i have get data from input value:
<input type="text" class="form-control" id="searchMovie" value="">
and here i get movies and make html markup with javascript for show these results in html:
var searchInput = document.getElementById("searchMovie");
// get movie
searchInput.onkeydown = function() {
var searchData = document.getElementById("searchMovie").value;
if (searchData.length >= 3 ) {
var request = new XMLHttpRequest();
request.open('GET', 'http://www.omdbapi.com/?s=' + searchData + '&apikey=000000', true);
request.onload = function () {
// Begin accessing JSON data here
var data = JSON.parse(this.response);
const wrapper = document.createElement('div');
app.appendChild(wrapper);
var results = data;
if (request.status >= 200 && request.status < 400) {
console.log(data);
Object.keys(data.Search).map(function(key, index) {
console.log(data.Search[index].Title);
const searchResultsContainer = document.createElement('div');
searchResultsContainer.setAttribute('class', 'row');
const h1 = document.createElement('h1');
h1.textContent = data.Search[index].Title;
wrapper.appendChild(searchResultsContainer);
searchResultsContainer.appendChild(h1);
console.log(searchResultsContainer);
});
} else {
console.log('error');
}
};
request.send();
}
};
everything work well but problem is:
when i try to delete keyword which i wrote and write new one results not disappear from html, i want change
You need to capture the change in the text input. Adding your code to a function and binding the input to oninput function. When there is a change in the value of the input it will rerun the api call. Furthermore, you need to clear out the old result.
<input type="text" class="form-control" id="searchMovie" value="" oninput"apiCall()">
<script>
function apiCall(){
var searchInput = document.getElementById("searchMovie");
// get movie
searchInput.onkeydown = function() {
var searchData = document.getElementById("searchMovie").value;
if (searchData.length >= 3 ) {
while (document.getElementsByClassName('autoComplete')[0]) {
document.getElementsByClassName('autoComplete')[0].remove();
}
var request = new XMLHttpRequest();
request.open('GET', 'http://www.omdbapi.com/?s=' + searchData + '&apikey=000000', true);
request.onload = function () {
// Begin accessing JSON data here
var data = JSON.parse(this.response);
var wrapper = document.createElement('div');
wrapper.className = "autoComplete";
app.appendChild(wrapper);
var results = data;
if (request.status >= 200 && request.status < 400) {
console.log(data);
Object.keys(data.Search).map(function(key, index) {
console.log(data.Search[index].Title);
const searchResultsContainer = document.createElement('div');
searchResultsContainer.setAttribute('class', 'row');
const h1 = document.createElement('h1');
h1.textContent = data.Search[index].Title;
wrapper.appendChild(searchResultsContainer);
searchResultsContainer.appendChild(h1);
console.log(searchResultsContainer);
});
} else {
console.log('error');
}
};
request.send();
}
}
</script>
That should remove the wrapper element you added and its children and populate a new one with new data. I can't really test this to make sure it works as I can not see the rest of your code. But it should work. if not I can help you to figure out any errors.
Also, I would consider making wrapper just a hidden div that you can easily clear and unhide when needed. It would be much easier and you wouldn't need to add and remove so many elements. just wrapper.innerHTML = ""; then wrapper.innerHTML = newRowSet; and done
Instead of setting h1.textContent = data.Search[index].Title; update this to h1.innerHTML = data.Search[key].Title;
I want to create a small web application that includes a function to search movies in Javascript. I want to make that when I search a movie's name, the function completes the rest of word. But I couldn't make it.
For example:
I wrote "bat" and function completes the "man". It is like google search. I wrote "stack" and google completes "overflow" in a dropdown list.
So here is my code in script:
var dataList = document.getElementById('json-datalist');
var input = document.getElementById('ajax');
var request = new XMLHttpRequest();
request.onreadystatechange = function(response) {
if (request.readyState === 4) {
var jsonOptions = JSON.parse(request.responseText);
jsonOptions.forEach(function(item) {
var option = document.createElement('option');
option.value = item;
dataList.appendChild(option);
});
else {
input.placeholder = "Couldn't load datalist options ";
}
}
};
request.open('GET', 'url', true);
request.send();
HTML code:
<form>
<p> Movie name: </p>
<input type="text" id="ajax" list="json-datalist" placeholder="e.g. Spider-Man">
<datalist id="json-datalist"></datalist>
I have verified the above code is working correctly. Now it could be a problem with how you are sending the data from the server.
The problem could be at below line.
option.value = item;
Check your json object, how you are sending data back. For example if there is a properties in object then you should use it as below;
option.value = item.value; => name of element
i have some problrm creating the radio buttons dynamically. in my problem i am requesting data from server in json formate than i check if it contains options i have to create the radio buttons otherwise simply creates the txt area of field to submit the answer. than again i parse it in json formate and send to the server and if my question is write i get new url for next question and so on...
my question is how can i create the radio buttons and read the data from it and than parse that data like {"answer": "something"}.my code is bellow:
enter code herefunction loadDoc(url) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
var data = JSON.parse(this.responseText);
document.getElementById("my_test").innerHTML = data.question;
// Send the answer to next URL
if(data.alternatives !== null){
createRadioElement(div,);
}
var answerJSON = JSON.stringify({"answer":"2"});
sendAnswer(data.nextURL, answerJSON)
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
function sendAnswer(url, data) {
xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var data = JSON.parse(this.responseText);
console.log(this.responseText);
loadDoc(data.nextURL);
}
}
// var data = JSON.stringify({"email":"hey#mail.com","password":"101010"});
xhr.send(data);
}
function createRadioElement(name, checked) {
var radioHtml = '<input type = "radio" name="' + name + '"';
if ( checked ) {
radioHtml += ' checked="checked"';
}
radioHtml += '/>';
var radioFragment = document.createElement('div');
radioFragment.innerHTML = radioHtml;
return radioFragment.firstChild;
}
I'm only guessing since you have some things in your posted code that won't even run, but createRadioElement returns a detached node which you never actually inject into your document.
E.g.,
document.body.appendChild(createRadioElement());