Javascript delete function from a select - javascript

I created an API with Node.js express and mongodb, working perfectly fine.
I have a delete function that works fine as well.
I have an empty HTML select, and I generate the different options by a performing a get request that create all options that I have in my mongodb database.
I would like to delete the selected option in my select but I'm struggling to find a way to get the id of the specific select option.
HTML
<select id="content-dropdown">
</select>
JS :
function showGames(url){
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (this.readyState == XMLHttpRequest.DONE && this.status == 200) {
var response = JSON.parse(this.responseText);
let i = 0;
for(i in response){
dropdown.innerHTML += '<option value="'+response[i].title+'" id="'+response[i]._id+'" class="game">'+response[i].title+'</option>';
}
}
};
request.open("GET", url);
request.send();
}
I managed to get all the id but when I use the delete function it delete the last option in the select.
I tried onchange / onclick event on the select but didn't manage to get it working.

Just set the identifier as the option value: value="'response[i]._id'" then listen to the onchange event of the select element and retrieve the current value with event.target.value in order to call the backend.

Related

Dynamically filling drop downs on each row of table

I have a table with n number of rows depending on results. There is a drop down on the top of the page. Depending on the selection of that drop down I want to dynamically fill a column on each row with a drop down of its own, based off of an xhttp.response.
This is what I have so far:
function getJobs(taskID){
var xhttp = new XMLHttpRequest();
var url = "dynamicdd.php";
var data = new FormData();
data.append('taskID', taskID);
xhttp.open('POST', url, true);
xhttp.send(data);
$('#cTable tr').each(function(){
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("testSelect").innerHTML = xhttp.responseText;
}
}
});
}
I'm able to change the first row successfully, but subsequent rows don't. I've tried $(this).find(select:eq(0)).html() in replace of the document.getElementById() but no luck. I feel like I'm close but lack expertise in jquery/javascript. Thanks for your help.
You are re-assinging onreadystatechange function for each table row which is wrong,
First assing the function for what it must do,
then send the request
then wait for the response ready
then seek the element you want and replace element html with response text as below,
function getJobs(taskID){
var xhttp = new XMLHttpRequest();
var url = "dynamicdd.php";
var data = new FormData();
data.append('taskID', taskID);
xhttp.open('POST', url, true);
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
$('#cTable tr').each(function(index, element){
$(element).find('#testSelect').html(xhttp.responseText);
}
}
});
xhttp.send(data);
}

Dynamically Populating Dropdown from xhttp.open("Get"); response

I have a local text file that I am trying to populate a select dropdown with that data. I have installed IIS to get past the local restrictions and have gotten past CORS. I have used the xhttp method to retrieve the text file data from the file located on the IIS server. I am able to display it in a div as you can see from the below code. I am trying to get this data into a dropdown that I can easily get a value from. For example, if the user selects "Part1" I get an integer value from like 1 as I would from any other dropdown that I specifically declared. I would prefer a javascript solution if possible as that is what the code I have been using for the most part.
I have looked at Google for solutions with nothing really matching.
<body onload="pList();">
<div id="PartList"></div>
<script>
function pList() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("PartList").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "http://127.0.0.1:8080/PartList.txt", true);
xhttp.send();
}
</script>
You have to split your data into an array and then add to the select this way:
<script>
function pList() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var options = this.responseText.split(delimiter);
var select = document.getElementById("PartList");
for (var i = 0; i < options.length; i++) {
var option = document.createElement("option");
option.text = options[i];
option.value = i;
select.add(option);
}
}
};
xhttp.open("GET", "http://127.0.0.1:8080/PartList.txt", true);
xhttp.send();
}
</script>
If you want to clear the select before load use this:
document.getElementById("PartList").innerHTML = "";

Updating html content on submit

