jQuery - catch row field for value in edit modal - javascript

On table row Edit button click, a form modal is opened.
I am picking that row current values so they can be default values of that form fields when modal is opened.
As I am new in jQuery I can not figure out how to pass that values in other method.
My func:
var $fruitForm = $('#edit-form')
$('.fruit_edit').on('click', function(event) {
// Get the data-id value of the modal link.
var id = $(this).data('fruit_id');
// Set the hidden input field with the id.
$('#fruit_id').val(id);
var $row = $(this).closest('tr');
// Here I am finding row value on click
var tableFruitName = $("a[data-fruit_id="+id+"]").closest("tr").find('.tableFruitName').text()
event.preventDefault();
});
// Listen for submit instead of click.
$fruitForm.on('submit', function(event) {
event.preventDefault();
// Get the values from the form.
var $form = $(this);
var id = $form.find('input[name="fruit_id"]').val();
I want for the value from upper 'onclick' to be defined in from input here
var fruitName = $('#fruitName').val(tableFruitName);
$.ajax({
type: 'PATCH',
url: '/fruit/edit',
data: JSON.stringify({
'id' : id,
'fruitName' : fruitName
}),
processData: false,
contentType: 'application/json-patch+json',
success: function () {
$("#fruit-table").load(location.href + " #fruit-table");
$('#editFruit').modal('hide');
},
error: function (xhr, status, error) {
var ErrorMessage = JSON.parse(xhr.responseText);
}
});
});
Explanation of my workflow is within comments. I don't know how to pass catched value in other method where the input is defined.
<tr>
<td class="text-center"> {{ fruit.id }} </td>
<td class="text-center tableFruitName"> {{fruit.fruitName is empty ? "N/A" : fruit.startDate }}</td>
<td class="td-actions text-center">
<a href data-toggle="modal" data-target="#editFruit" data-fruit_id="{{ fruit.id }}" class="btn btn-warning fruit_edit">
<i class="fa fa-fw fa-pencil"></i>
</a>
</td>
</tr>

Related

trigger event with dynamic elements in jQuery

