How to delete a row based on its index? - javascript

I want to delete a selected row using jQuery. First, while clicking add button, rows are added dynamically with a delete button. Now I want to delete the selected row.
I am using the following code to add rows dynamically:
$("#btnAdd").on('click', function (){
$('#Time tr').last().after('<tr><td><span style="font-size:14px;">Diplamo/Certificate :</span><input type="textbox" input id="addedValue12" name = "Certificate"></td><td><span style="font-size:14px;">Percentage :</span><input type="textbox" id="addedValue123" name = "CertificatePer"></td></tr>');
});
<input id="btnAdd" type="button" value="add" />
<table id="Time">
<tr>
</tr>
</table>
I am displaying values in a JSP page.
<c:forEach var="var1" items="${empedu.empCertificate}">
Certificate Name:<input value="${var1.certification}" name="Certificate" type="text" title="Only Text Allowed" pattern="[a-zA-Z\s'.,#:&?!()$#/\\]+" />
Percentage: <input value="${var1.percentage}" name="CertificatePer" style="width: 100px;" type="text" max="100" />
<input type="button" id="deleteRow" name="delete" value="delete" /><br/>
</c:forEach>
It is displayed on screen like this:
Here, If I click the third row, I want to delete the third row. How can I do this?

$("#Time").on("click", ".delete", function(){
$(this).closest("tr").remove();
});
Assuming delete is the class of the delete button. I have used .on as the rows and thus delete buttons are dynamically added.
This is picking the closest tr from the clicked delete button, and removing it.
Working Fiddle

1st: Id must be unique so don't use id for more than one element .. use class instead
2nd: while you append rows you need to jQuery event delegation ...
$('#Time').on('click' , '.delete' , function(){
// change .delete_btn with your delete btn class
$(this).closest('tr').remove();
});

Related

How to use checked input values used for math as part of cloned div elements

I have written a script that clones a certain div as required by the user. Within the div there are three checkbox input options and each option as a numeric value. I want the script to allow the user to select a checkbox and then the value will be reflected in another input space and each value that are added will be separated by a comma.
The tricky part is that it should be done for each clone, and that each checkbox has the same class name to which the script should be written. I realize that using unique id's would be better, but I would like it that a for loop could do it for any number of checkboxes under the specific class.
Here is the html script:
<style>
.hidden {
display: none;
}
</style>
<body>
<h2>Test</h2>
<button id="add">Add</button>
<div class="test hidden">
<div class="user_input1">
<label>Input1</label>
<input class="input1" type="text" required>
<label>Input2</label>
<input type="text" name="value2" required>
<div class="user_input2">
<table>
<thead>
<tr>
<th>Pick Option</th>
</tr>
</thead>
<tbody>
<tr id="append">
<td><input class="test" type="checkbox" name="test" value="1">Test1</td>
<td><input class="test" type="checkbox" name="test" value="2">Test2</td>
<td><input class="test" type="checkbox" name="test" value="3">Test3</td>
</tr>
</tbody>
</table>
<input type="text" id="insert" name="check">
<button class="hidden" id="testbtn">Calc</button>
</div>
</div>
</div>
<form action="server/server.php" method="POST">
<div class="paste">
</div>
<button type="submit" name="insert_res">Submit</button>
</form>
</body>
And my attempt for the jQuery:
$(document).ready(function() {
var variable = 0
$("#add").click(function() {
var element = $(".test.hidden").clone(true);
element.removeClass("hidden").appendTo(".paste:last");
});
});
$(document).ready(function(event) {
$(".test").keyup(function(){
if ($(".test").is(":checked")) {
var test = $(".test").val();
};
$("#insert").val(test);
});
$("#testbtn").click(function() {
$(".test").keyup();
});
});
I think a for loop should be used for each checkbox element and this to specify each individual clone, but I have no idea where or how to do this. Please help!
I am assuming you already know how to get a reference to the dom element you need in order to append, as well as how to create elements and append them.
You are right in that you can loop over your dataset and produce dom elements with unique id's so you can later refer to them when transferring new values into your input.
...forEach((obj, index) => {
(produce tr dom element here)
(produce three inputs, give all unique-identifier)
oneOfThreeInputs.setAttribute('unique-identifier', index); // can set to whatever you want, really
(proceed to creating your inputs and appending them to the tr dom element)
targetInputDomElementChild.setAttribute('id', `unique-input-${index}`); // same here, doesn't have to be class
});
Observe that I am using template strings to concat the index number value to the rest of the strings. From then on, you can either reference the index to refer to the correct input or tr using jquery in your keyUp event handler:
function keyUpEventHandler($event) {
const index = $(this).attr('unique-identifier');
const targetInput = $(`#unique-input-${index}`)
// do stuff with targetInput
}
I have created a fiddle to show you the route you can take using the above information:
http://jsfiddle.net/zApv4/48/
Notice that when you click an checkbox, in the console you will see the variable number that designates that set of checkboxes. You can use that specific number to get the input you need to add to and concat the values.
Of course, you still need to validate whether it is being checked or unchecked to you can remove from the input.

