remove label and button when button clicked - javascript

I have made two labels(Label1 and Label 2 and two remove button for each labels) by using html, javascript and jquery for my learning purposes.
Now I want the label and button to be removed when the cross button is clicked.
I tried
$(".labels").closest().remove();
But it does not work. Please help
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Page 2</title>
</head>
<body>
<div class="container">
<div class="form-group row">
<div class="col-md-2 labels">
<label>Label 1 </label>
</div>
<div class="col-md-1" style="padding-bottom: 5px">
<button class="btn btn-danger btn-xs removeBtn">
<span class="glyphicon glyphicon-remove"></span>
</button>
</div>
</div>
</div>
<script type="text/javascript">
$(document)
.ready(
function() {
var formGroupRowDiv = $(
document.createElement('div')).attr(
"class", 'form-group row');
var labelTwoDiv = $(document.createElement('div'))
.attr("class", 'col-md-2 labels');
var removeBtnDiv = $(document.createElement('div'))
.attr("class", 'col-md-1 removeBtn');
labelTwoDiv.appendTo(formGroupRowDiv).html(
'<label>Label 2</label>');
removeBtnDiv
.appendTo(formGroupRowDiv)
.html('<button class="btn btn-danger btn-xs removeDate">'
+ '<span class="glyphicon glyphicon-remove"></span>'
+ '</button>');
$(formGroupRowDiv).appendTo('.container');
$(".removeBtn").click(function(e) {
e.preventDefault();
$(".labels").closest().remove();
});
});
</script>
</body>
</html>