function getAnnoDetailsForTeacher(){
var tcounter = 1;
$.ajax({
url:'<%=contextPath%>/show/announcementsForTeacher',
headers: {
'Authorization':'${sessionScope.token}'
},
type:'GET',
data: {
'loginId' : '${loginId}'
},
success:function(data){
$('#annoTable tbody').empty();
for(var i=0; i<data.length;i++)
{
var aid = data[i].id;
var date = data[i].date;
var subject = data[i].subject;
var details = data[i].details;
var status = data[i].status;
$('#annoTable tbody').append('<tr data-toggle="modal" data-target="#viewTAnnoModal"><td id="tCounter'+aid+'"><strong>'+tcounter+
'</strong></td><td id="tDate'+aid+'"><strong>'+date+
'</strong></td><td id="tSubject'+aid+'"><strong>'+ subject +
'</strong></td><td id="tDetails'+aid+'" class="cell expand-small-on-hover"><strong>'+ details +
'</strong></td><td><button type="button" id="tAnnoBtn'+aid+'" onclick="viewTAnno()" class="viewbtn" data-toggle="modal" data-target="#" style="display:block;">View</button>'+
'</td>'+
......+
'</tr>');
tcounter += 1;
}
$('#tnoti').empty();
$('#tnoti').css('display','block');
$('#tnoti').append(tcounter-1);
},
error:function(e){
console.log(e)
}
});
return tcounter;
}
my goal is to unbold a row when clicked on view btn (where id is dynamic:i d="tAnnoBtn'+aid+'") inside the jQuery.
Here is the unbold jQuery
$('#tAnnoForm').on('click', '.viewbtn', function() {
const fooTCounter = document.getElementById("tCounter");
fooTCounter.innerHTML = fooTCounter
.innerHTML
.replace(/<strong>/g, "")
.replace(/<\/strong>/g, "");
const fooTDate = document.getElementById("tDate");
fooTDate.innerHTML = fooTDate
.innerHTML
.replace(/<strong>/g, "")
.replace(/<\/strong>/g, "");
const fooTSubject = document.getElementById("tSubject");
fooTSubject.innerHTML = fooTSubject
.innerHTML
.replace(/<strong>/g, "")
.replace(/<\/strong>/g, "");
const fooTDetails = document.getElementById("tDetails");
fooTDetails.innerHTML = fooTDetails
.innerHTML
.replace(/<strong>/g, "")
.replace(/<\/strong>/g, "");
});
problem is every element is created dynamically with dynamic id (td cells and buttons)
so how can i input the dynamic ids inside the unbold jQuery??
like in jQuery it should go like document.getElementById("tCounter1") where 1 is concatenated with tCounter.
also in '.viewbtn', it should go like '#tAnnoBtn1' where 1 is dynamically concatenated with tAnnoBtn.
check this viewTAnno(aid) function
function viewTAnno(aid)
{
var viewed;
$.ajax({
url:'<%=contextPath%>/show/annoViewedForTeacher',
headers: {
'Authorization':'${sessionScope.token}'
},
type:'GET',
data: {
'loginId' : '${loginId}',
'anno_id' : aid
},
success:function(data){
//alert("New Announcement Added Successsfully");
console.log(data);
viewed =data;
$('#tAnnoTable').on('click', '.viewbtn', function() {
if(viewed==0){
//get closest tr > loop through tds
$(this).closest("tr").find("td:not(:last)").each(function() {
//replace text
$(this).text($(this).text().replace(/<strong>/g, "")
.replace(/<\/strong>/g, ""))
//tcounter=tcounter-1;
$.ajax({
url:'<%=contextPath%>/show/annoViewedForTeacher',
headers: {
'Authorization':'${sessionScope.token}'
},
type:'POST',
data: {
'loginId' : '${loginId}',
'anno_id' : aid
},
success:function(data){
console.log(data);
},
error:function(e){
console.log(e)
}
});
})
}
})
},
error:function(e){
console.log(e)
}
});
return viewed;
}
i want to unbold a particular row upon clicking on view so that it also changes in db just like gmail inbox. how can i do that?
You can simply iterate through your tds where view button has been clicked then using $(this).text(..) replace <strong> tag with ''
Demo Code :
$('#annoTable').on('click', '.viewbtn', function() {
//get closest tr > loop through tds
$(this).closest("tr").find("td:not(:last)").each(function() {
//replace text
$(this).text($(this).text().replace(/<strong>/g, "")
.replace(/<\/strong>/g, ""))
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="annoTable">
<tbody>
<tr data-toggle="modal" data-target="#viewTAnnoModal">
<td id="tCounter1"><strong>1</strong></td>
<td id="tDate1"><strong>0.005997001499250375</strong></td>
<td id="tSubject1"><strong>Abc</strong></td>
<td id="tDetails1" class="cell expand-small-on-hover"><strong>Somwthing..</strong></td>
<td><button type="button" id="tAnnoBtn1" onclick="viewTAnno()" class="viewbtn" data-toggle="modal" data-target="#" style="display:block;">View</button></td>
</tr>
<tr data-toggle="modal" data-target="#viewTAnnoModal">
<td id="tCounter2"><strong>2</strong></td>
<td id="tDate2"><strong>0.005997001499250375</strong></td>
<td id="tSubject2"><strong>Abc</strong></td>
<td id="tDetails2" class="cell expand-small-on-hover"><strong>Somwthing..</strong></td>
<td><button type="button" id="tAnnoBtn2" onclick="viewTAnno()" class="viewbtn" data-toggle="modal" data-target="#" style="display:block;">View</button></td>
</tr>
</tbody>
</table>

jQuery bringing back more than 1 row of data from table

I have a table, currently with 2 rows. Next to these rows I have an icon, which when clicked, brings up a dialog box, and in this dialog box is a button which when pressed, is to run a function which copies the selected item to another file
So pretend we're in my dialog box, and this is my code:
$(document).ready(function() {
$(function() {
$("#save").on("click", saveNote);
});
})
This calls the following function:
function saveNote() {
var OpenNote = $('.dlg_lineNote');
var row = jQuery(OpenNote.closest("tr"));
var cpyItem = row.find(".IPROD").text();
$('div#dialogD').data('dataIPROD', cpyItem);
jQuery.ajax({
url: 'B2BUNV400.PGM',
type: 'POST',
data: {
task: 'copyItem',
cpyItem: cpyItem
},
}).done(function(message) {
$("#saveComment").html("Saved");
});
}
My table has two rows with the following items:
row1: 97940G96058445V
row2: 32253216058445
Here is the html:
<tr class="altcol1">
<input type="hidden" name="IPRODa" value="97940G96058445V" />
<td class="" align="center"><span><a class="icon-sitemap split dlg_lineNote" href="#" id="dlg_lineNote" title="Copy item to LXF files" href=""></a></span></td>
<td align="center" class="IPROD">97940G96058445V</td>
<td class="text" align="center">PA</td>
<td class="text" align="center">F7940</td>
<td class="text" align="center">G9</td>
<td class="text" align="center">58</td>
<td class="text" align="center">44</td>
<td class="text" align="center">5</td>
<td class="text num" align="center">6.000</td>
</tr>
<tr class="altcol2">
<input type="hidden" name="IPRODa" value="32253216058445" />
<td class="" align="center"><span><a class="icon-sitemap split dlg_lineNote" href="#" id="dlg_lineNote" title="Copy item to LXF files" href=""></a></span></td>
<td align="center" class="IPROD">32253216058445</td>
<td class="text" align="center">PA</td>
<td class="text" align="center">F2253</td>
<td class="text" align="center">21</td>
<td class="text" align="center">58</td>
<td class="text" align="center">44</td>
<td class="text" align="center">5</td>
<td class="text num" align="center">6.000</td>
</tr>
This is the html for the dialog:
<div id="dialogD">
<button id="save">Copy Item</button>
</div>
This is jQuery I have to open said dialog:
$(document).ready(function() {
$('div#dialogD').dialog({ autoOpen: false, height: 250, width: 300 })
$('.dlg_lineNote').click(function(){
var OpenNote = $(this);
var row = jQuery(OpenNote.closest("tr"));
var cpyItem = row.find(".IPROD").text();
$('div#dialogD').data('dataIPROD',cpyItem);
jQuery.ajax(
{
url: 'B2BUNV400.PGM',
type: 'POST',
data: {task: 'copyItem', Item: cpyItem},
}).done(function(message)
{
$("#notetext").val(message);
$('div#dialogD').dialog('open');
});
$(document).ready(function() {
$(function() {
$("#save").on("click", saveNote);
});
})
})
And the result:
task=copyItem&cpyItem=97940G96058445V32253216058445
Notice cpyItem is actually retrieving both the item records in the table, instead of the item I have clicked when opening the dialog box
Whichever item I chose to 'save', it is pulling both rows...
I hope this makes sense
Appreciate any help in advance
Note: I do not use jquery very often
Edit: This is my updated code
<script>
jQuery(function() {
jQuery("input:submit, input[type=button], input[type=submit], button,
.button").button();
});
$(document).ready(function() {
$('div#dialogD').dialog({ autoOpen: false, height: 250, width: 300 })
$('.dlg_lineNote').click(function(){
var OpenNote = $(this);
var row = jQuery(OpenNote.closest("tr"));
var cpyItem = row.find(".IPROD").text();
$('div#dialogD').data('dataIPROD',cpyItem);
jQuery.ajax(
{
url: 'B2BUNV400.PGM',
type: 'POST',
data: {task: 'copyItem', Item: cpyItem},
}).done(function(message)
{
$("#notetext").val(message);
$('div#dialogD').dialog('open');
});
})
// var item = row.find(".IPROD").text();;
// $("#save").click({cpyItem: item} ,saveNote);
$('.dlg_lineNote').on('click', function() {
var row = $(this).closest("tr");
var cpyItem = row.find(".IPROD").text();
$('div#dialogD').data('dataIPROD', cpyItem);
});
function saveNote() {
jQuery.ajax({
url: 'B2BUNV400.PGM',
type: 'POST',
data: {
task: 'copyItem',
cpyItem: $('div#dialogD').data('dataIPROD') //get the value of the last selected row
},
}).done(function(message) {
$("#saveComment").html("Saved");
});
}
})
</script>
Your OpenNote variable is pointing to two objects as it's selecting by class and there's two td elements with that class.
You need to select the closest td with the class .dlg_lineNote to the item you choose to save.
How do you choose which item to save? I know you click the save button in your dialog but you need a way of relating that to a specific row
You could do it like this:
var row;
$('.dlg_lineNote').on('click', function() {
row = $(this).closest("tr");
});
function saveNote() {
var cpyItem = row.find(".IPROD").text();
$('div#dialogD').data('dataIPROD', cpyItem);
jQuery.ajax({
url: 'B2BUNV400.PGM',
type: 'POST',
data: {
task: 'copyItem',
cpyItem: cpyItem
},
}).done(function(message) {
$("#saveComment").html("Saved");
});
}
Currently you're selecting the fields from every row with $('.dlg_lineNote');.
What you need to do instead is identify the row which was clicked on. You can use a data-attribute on the button to hold the value from the row, as you do now (although in your current code the data attribute is redundant), but you need to change the location where you set the value to the moment when the row is clicked on (rather than the dialog button), so you can easily identify the right row:
$(document).ready(function() {
$('div#dialogD').dialog({ autoOpen: false, height: 250, width: 300 });
$('.dlg_lineNote').on('click', function() {
var row = $(this).closest("tr"); //use "this" to get the exact element clicked on. From here we can get to the exact tr, instead of selecting all of them at once.
var cpyItem = row.find(".IPROD").text();
$('div#dialogD').data('dataIPROD', cpyItem);
});
$("#save").click(saveNote);
});
function saveNote() {
jQuery.ajax({
url: 'B2BUNV400.PGM',
type: 'POST',
data: {
task: 'copyItem',
cpyItem: $('div#dialogD').data('dataIPROD'); //get the value of the last selected row
},
}).done(function(message) {
$("#saveComment").html("Saved");
});
}

Toggle Selected Table Row Highlight on Button Click

I have a simple table with a Select button for each row that when clicked calls a PHP script to update a Session Variable with the ID of the selected Item. Here's the table:
<tr class="" id="PR9215">
<td>CODE A</td>
<td>Fresh Frust</td>
<td class="text-center"><button type="button" class="btn btn-success btn-sm">Select</button></td>
</tr>
<tr class="" id="PR9594">
<td>Oranges</td>
<td>Fresh Oranges</td>
<td class="text-center"><button type="button" class="btn btn-success btn-sm">Select</button></td>
</tr>
<tr class="" id="PR9588">
<td>MANGO</td>
<td>Fresh Mango</td>
<td class="text-center"><button type="button" class="btn btn-success btn-sm">Select</button></td>
</tr>
and here's the script that it calls:
$(document).ready(function() {
$('button.btn-success').click(function() {
var itemID = $(this).closest('tr').attr('id');
// Create a reference to $(this) here:
$this = $(this);
$.post('updateSelections.php', {
itemID: itemID,
selectionType: 'yes'
}, function(data) {
data = JSON.parse(data);
if (data.error) {
var ajaxError = (data.text);
var errorAlert = 'There was an error updating your selections - ' + ajaxError + '. Please contact Support';
$this.closest('tr').addClass("warning");
$('#alert_ajax_error').html(errorAlert);
$("#alert_ajax_error").show();
return; // stop executing this function any further
} else {
console.log('update successful - success add class to table row');
$this.closest('tr').addClass("success");
$this.closest('tr').removeClass("danger");
//$(this).closest('tr').attr('class','success');
}
}).fail(function(xhr) {
var httpStatus = (xhr.status);
var ajaxError = 'There was an error updating your selections - AJAX request error. HTTP Status: ' + httpStatus + '. Please contact Support';
console.log('ajaxError: ' + ajaxError);
$this.closest('tr').addClass("warning");
$('#alert_ajax_error').html(ajaxError);
$("#alert_ajax_error").show();
});
});
});
This is working when it comes to making the initial selection - the table row is coloured green to indicate it has been selected. I now need to extend this so that when the Select button is clicked a 2nd time it then removes the green table row highlighting and returns it to it's original state.
Now sure how to go about extending the script to achieve this.
Check below logic for that:
$('button.btn-success').click(function() {
if ($this.closest('tr').hasClass("first_click")) {
$this.closest('tr').removeClass();
//$( "tr" ).removeClass();
return false;
}else{
$this.closest('tr').addClass("first_click");
}
You chould achieve that by using a boolean to track the state of the button. Then check the state of the button before taking action.
Ps. You can chain your addClass() and removeClass() methods.
var buttonSelected = false;
if(buttonSelected){
$this.closest('tr').addClass("success").removeClass("danger");
buttonSelected = true;
} else {
$this.closest('tr').removeClass("success").addClass("danger");
buttonSelected = false;
}

After prepend, set value as input javascript then process values in php script

I am using script to print selected values from table into another div.
<script>
$(".addValues").click(function () {
$('#selection').show();
var $this = $(this),
myCol = $this.closest("td"),
myRow = myCol.closest("tr"),
targetArea = $("#selection");
var qte_input = ('<input type="text" name="kolicina" id="kolicina" placeholder="kg / m" size="10"/>');
var broj = ($("td.data-id", myRow).text());
targetArea.prepend(broj + qte_input +"<hr />");
var arr = { sifra:broj, kolicina:qte_input };
$.ajax({
url: 'script.php',
data: arr,
type: 'post',
});
});
</script>
I am trying to get selected values in script.php, multiple values will be selected and after each selection I need to type quantity that is var qte_input.
Could anyone tell me how to set var broj as input and in the same time print it to another div as selected?
html code
<table id="datatable" class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>-</th>
</tr>
</thead>
<tbody>
<?php while($r=$q->fetch()){ ?>
<tr>
<td class='data-id'><?=''. $r['Id']?> </td>
<td> <button class="addValues" value="<?=''. $r['Id']?>"><i class="ion-ios-cart-outline"></button></td>
</tr>
<?php } ?>
</tbody>
</table>
Once I click on button one value prints in div. Multiple values could be selected as displayed on the image. Once I finish selection I hit button "PoĊĦalji zahtjev" it should pick up all
You should write a function which collect you all data from the table. After that this collection should be sent to you backend via ajax. Demo in this fiddle: https://jsfiddle.net/mgrem9gb/
/**
* Function collect the form data
*/
function collectData(container){
var data = [];
$(container).find('tbody').find('tr').each(function(index, item){
var rowData = {
id: $(item).find('td.data-id').text(),
value: $(item).find('input[name="kolicina"]').val()
};
data.push(rowData);
});
return data;
}
/**
* Excecute the data collect function and the ajax post
*/
$.ajax({
url: 'script.php',
data: collectData('#datatable'),
type: 'post',
});

Identifying a Specific Button when Submitting AjaxForm(s)

I'm using Django and AjaxForm to submit a form(s) that adds an item to a user's "cart". I have multiple items listed on the page, each with it's own "add to cart" button. Upon clicking a specific "add to cart" button, I use Ajax to add the item to the user's "cart" and display it in their "cart" at the top of the screen. Users can also delete an item from their cart by clicking on a given item in the cart.
I would now like to change the appearance of the "add to cart" button once it has been clicked, but I am having trouble identifying only the specific button that was clicked (and not all of the 'add to cart' buttons). How can I identify which 'add to cart' button was clicked. I added an 'id' field to my html button and have been trying to use that but have been unsuccessful....??
I have tried many different things but either they are not working or I am putting them in the wrong spot. For example, I have tried:
$('.add-to-cart').on('click',function(){
var id = $(this).attr("id");
console.log("ID: ");
console.log(id);
});
And also:
var addButtonID;
$(this).find('input[type=submit]').click(function() {
addButtonId = this.id;
console.log("ID: ");
console.log(addButtonId)
)};
Any ideas on how I can find the specifc button that was clicked so I can update the button's appearance???
My html:
{% for item in item_list %}
<form class="add-to-cart" action="/item/add/{{ item.id }}/" method="post" enctype="application/x-www-form-urlencoded">
<ul>
<li style="display: block"><button class="addItemButton2" type="submit" id="{{ item.id }}">Add to Cart</button></li>
</ul>
</form>
{% endfor %}
My javascript:
function remove_form_errors() {
$('.errorlist').remove();
}
function show_hide_cart(){
var cart = $('#cart');
var message = $('#message');
if (cart.find('li').length >= 1){
cart.show();
continueButton.show();
message.hide();
}
else {
cart.hide();
continueButton.hide();
message.show();
}
}
function process_form_errors(json, form)
{
remove_form_errors();
var prefix = form.data('prefix'),
errors = json.errors;
if (errors.__all__ !== undefined) {
form.append(errors.__all__);
}
prefix === undefined ? prefix = '' : prefix += '-';
for (field in errors)
{
$('#id_' + prefix + field).after(errors[field])
.parents('.control-group:first').addClass('error');
}
}
function assign_remove_from_cart() {
var cart = $('#cart');
$('.remove-from-cart').on('click', function(e) {
e.preventDefault();
$.get(this.href, function(json) {
remove_form_errors();
cart.find('a[href$="' + json.slug + '/"]').parent('li').remove();
show_hide_cart();
});
});
}
(function($){
$(function() {
var cart = $('#cart'),
message = $('#message');
continueButton = $('#continueButton');
assign_remove_from_cart();
// ajax-enable the "add to cart" form
$('.add-to-cart').ajaxForm({
dataType: 'json',
url: this.action,
success: function(json, status, xhr, form) {
if (json.errors !== undefined) {
// display error message(s)
process_form_errors(json, form);
}
else if(json.id == -1){
// duplicate, do nothing
console.log("json.id:%s:json.slug:%s", json.id, json.slug)
}
else {
// Hide any previously displayed errors
remove_form_errors();
// compile cart item template and append to cart
var t = _.template($('#cart-item-template').html());
$('#cart').append(t(json));
show_hide_cart();
assign_remove_from_cart();
}
}
});
});
})(jQuery);
Based on your comments, you ought to be able to drop your onClick function into a script tag at the end of your HTML page and have it function as intended (though your javascript should actually all be in a separate file that gets referenced via a script tag).
$( document ).ready(function(){
$('.add-to-cart :submit').on('click',function(){
var id = this.id;
console.log("ID: ",id);
//do something with your ID here, such as calling a method to restyle your button
$('#' + id).css("attribute","new value");
//or
$('#' + id).addClass("yourClassName");
});
});
Change the button type to 'button', and then add onClick="addToCartFunction(this);"
then in the addToCarFunction, this.id will be your item id your adding?, or you can use data-attributes to add more item details for the function to get.
if you then need to send information to the server to cache the cart, use a $.ajax jQuery call to the server.

Categories

Resources