I am trying to create a simple webpage containing comments in a table. I can successfully populate it by calling following function on "window.onload" event.
function FillCommentsTable() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var comments = JSON.parse(this.responseText);
var i = 0;
var old_tbody = document.getElementById("comments");
var new_tbody = document.createElement("tbody");
for (i = 0; i < comments.length; i++) {
var row = new_tbody.insertRow(-1);
var id = row.insertCell(0);
var user = row.insertCell(1);
var comment = row.insertCell(2);
var timestamp = row.insertCell(3);
id.innerHTML = comments[i].Id;
user.innerHTML = comments[i].User;
comment.innerHTML = comments[i].Comment;
timestamp.innerHTML = comments[i].Timestamp;
}
old_tbody.parentNode.replaceChild(new_tbody, old_tbody);
}
};
xhttp.open("GET", "API/get_comments.php", true);
xhttp.send();
}
The webpage also have functionality to submit and delete comment with simple form calling the API that manipulates the database storing the comments. The wanted functionality here is that after the submit/delete form has been submitted and called the API the page is reloaded and the table updated. To achieve this I have tried to reload the page on submit with:
<form action="API/delete_comment.php" method="post"
onsubmit="window.location.reload()">
<input type="number" name="id">
<input type="submit" value="Delete">
</form>
but this seems to have no effect except that the expected call to the API is sent. This also only occurs when trying to update the table with a form since just binding a button:
<button onclick="window.location.reload()">Load comments</button>
works as intented and updates the table correctly. Is it not possible to sent both the GET for the webpage and the POST to the API triggered on the same event or what am I missing here?
The point of AJAX is to be able to communicate with the server without having to reload the page...
Submit the form with AJAX instead and then simply call your FillCommentsTable again.
<form action="#" method="post" onsubmit="return deleteComment()">
<input type="number" name="id">
<input type="submit" value="Delete">
</form>
function deleteComment() {
var id = document.querySelector("input[name='id']");
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
FillCommentsTable();
}
};
xhttp.open("POST", "API/delete_comment.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("id="+encodeURIComponent(id.value));
return false;
}
Edit:
The above successfully sends the GET request retrieving the data. In addition to these changes I also added
new_tbody.setAttribute("id","comments");
in the FillCommentsTable function. The mistake of omitting this caused the comments table body to lose its name on the first reload which then caused subsequent calls to FillCommentTable to have no effect since there is no tbody called "comments" ...
Ideally, you should have two data call functions, one to GET data from DB and one to POST data to your DB.
function FillCommentsTable() {
//Function Stuff
}
function AddNewComment() {
//Function Stuff
}
You have a few options on how to process the data:
On POST of a new item, after you receive a status of 200, call your
FillCommentsTable function.
If you have an array storing your comments on the client side, as
you make your POST call and after you receive a status of OK,
array.push(newComment)
You can also take advantage of Promises (Browser support, ECMA2015) to ensure sequencing. I will leave it at a resource link for now as its not exactly within scope of the OP.

Creating Autocomplete Dropdowns with the data comes from database in Javascript

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

Send javascript function parameters onChange

Okay, I've been struggling with this for a few hours now. I'm using ajax to update a div in my site with a php code however, i'm trying to send parameters in the function from the external javascript file to update the correct link(there are multiple drop down boxes)
for example: this is my select box
<script type='text/javascript' src='ajax.js'></script>//include ajax file
<select onchange='MakeRequest(raceupdate);
this.options[this.selectedIndex].value;'> //so no use of a button is needed to auto link to anchor tag
<option>Deathmateched</option>
<?php
dmList()
?>
</select>
Then next my external ajax function MakeRequest().
function MakeRequest(value)
{
var linkInfo = "teleport.php?call=" + value;//create appropriate link depending on function parameters
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
HandleResponse(xmlHttp.responseText);
}
}
xmlHttp.open("GET", linkInfo, true); //update page using link info variable created above
xmlHttp.send(null);
}
So as you can see I'm trying to pass a sting of text into this function, but I seem to be failing somewhere.
You probably want to setup your tag to pass "this". I don't see where your raceupdate variable is declared, unless it's global... in which case you should show us what you're doing with that variable.
<select onchange='MakeRequest(this);'>
<option>Deathmateched</option>
<?php
dmList();
?>
If you did it that way, you'd have to change this function as such:
function MakeRequest(element)
{
var linkInfo = "teleport.php?call=" + element.value;//create appropriate link depending on function parameters
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
HandleResponse(xmlHttp.responseText);
}
}
xmlHttp.open("GET", linkInfo, true); //update page using link info variable created above
xmlHttp.send(null);
}
And what are you trying to do here?
this.options[this.selectedIndex].value;
In your comments, it looks like you're saying you want to jump to an anchor tag? If so, then you would want to do something like
var anchorTag = document.getElementID("YOUR_ANCHOR_TAG_ID");
anchorTag.focus();

Categories

Resources