How to select and delete a TR element with multiple td's? - javascript

So what it does it creates a to do list. You add and select a category in the first input field and then in the second you create a TR which contains 4 tds with information such as the number of the list, date, the chosen category and the chosen second user input. With my code I can select and delete categories but I'm having trouble figuring out how to target the TR with multiple TD's in it.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="utf-8">
<script src="javascript.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<script src="style.js"></script>
</head>
<body>
<div class="page-header text-center bg-primary mb-1">
<h1>Opravila</h1>
</div>
<div class="container">
<div class="row m-3">
<div class="col-md-6">
<div class="input-group mb-2 mt-2">
<input type="text" class="form-control mr-2" id = "dodaj" name="additem">
<button id="add" class="btn btn-primary mr-2" onclick="newElement()">Dodaj</button>
<button id="remove" class="btn btn-primary" class="remove" >Zbriši</button>
</div>
<ul id="kategorija" class="notes" class="list-group">
<li class="list-group-item">Vaje</li>
<li class="list-group-item">Treningi</li>
<li class="list-group-item">Projekt</li>
</ul>
</div>
<div class="col-md-6">
<div class="input-group mb-2 mt-2">
<input type="text" id = "opravila" class="form-control mr-2">
<button id="add2" onclick="AddTo()" class="btn btn-primary">Dodaj</button>
</div>
<table class="table table-striped table-hover">
<table class="table table-striped table-hover">
<thead>
<tr>
<th id="number">#</th>
<th id="desc">Opis</th>
<th id="category">Kategorija</th>
<th id="time">Datum vnosa</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<button id="removerino" class="btn btn-danger">Brisi</button>
</div>
</div>
</div>
<div class="page-footer text-center bg-secondary p-3">
<p class="m-0">OSS Vaja 5 - jQuery in Bootstrap</p>
</div>
</body>
</html>
JS
var counter = 0;
$(document).on('click', '.list-group-item', function(){
$('.list-group-item')
.css({ "font-weight": 'normal', "text-decoration": 'none'})
.removeClass("selectedItem");
$(this)
.css({"font-weight": 'bold', "text-decoration": 'underline'})
.addClass("selectedItem");
});
$(function(){
$("#add").click(function(){
var addItem = $("#dodaj").val();
if(addItem.length > 0) {
$("ul").append($('<li class="list-group-item"></li>)').text(addItem));
$("#dodaj").val("");
}
});
$("#remove").click(function() {
$(".selectedItem").remove();
});
$("#removerino").click(function() {
$(".selectedItem").remove();
});
});
function AddTo(){
var currentdate = new Date();
var datetime = currentdate.getDate() + "/"
+ (currentdate.getMonth()+1) + "/"
+ currentdate.getFullYear() + " # "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":"
+ currentdate.getSeconds();
counter++;
var td1 = counter;
var td2 = document.getElementById('opravila').value;
var td3 = document.getElementsByClassName("selectedItem")[0].innerText;
var td4 = datetime;
$("tbody").append("<tr>" + "</tr>");
$("tr").last().append("<td>" +td1+ "</td");
$("td").last().append("<td>" +td2+"</td");
$("td").last().append("<td>" +td3+"</td");
$("td").last().append("<td>" +td4+"</td");
$("tr").last().attr("<td>" +td1+ "</td");
}

Based on the code you have given I found.remove(), so if that is the intended 'TD' you are trying to remove and you want relevant TR you can try "parent().remove()" which will remove 'TR' completely.
sample Js:
$("#remove").click(function() {
$(".selectedItem").parent().remove();
});
$("#removerino").click(function() {
$(".selectedItem").parent().remove();
});

Related

how can I Add options weight and value selected when user click add to cart button