Try this:
$("body").click(".removeBtn", function(e) {
$(e.target).parent().parent().siblings().find("label").remove()
});
Since you are dynamically generating the divs, you cant just bind the handler to the divs that appear on load. You need to bind it to something higher up (like body)
e.target here is the removeBtn
.parent() will return a jQuery object of the parent
.siblings() will return all of it [the parent's] siblings
.find() will filter to the passed selector
.remove() will remove it from the DOM

Basically you had 4 problems here:
You don't want to remove all the closest() elements of any .labels element that exists on the page (you want to remove a specific .labels element that is the closest to the current .removeBtn you just clicked.
The closest is not what you are looking for, but actually the prev element.
Since your structure for your HTML is different between the two .removeBtn elements you have - you will need two different selectors.
The first selector will be $(this).prev('.labels') and the second will be $(this).parent().prev('.labels').
If you also want to remove the button that was just clicked - use $(this).remove();.
This is the fist to your code:
$(".removeBtn").click(function(e) {
e.preventDefault();
if ($(this).prev('.labels').length) {
$(this).prev('.labels').remove();
} else if ($(this).parent().prev('.labels').length) {
$(this).parent().prev('.labels').remove();
}
$(this).remove();
});
Here is a working snippet:
$(document)
.ready(
function() {
var formGroupRowDiv = $(
document.createElement('div')).attr(
"class", 'form-group row');
var labelTwoDiv = $(document.createElement('div'))
.attr("class", 'col-md-2 labels');
var removeBtnDiv = $(document.createElement('div'))
.attr("class", 'col-md-1 removeBtn');
labelTwoDiv.appendTo(formGroupRowDiv).html(
'<label>Label 2</label>');
removeBtnDiv
.appendTo(formGroupRowDiv)
.html('<button class="btn btn-danger btn-xs removeDate">'
+ '<span class="glyphicon glyphicon-remove"></span>'
+ '</button>');
$(formGroupRowDiv).appendTo('.container');
$(".removeBtn").click(function(e) {
e.preventDefault();
if ($(this).prev('.labels').length) {
$(this).prev('.labels').remove();
} else if ($(this).parent().prev('.labels').length) {
$(this).parent().prev('.labels').remove();
}
$(this).remove();
});
});
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Page 2</title>
</head>
<body>
<div class="container">
<div class="form-group row">
<div class="col-md-2 labels">
<label>Label 1 </label>
</div>
<div class="col-md-1" style="padding-bottom: 5px">
<button class="btn btn-danger btn-xs removeBtn">
<span class="glyphicon glyphicon-remove"></span>
</button>
</div>
</div>
</div>
</body>
</html>

Related

Editable notes function button not functioning in Jquery

The jquery code to allow a form and button to show entered data as a list is not functioning. The code is also written to delete the text when it is clicked on - unable to check if this is also working. Any suggestions on where the error may be found?
$(document).ready(function(){
$('#button').click(function(){
var toAdd = $('input[name=checkListItem]').val();
$('.list').append("<div class='item'>" + toAdd + "</div>");
});
$('.list').click(function(){
});
});
$(document).on('click', '.item', function(){
$(this).remove();
});
html
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="style.css" type="text/css">
<!-- <script src="js_lib/jquery-ui.js"></script>-->
<script src="jquery-3.5.1.min.js"></script>
<title>A Simple Notes List</title>
<h1><span>A Simple Notes List</span></h1>
<div id="canvas" class="container group">
<div id="primaryContent" class="group">
<p> </p>
<form name="checkListForm">
<input type="text" name="checkListItem"/>
</form>
<div id="button" value="button">Add!</div>
<br/>
<div class="list"></div>
<p>Click item on list to remove item from list</p>
</div>

dynamic form datepicker jquery

I tried to create a dynamic form. Im not sure why the datepicker cant be clicked. Datepicker only work on first row. I already try few other code but no luck. The code is provided below. I excluded the PHP code because it only consist of code for insert into database. My target is to store the dynamic form into database.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(function(){
$(".datepicker").datepicker({
dateFormat: 'dd-mm-yy'
});
});
$(function()
{
$(document).on('click', '.btn-add', function(e)
{
e.preventDefault();
var controlForm = $('.controls .d1:first'),
currentEntry = $(this).parents('.entry:first'),
newEntry = $(currentEntry.clone()).appendTo(controlForm);
newEntry.find('input').val('');
controlForm.find('.entry:not(:last) .btn-add')
.removeClass('btn-add').addClass('btn-remove')
.removeClass('btn-success').addClass('btn-danger')
.html('<span class="fa fa-minus"></span>');
}).on('click', '.btn-remove', function(e)
{
$(this).parents('.entry:first').remove();
e.preventDefault();
return false;
});
});
</script>
</head>
<body>
<form method="POST" action="" name="loginin">
<div class="controls">
<div class="d1">
<div class="entry input-group">
<input list="pronama" name="proPlace[]" type="text" placeholder="Place" class="form-control">
<input type="text" class="datepicker" class="form-control" name="date[]">
<span class="input-group-btn">
<button class="btn btn-success btn-add" type="button">
<span class="fa fa-plus"></span>
</button>
</span>
</div>
</div>
</div>
<button type="submit" name="login" class="btn btn-lg btn-success btn-block">Sign In</button>
</form>
</body>
</html>
You need to initialize the datepicker with each creation, like so:
newEntry.removeAttr('id');
$(".datepicker", newEntry)
.removeAttr('id')
.removeClass('datepicker hasDatepicker')
.datepicker({
dateFormat: 'dd-mm-yy'
});
making the new entry's input a date picker, the removal of the hasDatepicker class is needed for this to work, because you clone the input, the class is in the cloned element too.
here's a jsfiddle: adding dynamic datepickers
EDIT:
updated the fiddler, the reason only the first input was updated on selecting a date, is because it's a cloned element, containing the same id as the original, so when looking for the id of the datepicker, it stumbles upon the one.
the fix was described here.
Datepicker selected value always goes on the first textbox

Iterate through a JSON list with JS function

I'm looking for a way to append some JSON results, I'm working with a list (array?) and there's multiple elements, I know I can add some styling directly in the JS code but I'm more comfortable with this method. How can I iterate through elements and implement in some divs, then create similar divs with the next elements.
The only way to achieve that goal afaik is like this:
$("#article").append(data[i].datetime + data[i].headline + "<br />" + "<hr />" + data[i].summary);
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Project JS 02</title>
<link rel="stylesheet" href="assets/main.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<div class="container container-table">
<div class="row vertical-center-row">
<div class="col-md-4 col-md-offset-4">
<button type="submit" class="btn btn-primary" style="width: 100%" class="search" id="getnews">Get News!</button>
<h1 id="headline"></h1><br>
<h3 id="datetime"></h3><br>
<div id="summary"></div><br>
<h6 id="source"></h6><br>
</div>
</div>
</div>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script>
document.getElementById("getnews").addEventListener("click", function () {
var newsurl = "https://api.iextrading.com/1.0/stock/aapl/news"
$.getJSON(newsurl, function (data) {
for (i in data)
{
$("#headline").append(data[i].headline);
$("#datetime").append(data[i].datetime);
$("#summary").append(data[i].summary);
$("#source").append(data[i].source);
}
})
})
</script>
</body>
</html>
You can do this by creating the elements (with jQuery) as needed, and appending them to a container:
$("#getnews").on("click", function () {
var newsurl = "https://api.iextrading.com/1.0/stock/aapl/news"
$('#data').text("...loading...");
$.getJSON(newsurl, function (data) {
$('#data').html("");
data.forEach(function (article) {
$('#data').append(
$('<h1>').text(article.headline),
$('<h3>').text(article.datetime),
$('<div>').text(article.summary),
$('<h6>').text(article.source)
);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn btn-primary search"
style="width: 100%" id="getnews">Get News!</button>
<div id="data"></div>
First: remove the ids. If you want to create similar containers, the ids will be there multiple times, that won't work.
Second: Take the div with $('.row.vertical-center-row') and clone it.
Third: set the values at the cloned HTMLNode und append it to $('.container.container-table')
Something like that (untested):
<div class="container container-table">
<div class="row vertical-center-row">
<div class="col-md-4 col-md-offset-4">
<button type="submit" class="btn btn-primary" style="width: 100%" class="search" class="getnews">Get News!</button>
<h1 class="headline"></h1><br>
<h3 class="datetime"></h3><br>
<div class="summary"></div><br>
<h6 class="source"></h6><br>
</div>
</div>
</div>
<script>
document.getElementsByClassName("getnews").forEach((el)=>el.addEventListener("click", function () {
var newsurl = "https://api.iextrading.com/1.0/stock/aapl/news"
$.getJSON(newsurl, function (data) {
var $elClone = $('.row.vertical-center-row').clone(true).appendTo($('.container.container-table'));
for (i in data) {
$(".headline", $elClone).append(data[i].headline);
$(".datetime", $elClone).append(data[i].datetime);
$(".summary", $elClone).append(data[i].summary);
$(".source", $elClone).append(data[i].source);
}
})
}));
</script>

Window onload function is not working properly?

This is my code :
I have used window onload function to populate ui elements but it is not working properly.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Regalo - Shop</title>
<link rel="stylesheet" href="<%=request.getContextPath()%>/resources/css/bootstrap.min.css" />
<script src="<%=request.getContextPath()%>/resources/js/jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(window).on('load',function(){
alert("OK");
<c:forEach var="item" items="${itemList}">
var name= '${item.desktopbrand}';
var details='${item.details}';
var id = '${item.desktopid}';
var price = '${item.desktopid}';
var catagory = '${item.catagory}';
var spanTag = '<div class="col-sm-6 col-md-4"> <div class="thumbnail"> <img data-src="img/Desktop/'+ id +'.jpg"> <div class="caption"><h3>'+ name+ '</h3> <p>'+ price+ '</div> </p> <p><button type="button" class="btn btn-success btn-lg" onclick="details()">Show Details</button></p><p><button type="button" class="btn btn-success btn-lg" onclick="addToCart()">Buy now</button></p></div></div></div>';
$("#" + catagory).append(spanTag);
</c:forEach>
});
</script>
</head>
<body>
<h1>Gens Cooner</h1>
<div id="gen" class="container"></div>
<h1>Ladies Cooner</h1>
<div id="lad" class="container"></div>
<h1>Childrens Cooner</h1>
<div id="chil" class="container"></div>
</body>
</html>
I try to find the issue but couldn't. Your help would be highly appreciated.
window.onload = function(){ alert('Working!!'); }
Use above function and make sure you use only one window.onload function in a page

Jquery: How to make objects inside <div> to hide or show on click?

I want to make a webpage in which three different contents show/hide when a button is clicked. The code is shown below.
I want the same page to show three contents:
only a search bar when button 'search' is clicked,
only the result of the search after a search is done or when the button 'results' is clicked, and
only the visualization of the search when one specific outcome of the results is chosen, or when the button 'visualization' is clicked.
Right now I only know how to show the results in different pages, not in the same one hiding what I don't want.
Code is below.
Thanks
<html lang="en">
<head>
<title>Test</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<link rel="shortcut icon" href="docs-assets/ico/favicon.png">
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/bootstrap-theme.min.css">
<link href="css/jumbotron-narrow.css" rel="stylesheet">
<link href="css/jquery.dataTables.css" rel="stylesheet">
<link rel="shortcut icon" type="image/ico" href="" />
<script src="js/jquery-1.10.2.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script type="text/javascript" language="javascript" src="js/libs/jquery-2.0.3.min.js"></script>
<script type="text/javascript" language="javascript" src="js/libs/jquery.sprintf.js"></script>
<script type="text/javascript" language="javascript" src="js/libs/jquery.dataTables.min.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
//xmakeTable("treaty");
});
makeTable = function(query) {
var q = encodeURIComponent(query)
$('#example').dataTable({
"oLanguage": {"sSearch": "Filter results:"},
"bProcessing": true,
"bDestroy":true,
"sAjaxSource": $.sprintf('http://leela.sscnet.ucla.edu/voteview/searchdt?q=%s',q),
"aoColumns":[{"mData":"id", "sWidth": "20px", "sTitle":"ID"},
{"mData":"chamber", "sWidth": "10px", "sTitle":"Chamber"},
{"mData":"date", "sWidth": "85px", "sTitle":"Date"},
{"mData":"yea","sTitle":"Vote","sWidth":"80px"},
{"mData":"descriptionShort", "sWidth": "200px","sTitle":"Description"}],
"fnRowCallback": function( nRow, aData, iDisplayIndex ) {
$('td:eq(0)', nRow).html(
$.sprintf('%s',aData['id'],aData['id'])).attr("title","Click to explore this vote");
$('td:eq(3)', nRow).html(
$.sprintf('%s-%s',aData['yea'],aData['no']));
$('td:eq(4)', nRow).attr("title",aData['description'])
return nRow; }
});
}
searchvotes = function() {
$('#example').empty();
makeTable($('#qqtext').val());
};
</script>
</head>
<body>
<div class="container">
<div class="header">
<ul class="nav nav-pills pull-right">
<li>Home</li>
<li class="active">Search</li>
<li>Contact</li>
</ul>
<h3 class="text-muted">VoteView</h3>
</div>
<div class="jumbotron">
<div class="container">
<div>
<h3 align="center">Search for Roll Calls</h3>
<div class="col-sm-12">
<input type="search" class="form-control" placeholder="Search" id="qqtext" onchange="searchvotes()"></input>
</div>
</div>
<br>
<div>
<div class="table-responsive">
<table id="example" class="table table-striped"></table>
</div>
</div>
<div>
<div class="col-lg-14 col-md-14 portfolio-item" id="example">
</div>
</div>
</div>
</div>
<div align="center">
<button type="button" class="btn btn-primary btn-lg">
<span class="glyphicon glyphicon-search"></span><br><font color="white">Search</font>
</button>
<button type="button" class="btn btn-success btn-lg">
<span class="glyphicon glyphicon-list"></span><br><font color="white">Results</font>
</button>
<button type="button" class="btn btn-warning btn-lg">
<span class="glyphicon glyphicon-eye-open"></span><br><font color="white">Visualize</font>
</button>
</div>
<br>
<hr>
<p></p>
<footer>
<p>Example</p>
</footer>
</div>
</body>
</html>
If one tries a search with this code, the code should show results, but not the way I expect.
Thanks
Probably not the solution but some hint to get there. Given this:
<ul>
<li class="collapsable"><h2>Release 3.0</h2>
<ul>
<li><h3>Allgemeine Übersicht</h3>
<p>Text ....
</li>
</ul>
</li>
....
</ul>
I do:
<script type="text/javascript">
jQuery(document).ready( function () {
jQuery('.collapsable').click(function () {
jQuery(this).children('ul').first().toggle("slow");
});
});
</script>
And
<style>
li.collapsable ul {
display: none;
}
</style>
A Click on the headline opens the <ul> and closes it again on next click (Actually, there is a lot of text in there and thus the list is very long)
Firstly add an Id to your buttons to make things a bit easier
<button id="btnSearch" type="button" class="btn btn-warning btn-lg" />
<button id="btnResult" type="button" class="btn btn-warning btn-lg" />
<button id="btnVisual" type="button" class="btn btn-warning btn-lg" />
then make sure that you have the three mark-up sections on the page wrapped inside it's own div with an Id on each div.
<div id="search">
...
</div>
<div id="result">
...
</div>
<div id="visual">
...
</div>
In your JavaScript, set-up page for the initial conditions and handle the clicks on the buttons as required. In your search and visualisation functions just show and hide the appropriate div(s) for the conditions your require using JQuery's show() and hide() functions.
It may go something like this - just tweaks this snippet as required, to suit your actual scenario.
function reset() {
$('#search').show();
$('#result').hide();
$('#visual').hide();
}
function init() {
var self = this;
// button clicks
$('#search').click(function () {
self.reset();
});
$('#results').click(function () {
self.search();
});
$('#visual').click(function () {
self.visualize();
});
}
function search() {
// Do search and set results table contents
$('#search').hide();
$('#result').show();
}
function visualize() {
// Do visualisation and set content
$('#result').hide();
$('#visual').show();
}
$(document).ready( function () {
this.reset();
this.init();
)};
You need to use toggle() It will hide element if its current status is visible and show if it is currently hidden:
$('.collapsable').click(function () {
$(this).children('ul').first().toggle();
});

Categories

Resources