How can I target EVERY link and button on the page?

I have a shopping cart that contains a form field and a checkbox in each row. The form field controls the quantity, which can be edited, if the customer wants to modify the quantity of the product they order, and the checkbox selects the item, either to toss the item in a wish list, or to remove it. The Add To Wish list and Remove Functions are separated out of this particular question.
What, I am looking at doing, is detecting when the form has been changed, and then targeting EVERY anchor tag and button on the page, so if the items have been modified, the script stops the click through and pops up a bootstrap modal, alerting the user that something in their cart has been modified.
HTML (the shopping cart row, run through a JSTL forEach loop, but the markup is this):
<table>
<form id="shoppingCart" action="updateTheCart.action">
<c:forEach var="item" items="${shoppingCart.items}" varStatus="status">
<tr class="cart-row">
<td class="remove" data-label="Remove">
<label>
<input type="checkbox" name="removeFlag(<c:out value="${status.count}"/>)" value="true"/>
</label>
</td>
<td class="title" data-label="Title">
${item.value.sellableGood.name}
</td>
<td class="qty" data-label="Quantity">
<input type="num" class="form-control qty-input" name="quantity(<c:out value="${status.count}" />)" value="<c:out value="${item.value.quantity}" />"/>
</td>
<td class="subtotal" data-label="Line Total">
<fmt:formatNumber type="currency" pattern="$#,##0.00" value="${item.value.itemExtendedTotal}" />
</td>
</tr>
</c:foreach>
</table>
<p>Checkout</p>
<p><button type="submit" id="checkout">Update Cart</button></p>
<p><button id="addToWishlist" type="submit" id="wish-list">Add To Wish List</button></p>
<p>Chontinue Shopping</p>
</form>
JS:
$("#shoppingCart :input").change(function() {
$("#shoppingCart").data("changed",true);
});
I know I am missing a LOT, but I really don't know where to begin at this point.
You can try the onbeforeunload Event
$('input').change(function() {
if( $(this).val() != "" )
window.onbeforeunload = "Are you sure you want to leave?";
});
Javascript:
;[].forEach.call(document.querySelectorAll('a, button'), function(element) {
//do something with buttons and links, for example:
element.setAttribute('data-changed', true')
});
The jquery equivalent is:
$('a, button').each(function(element) {})
To watch the form for changes, I would use the blur event, it's the reverse of focus:
;[].forEach.call(document.querySelectorAll('#myForm input'), function(element) {
element.addEventListener('blur', function(event) {
//something has changed
})
});
Jquery:
$('#myForm input').on('blur', function(event) {})

Access sibling variable of text-field

I have a simple form, just a single text field containing a email from a MySQL database. The user has 2 buttons one can completely update the email with what they replace it with or they can choose to return the email to a default state i.e. the original email. It all works OK if you have the 2 buttons immediately 'in-situ' with the relevant text-field. But if you put the 'reset' button in a separate table cell, the 'onlick' set-email-back-to-default function stops working, and I don't understand how to fix it.
It will work like this because the reset button is slap-bang next to the text field:
<input name="cc_email" type="text" value="<?php echo !empty($_SESSION["cc-email"]) ? $_SESSION["cc-email"] : $_SESSION['admin_username'];?>" />
<input id="reset-cc" name="add" type="button" value="Set to default" />
Here's the JavaScript:
$(document).ready(function() {
$('#reset-cc').click(function() {
$(this).siblings('input[name="cc_email"]').val('<?php echo $_SESSION['admin_username'] ?>');
$('#update_cc').submit();
return false;
});
But if I place the reset button in a separate table cell as follows the function ceases to work as if it can no longer access the text field:
<td>
<input name="cc_email" type="text" value="<?php echo !empty($_SESSION["cc-email"]) ? $_SESSION["cc-email"] : $_SESSION['admin_username'];?>" />
</td>
<td>
<input id="reset-cc" name="add" type="button" value="Set to default" />
</td>
I assume I need to modify the JavaScript so it can still access the text field even though it is now separated by a table-cell but I don't know how to do it.
Your problem lies here:
$(this).siblings('input[name="cc_email"]')
By moving the input button into a different TD it is no longer a sibling (as the other answers have indicated). You may want to just give the button an ID and reference it that way:
//this bit |
// v
<input id="cc_email" name="cc_email" type="text" value="<?php echo !empty($_SESSION["cc-email"]) ? $_SESSION["cc-email"] : $_SESSION['admin_username'];?>" />
//...
$("#cc_email")...
Which will be easier than making convoluted parent/find calls. This button is unique, is it not?
The .siblings() function searches in a collection of siblings within the same parent. If you put them into different parents then they are not siblings. Try replacing it with something like:
$(this).parent().prev().find('input[name="cc_email"]').val('<?php echo $_SESSION['admin_username'] ?>');
If the input will always be in the same tr as the button, search for the input field within the row:
$('#reset-cc').click(function() {
$(this).closest('tr').find('input[name="cc_email"]').val('original#example.com');
$('#update_cc').submit();
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tr>
<td>
<input name="cc_email" type="text" value="loaded#example.com" />
</td>
<td>
<input id="reset-cc" name="add" type="button" value="Set to default" />
</td>
</tr>
</table>

jQuery, javascript: several forms same submit button text - how to determine value of closest hidden value box

I have several forms in HTML, each with a submit button and a hidden field. The same javascript function is called when any of the submit buttons are pushed. I want to know which submit button has been pushed. I think I can do this by finding out what the hidden field value is of the corresponding form - but I'm having difficulty with this. My HTML is:
<div id="existingPhotosList">
<table><tbody><tr><td>
<img src="./userPictures/IMG0001.jpg">
</td>
<td>
<form class="deleteFiles">
<input type="hidden" name="picture" value="IMG0001.jpg">
<input type="submit" name="deleteFile" value="Delete File">
</form>
</td>
</tr>
<tr>
<td>
<img src="./userPictures/IMG0002.jpg">
</td>
<td>
<form class="deleteFiles">
<input type="hidden" name="picture" value="IMG0002.jpg">
<input type="submit" name="deleteFile" value="Delete File">
</form>
</td>
</tr>
</tbody>
</table>
</div>
There may be more or less table rows with images and forms on them - depending on how many images are found on the server.
The javascript I have right now is:
$('.deleteFiles').submit(deleteFile);
function deleteFile() {
var myValue = $(this).parent().closest(".picture").val();
alert(myValue);
return false;
}
I'm currently getting undefined as the result of the alert.
I want to know which submit button has been pushed.
As each of your forms only has one submit, you don't have to change your code much.
this in your submit handler will refer to the form, and the element is within the form, so:
var myValue = $(this).find("input[name=picture]").val();
No need to go up to the parent, and closest goes up the ancestry (through ancestors), not down. find goes down (descendants).
the simplest way I think will be:
var myValue = $('input[name=picture]', this).val();
should be:
var myValue = $(this).closest(".deleteFiles").find("input[type=hidden]").val();
here is the demo http://jsfiddle.net/symonsarwar/963aV/
$('.deleteFiles').click(deleteFile);
function deleteFile() {
var me=$(this).closest('tr').find('td:eq(1) input').val();
alert(me)
}

How get get dynamically generated value

The following contain dynamic values
<c:forEach items="${allUserList}" var="eachUser">
<span class="name"> ${eachUser.getUserName()} <span>
<select class="role">
<c:forEach items="${roleList}" var="eachRole">
<option value="${eachRole.getRoleName()}">${eachRole.getRoleName()}</option>
</c:forEach>
</select>
<input type="button" class="add" value="add" />
</c:forEach>
When i click on add button i should see corresponding name, selected role in a alert box (e.g {jack, admin})
How to do this??
Using the class attribute of the button as a selector, you can use the .prev function to find the <select> element preceding the button:
$(".add").on("click", function() {
alert($(this).prev(".role").val()); // Role
alert($(this).prevAll(".name").text()); // Name
});
You don't need event delegation in this instance, as JSP will generate this code before it reaches the client.

Categories