it would be great if someone can help me here .I am trying to add weight value option that let user select add to cart like this screenshot here]
this is my code`
Sorry for the long code but how can I implement the option value inside this shopping cart code.
How to add options to a select element to display it on the modal section
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
<meta http-equiv="x-ua-compatible" content="ie=edge" />
<title>Shopping Cart Course Discoveryvip.com</title>
<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.5/css/bootstrap.min.css"
integrity="sha384-AysaV+vQoT3kOAXZkl02PThvDr8HYKPZhNT5h/CXfBThSRXQ6jW5DO2ekP5ViFdi"
crossorigin="anonymous"
/>
<style>
#output {
clear: both;
}
#checkoutdiv {
display: none;
}
.footer {
background-color: darkgrey;
color: white;
}
</style>
</head>
<body>
<header class="header">
<div class="htop">
<div id="checkoutdiv " class="container">
<div class="row">
<div class="col-md-6 text-xs-right">
(<span class="items text-muted"></span> <small>items</small>)
<span class="total"></span>
</div>
<div class="col-md-6 text-xs-right">
<span
class="btn btn-success"
data-toggle="modal"
data-target="#cart"
>Open Shopping Cart</span
><a href="checkout.html" class="btn btn-primary"
>Proceed to checkout</a
>
</div>
</div>
</div>
</div>
<div class="hbot">
<div class="container">
<nav class="navbar navbar-full navbar-dark bg-inverse">
<button
class="navbar-toggler light float-xs-right hidden-sm-up"
type="button"
data-toggle="collapse"
data-target="#nvbar"
></button>
<div id="nvbar" class="collapse navbar-toggleable-xs">
<ul class="nav navbar-nav float-sm-right">
<li class="nav-item">
<a class="nav-link" href="index.html">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="about.html">About</a>
</li>
<li class="nav-item">
<a class="nav-link" href="products.html">Products</a>
</li>
</ul>
</div>
</nav>
</div>
</div>
</header>
<div class="content">
<!-- content changes on each page -->
<div class="container">
<div class="row">
<div class="col-md-3">
<div class="card">
<div class="card-block">
<h3 class="card-title">iPhone</h3>
<h6 class="card-subtitle text-muted">$500.00</h6>
<img src="lamb.jpg" class="img-fluid" />
<form class="myform" action="" method="dialog">
<div class="optwheight">wheight-options</div>
<!-- <wheight -->
<select id="mySelect" onchange="myFunction()">
<option value="0">select
<option value="£9.50">226.79g=80z
<option value="£8.20">220g
<option value="£9.50">280g
<option value="£8.20">220g
</select>
<p id="demo"></p>
<div class="card-block">
<div class="card-text"><h4> 28 days Ribeye Steaks</h4>
<a href="#"
class="card-link productItem btn btn-primary" data-name="Beef" data-s="Ribeye Steaks" data-price="50000" data-id="1">Add to Cart</a> </div>
</div>
<!-- <wheight/end -->
<div><input id="res" type="reset" /></div>
</form>
</div>
</div>
</div>
</div>
<footer class="footer">
<div class="container">
<p class="text-xs-center">© Copyright info blah blah</p>
</div>
</footer>
<!-- Modals -->
<div class="modal fade" id="cart" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Shopping Cart</h4>
</div>
<div class="modal-body">
<table class="table table-hover">
<thead class="thead-inverse">
<tr>
<th>Qty</th>
<th>Item Name</th>
<th>Weight</th>
<th>Cost</th>
<th class="text-xs-right">Subtotal</th>
<th>Remove</th>
</tr>
</thead>
<tbody id="output"></tbody>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-warning" data-dismiss="modal">
Continue Shopping</button
><a href="checkitout.html" class="btn btn-primary"
>Proceed to checkout</a
>
</div>
</div>
</div>
</div>
<script>
function myFunction() {
var x = document.getElementById("mySelect").value;
document.getElementById("demo").innerHTML = " " + x;
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.3.7/js/tether.min.js"
integrity="sha384-XTs3FgkjiBgo8qjEjBk0tGmf3wPrWtA6coPfQDfFEY8AnYJwjalXCiosYRBIBZX8"
crossorigin="anonymous"
></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.5/js/bootstrap.min.js"
integrity="sha384-BLiI7JTZm+JWlgKa0M0kGRpJbF2J8q+qreVrKBC47e3K6BW78kGLrCkeRX6I9RoK"
crossorigin="anonymous"
></script>
<script>
var shopcart = [];
$(document).ready(function () {
outputCart();
$(".productItem").click(function (e) {
e.preventDefault();
var iteminfo = $(this.dataset)[0];
iteminfo.qty = 1;
var itemincart = false;
$.each(shopcart, function (index, value) {
//console.log(index + ' ' + value.id);
if (value.id == iteminfo.id) {
value.qty = parseInt(value.qty) + parseInt(iteminfo.qty);
itemincart = true;
}
});
if (!itemincart) {
shopcart.push(iteminfo);
}
sessionStorage["sca"] = JSON.stringify(shopcart);
outputCart();
///
});
function outputCart() {
if (sessionStorage["sca"] != null) {
shopcart = JSON.parse(sessionStorage["sca"].toString());
console.log(sessionStorage["sca"]);
$("#checkoutdiv").show();
}
var holderHTML = "";
var total = 0;
var itemCnt = 0;
$.each(shopcart, function (index, value) {
console.log(value);
var stotal = value.qty * value.price;
total += stotal;
itemCnt += parseInt(value.qty);
holderHTML +="<tr><td>" +value.qty +"</td><td>#" + value.id + " " +value.name +
"(" +
value.s +
")</td><td> " +
formatMoney(value.price) +
' </td><td class="text-xs-right"> ' +
formatMoney(stotal) +
'</td><td><span class="remove-item btn btn-danger">x</span></td></tr>';
});
holderHTML
holderHTML +=
'<tr><td colspan="3" class="text-xs-right">Total</td><td class="text-xs-right">' +
formatMoney(total) +
"</td></tr>";
$("#output").html(holderHTML);
$(".total").html(formatMoney(total));
$(".items").html(itemCnt);
}
function formatMoney(n) {
return "$" + (n / 100).toFixed(2);
}
$("#output").on("click", ".remove-item", function () {
var itemInfo = $(this.dataset)[0];
var itemToDelete = $(".remove-item").index(this);
shopcart.splice(itemToDelete, 1);
sessionStorage["sca"] = JSON.stringify(shopcart);
outputCart();
});
});
</script>
</body>
</html>
Use option:selected .
Checkout how to get selected option.
$(".productItem").click(function (e) {
e.preventDefault();
var iteminfo = $(this.dataset)[0];
let selectedItem = $('#mySelect option:selected') //add. selected option selector
iteminfo.qty = 1;
iteminfo.price = selectedItem.val().replace('£','') //add. value of selected option.
You'd better find a better way to use the formatMoney function with the numeric calculation instead of using .replace()
iteminfo.weight = selectedItem.text() //add. text of selected option
var itemincart = false;
$.each(shopcart, function (index, value) {
//console.log(index + ' ' + value.id);
if (value.id == iteminfo.id) {
value.qty = parseInt(value.qty) + parseInt(iteminfo.qty);
itemincart = true;
}
});
if (!itemincart) {
shopcart.push(iteminfo);
}
sessionStorage["sca"] = JSON.stringify(shopcart);
outputCart();
///
});
Add weight td in var stotal
var stotal = value.qty * value.price;
total += stotal;
itemCnt += parseInt(value.qty);
holderHTML +="<tr><td>" +value.qty +"</td><td>#" + value.id + " " +value.name +
"(" +
value.s +
")</td><td> " + //add
value.weight + //add
"</td><td> " +
formatMoney(value.price) +
' </td><td class="text-xs-right"> ' +
formatMoney(stotal) +
'</td><td><span class="remove-item btn btn-danger">x</span></td></tr>';

How to make this owlcarousel display items properly?

I'm trying to make this owlcarousel work but for some reason its not coming up. Its an issue with some of the script tags I guess.
I'm using owl carousel and displaying items from Database inside owlcarousel using Ajax. However when I do that there is no carousel and the items get dumped one below each other like so:
Ajax
<script>
var results = $(".owl-carousel");
$.ajax({
url: "getmaincarousel",
type: "GET",
success: function (response) {
response.forEach(function (item) {
results
.owlCarousel()
.trigger("add.owl.carousel", [
JQuery(
'<div class="item"> <div class="blog-entry"> <a href="#" class="block-20 d-flex align-items-start" style="background-image: url(' +
item.img +
');"> <div class="meta-date text-center p-2"> <span class="day">' +
item.subject +
'</span> <span class="mos">' +
item.subject +
'</span> <span class="yr">' +
item.courseduration +
'</span> </div> </a> <div class="text border border-top-0 p-4"> <h3 class="heading"><a href="#">' +
item.coursename +
"</a></h3> <p>" +
item.coursedesc +
'</p> <div class="d-flex align-items-center mt-4"> <p class="mb-0">Read More <span class="ion-ios-arrow-round-forward"></span></p> <p class="ml-auto meta2 mb-0"> ' +
item.courseprice +
" </p> </div> </div> </div> </div>"
),
])
.trigger("refresh.owl.carousel");
});
},
});
</script>
Script format 1
<script src="../js/jquery.js"></script>
<script src="../js/popper.js"></script>
<script src="../js/bootstrap.min.js"></script>
<script src="../js/owl.carousel.min.js"></script>
<script src="../js/main.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
When I do this, I get the following error in console:
the script owlcarousel.min.js is not getting used idk why
and when i interchange the script tags like so, I get this error
Script format 2
<script src="../js/jquery.js"></script>
<script src="../js/popper.js"></script>
<script src="../js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="../js/owl.carousel.min.js"></script>
<script src="../js/main.js"></script>
Notice how changing the Jquery 2.1.4 script position gives different errors.
I really dont know why this keeps happening. I need the owl carousel min to get the owlCarousel function which refreshes the carousel. I also need the Jquery 2.1.4 to perform Ajax query. How do I solve this and make use of both?
Here's my full html file
<!DOCTYPE html>
<html lang="en">
<head>
<title>Carousel 07</title>
<meta charset="utf-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
<link
href="https://fonts.googleapis.com/css?family=Poppins:300,400,500,600,700,800,900"
rel="stylesheet"
/>
<link rel="stylesheet" href="css/owl.carousel.min.css" />
<link rel="stylesheet" href="css/owl.theme.default.min.css" />
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/ionicons/4.5.6/css/ionicons.min.css"
/>
<link rel="stylesheet" href="css/style.css" />
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"
/>
<link
rel="stylesheet"
href="https://fonts.googleapis.com/icon?family=Material+Icons"
/>
</head>
<body>
<div class="navbar">
Phemesoft
Dashboard
Courses
Live classes
Labs
<div class="search">
<input type="search" placeholder="Search" class="inputSearch" />
<!-- <button type="submit" class="searchButton">
<i class="fa fa-search"></i>
</button>-->
</div>
<button type="submit" class="searchbtn">
<span class="material-icons">search</span>
</button>
<span class="material-icons">shopping_cart</span>
<span class="material-icons">account_circle</span>
</div>
<section class="ftco-section">
<div class="container">
<div class="row">
<div class="col-md-12 text-center">
<h2 class="heading-section mb-5 pb-md-4">Courses available</h2>
</div>
<div class="col-md-12">
<div class="featured-carousel owl-carousel">
<!-- <div class="item">
<div class="blog-entry">
<a href="#" class="block-20 d-flex align-items-start" style="background-image: url('images/image_1.jpg');">
<div class="meta-date text-center p-2">
<span class="day">csubj</span>
<span class="mos">cboard</span>
<span class="yr">cduration</span>
</div>
</a>
<div class="text border border-top-0 p-4">
<h3 class="heading">Finance And Legal Working Streams Occur Throughout</h3>
<p>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts.</p>
<div class="d-flex align-items-center mt-4">
<p class="mb-0">Read More <span class="ion-ios-arrow-round-forward"></span></p>
<p class="ml-auto meta2 mb-0">
cprice
</p>
</div>
</div>
</div>
</div> -->
</div>
</div>
</div>
</div>
</section>
<script src="../js/jquery.js"></script>
<script src="../js/popper.js"></script>
<script src="../js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="../js/owl.carousel.min.js"></script>
<script src="../js/main.js"></script>
<script>
// $.ajax({
// url: "getmaincarousel",
// type: "GET",
// success: function (response) {
// var $results = $(".owl-carousel");
// for (var a = 0; a < response.length; a++) {
// // console.log(response[a].Name);
// $results.append(
// '<div class="item"> <div class="blog-entry"> <a href="#" class="block-20 d-flex align-items-start" style="background-image: url(' +
// response[a].img +
// ');"> <div class="meta-date text-center p-2"> <span class="day">' +
// response[a].subject +
// '</span> <span class="mos">' +
// response[a].subject +
// '</span> <span class="yr">' +
// response[a].courseduration +
// '</span> </div> </a> <div class="text border border-top-0 p-4"> <h3 class="heading"><a href="#">' +
// response[a].coursename +
// "</a></h3> <p>" +
// response[a].coursedesc +
// '</p> <div class="d-flex align-items-center mt-4"> <p class="mb-0">Read More <span class="ion-ios-arrow-round-forward"></span></p> <p class="ml-auto meta2 mb-0"> ' +
// response[a].courseprice +
// " </p> </div> </div> </div> </div>"
// );
// }
// },
// });
</script>
<script>
var results = $(".owl-carousel");
$.ajax({
url: "getmaincarousel",
type: "GET",
success: function (response) {
response.forEach(function (item) {
results
.owlCarousel()
.trigger("add.owl.carousel", [
JQuery(
'<div class="item"> <div class="blog-entry"> <a href="#" class="block-20 d-flex align-items-start" style="background-image: url(' +
item.img +
');"> <div class="meta-date text-center p-2"> <span class="day">' +
item.subject +
'</span> <span class="mos">' +
item.subject +
'</span> <span class="yr">' +
item.courseduration +
'</span> </div> </a> <div class="text border border-top-0 p-4"> <h3 class="heading"><a href="#">' +
item.coursename +
"</a></h3> <p>" +
item.coursedesc +
'</p> <div class="d-flex align-items-center mt-4"> <p class="mb-0">Read More <span class="ion-ios-arrow-round-forward"></span></p> <p class="ml-auto meta2 mb-0"> ' +
item.courseprice +
" </p> </div> </div> </div> </div>"
),
])
.trigger("refresh.owl.carousel");
});
},
});
</script>
</body>
</html>

two level add more filed in Javascript

I'm trying to make Create Quiz Page. there should be dynamically inputs on-page. there is no defined number of questions and a number of answers to each question. for add question, I'm using bootstrap accordion and it works. after click add question it appends new accordion and inputs inside. but in a second-level load more after button click, nothing happens. also, I want dynamically add answers. I'm using same logic. after #question click I creating HTML element ad trying to append inside answersAccordion.
jQuery click event not working.
$(document).ready(function () {
var next = 0;
$("#add-more").click(function(e){
e.preventDefault();
let _html = '';
_html+='<div class="card">';
_html+='<div class="card-header" id="heading'+next+'">';
_html+='<h5 class="mb-0">';
_html+='<button class="btn btn-link" data-toggle="collapse" data-target="#collapse'+next+'" aria-expanded="true" aria-controls="collapse'+next+'">';
_html+='Quiz question: '+next;
_html+='</button>'
_html+='</h5>';
_html+='</div>';
_html+='<div id="collapse'+next+'" class="collapse" aria-labelledby="heading'+next+'" data-parent="#accordion">';
_html+='<div class="card-body">';
_html+='<input form="myform" type="text" name="questions[][question]">'
_html+='<input form="myform" type="file" name="questions[][image]">'
_html+='<div class="col-md-3">';
_html+='<button id="question" name="add-question" class="btn btn-primary">Add Question</button>'
_html+='<div id="answersAccordion">';
_html+='</div>';
_html+='</div>';
_html+='</div>'
_html+='</div>'
_html+='</div>'
$('#accordion').append(_html);
next+=1;
});
$("#question").click(function(e){
console.log(12121)
let _html = '';
_html+='<div class="ml-5">'
_html+='<input type="text" name="questions[][answers][][title]">';
_html+='<textarea name="questions[][answers][][description]"></textarea>';
_html+='<input type="file" name="questions[][answers][][image]" ';
_html+='</div>'
$(this).next().append(_html);
console.log($(e))
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="form-group">
<div class="col-md-12">
<button id="add-more" name="add-more" class="btn btn-primary">Add More</button>
</div>
</div>
<form id="myform" method="post" action="post.php" enctype="multipart/form-data">
<button>send</button>
</form>
<div class="col-xs-12">
<div class="col-md-12" >
<h3> Actions</h3>
<div id="accordion">
</div>
</div>
</div>
</body>
</html>
console.log not working also
in the console, there is no error
There is other way to make the code better and cleaner.
I hope it helps.
$(document).ready(function () {
var next = 0;
$("#add-more").click(function(e){
e.preventDefault();
let _html = `
<div class="card">
<div class="card-header" id="heading ${next}">
<h5 class="mb-0">
<button class="btn btn-link" type="button" data-toggle="collapse" data-target="#collapse-${next}" aria-expanded="true" aria-controls="collapse-${next}">
Quiz question: ${next}
</button>
</h5>
</div>
<div id="collapse-${next}" class="collapse" aria-labelledby="heading ${next}" data-parent="#accordion">
<div class="card-body">
<input form="myform" type="text" name="questions[][question]">
<input form="myform" type="file" name="questions[][image]">
<div class="col-md-3">
<button id="question" name="add-question" class="btn btn-primary add-question-${next}">Add Question</button>
<div id="answersAccordion">
</div>
</div>
</div>
</div>
</div>
`;
$('#accordion').append(_html);
$(`.add-question-${next}`).click(function(e){
let _html = `
<div class="ml-5">
<input type="text" name="questions[][answers][][title]">
<textarea name="questions[][answers][][description]"></textarea>
<input type="file" name="questions[][answers][][image]"
</div>
`;
$(this).next().append(_html);
});
next+=1;
});
});

How can I list movie names by results.title in the UI <li>

I know to show data on repeat in AngularJS , but now I am trying on native javascript.
I have called data from TMDB API. Now I need to list those in UI list.
function afterLoad() {
var data = JSON.parse(this.responseText);
console.log(data);
name.src = data.title;
}
function afterClick() {
// changed target to focus search
var terms = document.getElementById("search").value.split(' ').join('+');
var request = new XMLHttpRequest();
request.addEventListener('load', afterLoad);
request.open('GET', 'https://api.themoviedb.org/3/search/movie?api_key=8318c431b4fc8a2c4762bf2a52c351ee&query='+terms);
request.send();
}
button.addEventListener("click", afterClick);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css"/>
<title>Get Movies</title>
</head>
<body>
<header id="main-header" class="bg-success text-white p-4 mb-3">
<div class="container">
<h1 id="header-title">Get Movies<span style="display:none">123</span></h1>
<input style="align:right" type="text" class="form-control mr-2" id="search">
<input type="submit" class="btn btn-dark" value="Submit" id="button">
</div>
</header>
<div class="container">
<div id="main" class="card card-body">
<h2 class="title">Add Fav Movies</h2>
<form class="form-inline mb-3">
<input type="text" class="form-control mr-2">
<input type="submit" class="btn btn-dark" value="Submit">
</form>
<h2 class="title">Lists</h2>
<ul id="items" class="list-group">
<li class="list-group-item">Item 1</li>
</ul>
</div>
</div>
</body>
</html>
How can I list movie names by results.title in the UI <li class="list-group-item">Item 1</li> ?
Also I need to select particular movie by id and store in another json collection.
In your afterload function, get the results from data and loop over the items. add li to ul using .append
use document.createElement to create a new li.
use document.createTextNode to create text for the newly created li.
and .appendChild() to append li to ul.
function addListItem(title, listId) {
var ul = document.getElementById(listId);
var li = document.createElement("li");
li.className = 'list-group-item';
li.appendChild(document.createTextNode(title));
ul.appendChild(li);
}
function afterLoad() {
var data = JSON.parse(this.responseText);
var name = document.createElement('img');
const results = data.results;
// loop through items
results.forEach(item => {
addListItem(item.title, "items");
});
name.src = data.title;
document.body.appendChild(name);
}
function afterClick() {
// changed target to focus search
var terms = document.getElementById("search").value.split(' ').join('+');
var request = new XMLHttpRequest();
request.addEventListener('load', afterLoad);
request.open('GET', 'https://api.themoviedb.org/3/search/movie?api_key=8318c431b4fc8a2c4762bf2a52c351ee&query='+terms);
request.send();
}
button.addEventListener("click", afterClick);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css"/>
<title>Get Movies</title>
</head>
<body>
<header id="main-header" class="bg-success text-white p-4 mb-3">
<div class="container">
<h1 id="header-title">Get Movies<span style="display:none">123</span></h1>
<input style="align:right" type="text" class="form-control mr-2" id="search">
<input type="submit" class="btn btn-dark" value="Submit" id="button">
</div>
</header>
<div class="container">
<div id="main" class="card card-body">
<h2 class="title">Add Fav Movies</h2>
<form class="form-inline mb-3">
<input type="text" class="form-control mr-2">
<input type="submit" class="btn btn-dark" value="Submit">
</form>
<h2 class="title">Lists</h2>
<ul id="items" class="list-group">
</ul>
</div>
</div>
</body>
</html>
In your afterload function, get the results from data and loop over the items. add li to ul using .append it the options.
var data = JSON.parse(this.responseText);
var option;
for (var i = 0; i < data.length; i++)
{
option += '<div class="list" id="' + data[i].id + '">'+ data[i].Title +'</div>';
}
$('#items').append(option);

Adding text input to table

I am trying to make the value of the input with the name "game-name" to be in the "Name of the game" column of the table when I click on the "add game" button. Also the delete button does not work.
Here is my code:
$(function() {
var $td = '<td>' + '</td>';
$('input[name=add-game]').click(function() {
$('tbody').append('<tr>' + $td + $td + $td + '</tr>');
var $tableRows = $('tbody tr').length
$('tbody tr').eq($tableRows).children().eq(0).text($('input[name=game-name]').val())
$('td:nth-child(3)').html('<button>');
$('button').text('Delete').addClass('delete btn btn-block btn-sm btn-danger');
});
$('.delete').click(function() {
$(this).parent().parent().empty();
});
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Exercises</title>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/darkly/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<div class="container-fluid">
<div class="jumbotron">
<h2 class="text-center"><b>FAVORITE VIDEO GAMES <small>(all genres) <span class="glyphicon glyphicon-globe"></span></small></b></h2>
</div>
<div class="text-center row">
<div class="col-sm-6 col-md-6">
<ul class="list-group"><h4>These are the games that James like the most</h4>
<li class="list-group-item">...</li>
<li class="list-group-item">...</li>
<li class="list-group-item">...</li>
</ul>
</div>
<div class="col-sm-6 col-md-6">
<ul class="list-group"><h4>These are the games that <b>YOU</b> like the most</h4>
<li class="list-group-item">`empty`</li>
<li class="list-group-item">`empty`</li>
<li class="list-group-item">`empty`</li>
</ul>
</div>
</div>
<hr>
<br>
<div class="row">
<div class="col-sm-12 col-md-12 col-lg-12">
<form class="text-center" action="index.html" method="post">
Game: <input type="text" name="game-name" value="" placeholder="Choose the game">
Rate: <input type="text" name="game-rate" value="" placeholder="Rate the game">
<input class='btn btn-xs btn-success' type="button" name="add-game" value="Add Game">
</form>
<br>
<div class="container">
<table class="table table-bordered table-striped">
<thead>
<th>Name of the game</th>
<th>Rating</th>
<th><span class="glyphicon glyphicon-remove"></span></th>
</thead>
<tbody>
<!-- Here will be added the games -->
</tbody>
</table>
</div> <!-- Close CONTAINER -->
</div>
</div> <!-- Close ROW -->
</div> <!-- Close CONTAINER-FLUID -->
</div>
<script src='script.js'></script>
</body>
</html>
Here's a quick solution. Hope this helps.
$(function() {
$('input[name=add-game]').click(function() {
// Lets get the information ready to be added
var name = '<td>' + $('input[name="game-name"]').val() + '</td>';
var rating = '<td>' + $('input[name="game-rate"]').val() + '</td>';
var btnDelete = '<td><button class="delete btn btn-block btn-sm btn-danger">Delete</button></td>'
// Lets append the information into the game table
$('tbody[id="game-table"]').append('<tr>' + name + rating + btnDelete + '</td>');
// Since we've created a delete button, we need to bind
// an event listener to the button so that we can
// delete it from the table if the user clicks it
$('.delete').on('click', function() {
$(this).parent().parent().empty();
});
});
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Exercises</title>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/darkly/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<div class="container-fluid">
<div class="jumbotron">
<h2 class="text-center"><b>FAVORITE VIDEO GAMES <small>(all genres) <span class="glyphicon glyphicon-globe"></span></small></b></h2>
</div>
<div class="text-center row">
<div class="col-sm-6 col-md-6">
<ul class="list-group"><h4>These are the games that James like the most</h4>
<li class="list-group-item">...</li>
<li class="list-group-item">...</li>
<li class="list-group-item">...</li>
</ul>
</div>
<div class="col-sm-6 col-md-6">
<ul class="list-group"><h4>These are the games that <b>YOU</b> like the most</h4>
<li class="list-group-item">`empty`</li>
<li class="list-group-item">`empty`</li>
<li class="list-group-item">`empty`</li>
</ul>
</div>
</div>
<hr>
<br>
<div class="row">
<div class="col-sm-12 col-md-12 col-lg-12">
<form class="text-center" action="index.html" method="post">
Game: <input type="text" name="game-name" value="" placeholder="Choose the game">
Rate: <input type="text" name="game-rate" value="" placeholder="Rate the game">
<input class='btn btn-xs btn-success' type="button" name="add-game" value="Add Game">
</form>
<br>
<div class="container">
<table class="table table-bordered table-striped">
<thead>
<th>Name of the game</th>
<th>Rating</th>
<th><span class="glyphicon glyphicon-remove"></span></th>
</thead>
<tbody id="game-table">
<!-- Here will be added the games -->
</tbody>
</table>
</div> <!-- Close CONTAINER -->
</div>
</div> <!-- Close ROW -->
</div> <!-- Close CONTAINER-FLUID -->
</div>
<script src='script.js'></script>
</body>
</html>
Your code is in $(function()... it means that when the dogument gets ready these codes will run. You add delete buttons after all codes ended. In another way your delete buttons add after the codes running and this:
$('.delete').click(function() {
$(this).parent().parent().empty();
});
Does not register for new added .delete buttons.
To elements that dynamically adding to page you need to use delegate:
$('.delete').on('click', function() {
$(this).parent().parent().empty();
});

Categories

Resources