JAVA: Deleting a div generated by a for loop - javascript

How do you delete a div that is generated by a for loop? I have this code that generates divs:
EDIT: I have tried the changes of #Andrew Liberio but what happened is that my applicant divs have scattered all over the place. This is the new code and the script as well. Notice how I had put the ending semicolon of the for loop in order to get put the the index in the ajax. (Not seen in the code block for some reason but it goes like this >/script> <%}%>
<% ApplicantDAO applicantDAO = new ApplicantDAO();%>
<% for (int i = 0; i < applicantDAO.viewApplicant().size(); i++) {%>
<div class="column">
<div class="col-sm-3 col-xs-4">
<div class="list-group">
<a class="list-group-item active">
<img src = "th_1x1.jpg" class = "img-responsive" alt = "Responsive Image" width = "100%" height ="100">
<h4 class="list-group-item-heading" id="guardName<%=+i%>" id="guardName<%=+i%>"><%=applicantDAO.viewApplicant().get(i).getApplicantFirstName() + " "%>
<%=applicantDAO.viewApplicant().get(i).getApplicantLastName()%></h4>
</a>
<a class="list-group-item">
<p class="list-group-item-text" id="applyingFor<%=+i%>" id="applyingFor<%=+i%>"><%=applicantDAO.viewApplicant().get(i).getApplyingFor()%></p>
</a>
<a class="list-group-item" data-toggle="modal" href="#moreDetails<%=+i%>">
<button class="btn btn-primary btn-lg btn-block" id="moreDetails">More Details</button>
</a>
<a class="list-group-item">
<button type="button" class="btn btn-default" aria-label="Left Align">
<span class="glyphicon glyphicon-ok" aria-hidden="true"></span>
</button>
<button type="button" class="btn btn-default" aria-label="Left Align">
<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
</button>
</a>
<script>
$(".delete").on("click", function () {
var id = $(this).attr("delete<%=applicantDAO.viewApplicant().get(i).getApplicantID()%>"); //get the id of the row
$.post("url_to_servlet_responsible_to_exclude_item", {
tId: id,
someOtherData: "anyData"
}).done(function () {
//if everything went ok,
//delete the div
$("div#" + id).remove();
});
})
</script>
But I dont know how to delete it at the same time delete it at the database. I use a jsp and servlet. This is my code for delete:
public boolean rejectApplicant(Applicant RejectedApplicant) {
try {
DBConnectionFactory myFactory = DBConnectionFactory.getInstance();
Connection conn = myFactory.getConnection();
String query = "delete from applicant where applicantID = ?";
PreparedStatement pstmt = conn.prepareStatement(query);
int rows = pstmt.executeUpdate();
conn.close();
pstmt.close();
return true;
} catch (SQLException ex) {
Logger.getLogger(ApplicantDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
I think that the same logic applies when transferring the values of the div to the database. The page is an applicant page where applicants are screened then if they do not pass, they will be removed and when they are accepted, the values will be passed to the database. Please suggest on what should I do. I already searched javascript and jquery but I just dont understand the terms like nodes etc. Any help or leads would be appreciated. Thank you!

You could pass an id to each div or/and to each button as #LAROmega suggested.
<div class="column" id="<%=applicantDAO.viewApplicant().get(i).getApplicantId()">
<div class="col-sm-3 col-xs-4">
...
<button type="button" class="btn btn-default delete" aria-label="Left Align" id="<%=applicantDAO.viewApplicant().get(i).getApplicantId()">
<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
</button>
Then, you could use this script to delete the row using AJAX.
$(".delete").on("click", function(){
var id = $(this).attr("id"); //get the id of the row
$.post("url_to_servlet_responsible_to_exclude_item", {
tId: id,
someOthetData: "anyData"
}).done(function(){
//if everything went ok,
//delete the div
$("div#" + id).remove();
});
})

First, I think you should not use the function on("click" in a loop.
You should use class delete for each button that you want to delete.
<button type="button" class="btn btn-default delete" data-id="<%=applicantDAO.viewApplicant().get(i).getApplicantID()%>" aria-label="Left Align">
<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
</button>
Outside of the loop, you call function on click
$(".delete").on("click", function () {
var id = $(this).attr("data-id"); //get the id of the row
$.post("url_to_servlet_responsible_to_exclude_item", {
tId: id,
someOtherData: "anyData"
}).done(function () {
//if everything went ok,
//delete the div
$("div#" + id).remove();
});
})

Related

Cannot Update Bootstrap Modal Forms

I have a CRUD reminder app, and when users right click on a reminder, a context menu pops up. Options include edit, delete, etc. Each reminder has an id, and the context menu button updates based on the reminders id, and passes it to a bootstrap modal form:
JS:
//part of the context menu script
//this function is called when the user right clicks inside of any element with class task
function toggleMenuOn(e) {
if ( menuState !== 1 ) {
menuState = 1;
menu.classList.add( contextMenuActive );
}
let reminder_id = e.target.id
$.ajax({
url: '/ajax/get_reminder/',
data: {
'reminder_id': reminder_id
},
dataType: 'json',
success: function (data) {
let context_btn1 = document.getElementById("context_menu_btn1");
let reminder_pk = data.serialized_reminder.toString();
let reminder_url = "{% url 'update-reminder' 0 %}".replace(/0/, reminder_pk)
context_btn1.className = "update-reminder context-menu__link btn btn-light";
context_btn1.setAttribute('data-id', reminder_url);
change_var(reminder_url)
}
});
}
let context_btn_id = "/update_reminder/0/";
function change_var(new_name) {
context_btn_id = new_name;
}
$(document).ready(function() {
$("#context_menu_btn1").click(function () {
$(this).modalForm({formURL: context_btn_id});
});
});
HTML:
<nav id="context-menu" class="context-menu">
<ul class="context-menu__items">
<li class="context-menu__item">
<button type="button" class="context-menu__link btn btn-light" id="context_menu_btn1" data-id=""><i class="fa fa-edit"></i> Edit</button>
</li>
<li class="context-menu__item">
<button type="button" class="context-menu__link btn btn-light" id="context_menu_btn2" data-id=""><i class="fa fa-times"></i> Delete</button>
</li>
<li class="context-menu__item">
<button type="button"class="context-menu__link btn btn-light" id="context_menu_btn3" data-id=""><i class="fa fa-eye"></i> Share</button>
</li>
</ul>
</nav>
Reminder HTML:
<div>
<h3 class="ml-4">Long-Term Assignments:</h3>
<div class="events-content-section ml-4 mr-3">
{% get_reminder_id user.username as id_reminders %}
{% for reminder_id, long_term_reminder in id_reminders.items %}
<div class="task mb-2" style="display: flex;">
<button type="button" class="view-reminder btn btn-light" data-id="{% url 'view-reminder' long_term_reminder.pk %}" id="{{ reminder_id }}" style="width: 100%;">
<h4 style="float: left;">{{ long_term_reminder.title }}</h4>
</button>
</div>
{% endfor %}
</div>
</div>
As you can see, I have one navigation menu and have buttons that change data-id every time it is shown. The code works the first time, but when I go to edit another reminder it just brings up the modal form for the first reminder. For example, if I were to update a reminder named Test1, and then try to edit Test2, it would bring up the edit form form for Test1.
I think it has something to do with the code not creating a new modalForm every time context_btn_id is updated. As a reference, the code below works, but an individual button is created for each reminder.
$(".view-reminder").each(function () {
$(this).modalForm({formURL: $(this).data('id')});
});
How would I solve this issue? Any help would be appreciated!
You can add a data-id attribute for each reminder in reminders list or table and on navigation click you can get the selected reminder id.

Laravel Sessions: Why does my function load the old session?

I'm working on a shopping cart function using session. I am trying to make function that update the quantity of an item in shopping cart and reload the subtotal and the cart's items list on header of the page.The function update the session and reload the subtotal but the problem is that it reload the cart's items list with the old session's information (before i updated). I want it to get the new session's information. Could you give me any ideas how to fix this? Many thanks!
I tried js setTimeout($('#cart-button').load(),2000) to delay the function to see if it can get the new session but it's still not working.
P/s: I 've just tried to put $this->ajaxReloadCart($cart->totalQty, $this->money($cart->totalPrice), $cart->items); in subOneItem() function, it works fine but the cart list is now at the subtotal div
Here is my js function:
$('#sub-1-{{$item['item']['id']}}').click(function(){
var qty = $('#qty-{{$item['item']['id']}}').val();
var int_qty = parseInt(qty);
if(int_qty > 1){
int_qty--;
$('input#qty-{{$item['item']['id']}}').val(int_qty);
$('#sub-total').load('sub-one/{{$item['item']['id']}}');
$('#cart-button').load('reload-mini');
}
if(int_qty <= 1){
int_qty = 1;
}
});
My routes
Route::get('sub-one/{id}','PageController#subOneItem');
Route::get('reload-mini','PageController#reloadMiniCart');
and my controller functions:
-ajaxReloadCart:
public function ajaxReloadCart($totalQty, $totalPrice, $items){
echo ' <button type="button" class="btn btn-default">
<a href="view-cart">
<i class="fa fa-shopping-cart fa-lg"></i>
<div class="item-number">'
.$totalQty.
'</div>
</a>
</button>';
echo '<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<span class="caret"></span>
<span class="sr-only">Toggle Dropdown</span>
</button>';
echo ' <ul class="dropdown-menu cart-items-list" id="cart-items-list">';
foreach($items as $item){
$price = $this->money($item['item']['price']);
echo ' <li>
<div class="row" style="margin-left:0; margin-top:10px;">
<div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">
<img src="upload/product/'.$item['item']->productimg->first()->name.'" width="100" />
</div>
<div class="col-xs-8 col-sm-8 col-md-8 col-lg-8">
<div class="row">
<strong>'.$item['item']['name'].'</strong>
</div>
<div class="row">'
.$price.' X '.$item['qty'].
'</div>
</div>
</div>
</li>';
}
echo ' <li><a><strong>Subtotal:</strong> <div class="pull-right">'.$totalPrice.'</div></a></li>
<li role="separator" class="divider"></li><li>To Checkout</li></ul>';
}
-subOneItem:
public function subOneItem($id){
$product = Product::find($id);
$oldCart = Session::has('cart') ? Session::get('cart') : null;
$cart = new Cart($oldCart);
$cart->subOne($product, $id);
Session::put('cart',$cart);
$totalPrice = $this->money($cart->totalPrice);
// display mini cart and total price
echo $totalPrice;
}
-reloadMiniCart:
public function reloadMiniCart(){
$oldCart = Session::has('cart') ? Session::get('cart') : null;
$cart = new Cart($oldCart);
$this->ajaxReloadCart($cart->totalQty, $this->money($cart->totalPrice), $cart->items);
}
Try to clear the session first before you assign the new cart values to the session
with Session::forget('cart'); or clear all session with Session::flush()
then assign the new cart info to session
in your subonitem() function after
Session::put('cart',$cart);
add Session::save();
I found other way to get the cart list reloaded but i think it's not the best way.
if you guys find any other ways, please comment below. I want to find a better way.
my solution:
reload cart list every 1s
setInterval(function(){
$('#cart-button').load('reload-mini');
},1000);

Modifying a list in AngularJS

Attempting to make list items clickable without a checkbox. I want those items to to get a strike through when clicked and still have the delete option at the end. This functions properly, but I can't seem to maintain that when I try to make the items clickable. How do I need to modify this code to make it work?
<p class="lead" ng-bind="vm.list.content"></p>
<div class="list-group">
<span data-ng-repeat="item in vm.list.items|orderBy:'name'"
class="list-group-item" ng-class="{strike: item.check}">
<input type="checkbox" ng-model="item.check" ng-click="vm.cross(item)">
<a class="btn btn-default pull-right" ng-click="vm.remove(item)">
<i class="glyphicon glyphicon-trash"></i></a>
<h4 class="list-group-item-heading" ng-bind="item.name + ' - ' + item.priority"></h4>
</span>
</div>
Controllers:
function remove(item){
var removedItem = $scope.vm.list.items.indexOf(item);
$scope.vm.list.items.splice(removedItem, 1);
if (vm.list._id) {
vm.list.$update(successCallback, errorCallback);
} else {
vm.list.$save(successCallback, errorCallback);
}
function successCallback(res) {
$state.go('lists.view', {
listId: res._id
});
}
function errorCallback(res) {
vm.error = res.data.message;}
}
function cross(item){
if (vm.list._id) {
vm.list.$update(successCallback, errorCallback);
} else {
vm.list.$save(successCallback, errorCallback);
}
function successCallback(res) {
$state.go('lists.view', {
listId: res._id
});
}
function errorCallback(res) {
vm.error = res.data.message;}
}
Why not to move the checkbox behavior to the item wrapper? In this case, if click on the trash, the outer click handler will not be triggered because we stop event from further propagation.
<div class="list-group">
<span data-ng-repeat="item in vm.list.items|orderBy:'name'" class="list-group-item" ng-class="{strike: item.check}" ng-click="item.check = true; vm.cross(item)">
<a class="btn btn-default pull-right" ng-click="vm.remove(item);$event.stopPropagation();">
<i class="glyphicon glyphicon-trash"></i>
</a>
<h4 class="list-group-item-heading" ng-bind="item.name + ' - ' + item.priority"></h4>
</span>
</div>
If you want to cross/uncross item by click, you can implement a method like toggleCross and use it instead of "item.check = true" statement:
item.toggleCheck = function() {
this.check = !this.check;
}

animation when removing item from a list in angular

Given the following html:
<div class="list-group-item" ng-repeat="sd in dc.sourceDocuments.items">
<div class="btn-group pull-right" role="group">
<button type="button" data-toggle="tooltip" title="open" class="btn btn-default"><span class="fa fa-envelope-o"></span></button>
<button ng-click="dc.markComplete(sd)" type="button" data-toggle="tooltip" title="mark complete" class="btn btn-default"><span class="fa fa-check"></span></button>
</div>
The typescript method markComplete removes an item from the list after a successful post.
public markComplete(document: SourceDocument): void {
this.$service
.markComplete(document.id)
.then(() => this.remove(document));
}
public remove(document: SourceDocument): void {
var index = this.sourceDocuments.items.indexOf(document);
this.sourceDocuments.items.splice(index, 1);
this.$log.log(`removed document id: ${document.id}`);
}
Angular quite correctly and instantly removes the item from the list.
how do I animate the removal to make the item fade out using angular animate

Change class on span tag onClick inside Button tag

<button class="btn btn-primary" onclick="wavesurfer.playPause()" type="button">
<span class="glyphicon glyphicon-play"></span></button>
When I press this button I want the span class to change:
From: class="glyphicon glyphicon-play"
To: class="glyphicon glyphicon-pause"
http://jsfiddle.net/fnfNm/35/ Ive looked att this example but it doesnt have a class before it changes.
Please give me jsfiddle example.
I solved it like this:
HTML
<button class="btn btn-primary playPauseBtn" onclick="myFunction()" type="button">
<span id="playPauseSpanId" class="glyphicon glyphicon-play"></span>
</button>
Javascript
function myFunction(){
wavesurfer.playPause();
if(wavesurfer.isPlaying() == true){
document.getElementById("playPauseSpanId").className ="glyphicon glyphicon-pause"
}else {
document.getElementById("playPauseSpanId").className ="glyphicon glyphicon-play"
}
}
Here small algorithm for change class.
var playPauseBtn = document.querySelector('.playPauseBtn');
if(playPauseBtn){
var span = document.querySelector('.playPauseBtn .glyphicon');
playPauseBtn.addEventListener('click', function(){
if (span) {
if (span.classList.contains('glyphicon-play')) {
span.classList.remove('glyphicon-play');
span.classList.add('glyphicon-pause');
} else {
span.classList.remove('glyphicon-pause');
span.classList.add('glyphicon-play');
}
}
},false);
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<button class="btn btn-primary playPauseBtn" onclick="wavesurfer.playPause()" type="button">
<span class="glyphicon glyphicon-play"></span>
</button>

Categories