Update array data when clicking outside input - javascript

Cordial greetings I am developing a project in Laravel where I perform a data update in a table dynamically, this data is an array that is created by selecting an item and the function I perform is that when I click on the green button updates the data entered in the array.
But a requirement that they have asked me is that the green button is not there, that when entering the data in the input and clicking outside the input, it updates automatically. To update my data I do it this way, This is my table
<table class="table table-bordered">
<tr>
<th style="font-size: 11.7px;">Item</th>
<th style="font-size: 11.7px;">Eliminar</th>
</tr>
#foreach ($cart as $servicio)
<tr>
<td style="font-size: 11.7px;">
<input type="text"
class="form-con-lg"
value="{{$servicio->n_item}}"
id="servicio_{{$servicio->id}}">
<a class="btn-update-item btn btn-success"
data-href="{{ route('servicio_update',$servicio->id)}}"
data-id="{{$servicio->id}}">
<i class="fas fa-sync-alt"></i>
</a>
</td>
<td>
<i class="fas fa-trash-alt"></i>
</td>
</tr>
#endforeach
</table>
and this is my script where I pass the data to update my array
<script type="text/javascript">
$(document).ready(function(){
$(".btn-update-item").on('click', function(e){
e.preventDefault();
var id = $(this).data('id');
var href = $(this).data('href');
var n_item = $("#servicio_" + id).val();
swal("Good job!", "You clicked the button!", "success");
window.location.href = href + "/" + n_item;
});
});
</script>
and my controller where I update my array
//UPADTE
public function update(Servicios $servicios,$n_item){
$cart = Session::get('cart');
$cart[$servicios->id]->n_item = $n_item;
Session::put('cart', $cart);
return redirect()->route('coti_show');
}
and my route
Route::get('/servicios/update/{servicios}/{n_item?}', 'Admin\CotizacionController#update')->name('servicio_update');
I would like to know how I can do that when I enter the data in the input and click outside the input it is automatically updated, thank you for your help.

As Bravo said, a blur handler could be used, and would probably be the most straightforward. The other route would be to add a click handler to the window (or some encapsulating parent within which you want to check for clicks) and check that the Event.target.id (or some other property of your liking) does not match that of the input.
That being said, the blur handler is most likely the more straightforward solution, just presenting alternatives.

Related

Retrieve a specific row value from table HTML and submit it to PHP

I'm populating a table from my database and it looks like this :
<form name = "Form" role="form" action ="php/teilnehmen.php" method="POST">
<fieldset>
<table width="100%" class="table table-striped table-bordered table-hover" id="dataTables-example">
<thead>
<tr>
<th>ID</th>
<th>Studienfach</th>
<th>Teilnehmer/in</th>
<th>Teilnehmen</th>
</tr>
</thead>
<tbody>
//<?php php code.....
$i =0;
$sizeofstudienfaecherseperate =
count($studienfaecherseperate);
for ($i; $i < $sizeofstudienfaecherseperate; $i++) {
?>
<tr class="odd gradeX">
<td ><?php echo($i+1);?></td>
<td class="studienfach"><?php echo($studienfaecherseperate[$i]);?>
<input type="hidden" name="PARAM_STUDIENFACH" id="PARAM_STUDIENFACH"
value="<?php echo($studienfaecherseperate[$i]);?>"> </input>
</td>
<td ><?php echo($teilnehmer[$i]);?></td>
<td width="10%">
<?php if ($teilnahmestatus[$i] =="0"){ ?>
<button type="submit" class="btn btn-success use-address"
name="teilnehmern"id="teilnehmen">Teilnehmen</button>
<?php }else{?>
<button type="submit" class="btn btn-danger use-address" name="teilnahme-beenden"
id="teilnahme-beenden">Teilnahme beenden</button>
<?php }?>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</fieldset> <!-- /.table-responsive -->
the table is shown great, and my problem is when i try to submit my second column value "PARAM_STUDIENFACH" of a specific row to my php webservice. It always gives me back the last value. I know that because I'm using the same id in every row so it will be overwritten. I tried using JavaScript to return the value of the clicked row from other questions in the forum but it didn't work for me. I'm using a bootstrap table if that helps.
EDIT 1 :
Thanks to #Taplar answer I managed to find a solution to my problem. I used this JavaScript to retrieve the data and ajax to send a post request. This is the code I used :
$(".use-address").click(function() {
var item = $(this).closest("tr") // Finds the closest row <tr>
.find(".studienfach") // Gets a descendent with class="nr"
.text(); // Retrieves the text within <td>
$.ajax({
type: "POST",
dataType: "json",
url: "php/teilnehmen.php",
data: {PARAM_STUDIENFACH:item},
success: function(data){
alert(item);
},
error: function(e){
console.log(e.message);
}
});
});
my problem now is in the alert the "item" shows correctly but in my database it is saved as the following example :
item = a (shows in alert a)
item = a \n (it's saved like that in the database with spaces afeter \n)
i tried to trim the item before sending it but i got the same result
to get the item sent by ajax i'm using this line of code in :
$studienfach = null;
if(isset($_POST['PARAM_STUDIENFACH']))
$studienfach = $mysqli->real_escape_string($_POST['PARAM_STUDIENFACH']);
EDIT 2:
i managed to solve my second problem by doing this :
$pos= strpos($studienfach, "\\");
$studienfachtemp = substr($studienfach, 0,$pos);
trim($studienfachtemp);
if there is more elegent or correct way to do it ! please post it ! thank you all.
<elem1>
<elem2 class="getMe"></elem2>
<elem3></elem3>
</elem1>
Quick contextual lookup reference. Say you have a click event bound on all 'elem3' on your page. When you click it you want to get the associated 'elem2', not all of them. With the class you can contextually look this element up by doing...
//'this' being the elem3 that was clicked
$(this).closest('elem1').find('.getMe');
From the element you clicked, it will find the shared 'elem1' parent of both 'elem2' and 'elem3' and then find only the '.getMe' that belongs to that parent.
More reading material: http://learn.jquery.com/using-jquery-core/working-with-selections/

delete function delets the last record from table. js jquery.updated

I have a dynamic table which gets values from db. I have a button which onclcik runs the query to delete the record from database. Currently instead of deleteing record(which was clicked ) its deleting the last record available. I am updating from here I figure out the issue when I provide ID to the post somehow the LAST ID is being sent to the query, is there anyway I can delete the ID which was selected.please look at the code for more info
//this is how im creating dynamic table
//just for the test
function() {
});
});
<table>
<thead>
<tr>
<td>
</td>
</tr>
</thead>
<tbody id="table"></tbody>
</table>
<button type="button" id="chochk" style="display:none" class="sukuti">delete</button>
.
Perhaps you may be better listening directly on the change event of the checkbox and then get the value of the event.target afterwards? There is something wrong with the way you are getting the variable ad in your code i suspect, but without seeing how that is derived it's hard to see why.
The example below shows a simple way to get the value of a checkbox, hopefully this might lead you to the correct answer.
$('.test').on('change', function(e) {
alert(e.target.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Value of 1: <input type="checkbox" class="test" value="1" /><br />
Value of 2: <input type="checkbox" class="test" value="2" />
Instead of a checkbox, use a radio button, so the user can only select one at a time. Then in the handler for the delete button, get the value of the checked button and send that to the server.
//this is how im creating dynamic table
//just for the test
function() {
var table = document.getElementById('tablebody');
for (var i = 0; i < (test.length); i = i + 2) { //test is an array of values from db
var row = table.insertRow(-1);
var cell3 = row.insertCell(-1);
var cell1 = row.insertCell(-1);
var cell2 = row.insertCell(-1);
cell1.innerHTML = //some html span
cell2.innerHTML = //some html span
//this is the checkbox which onclick shows the button
cell3.innerHTML = '<input type="radio" name="checkbox" class="your" value="ID of current row">';
}
///this is how i am displaying a button on click and also delete function
$(document).on('click', ".your", function() {
$('#chochk').show();
});
$(".sukuti").click(function() {
var ad = $(".your:checked").val();
$.post("test.jsp", {
id: ad //ad is the ID which will delete the specifIC ID being clicked
}, function(data) { //sending a query to delete from db working good
});
});
<table>
<thead>
<tr>
<td>
</td>
</tr>
</thead>
<tbody id="table"></tbody>
</table>
<button type="button" id="chochk" style="display:none" class="sukuti">delete</button>

mapping wrong number of rows from a table in jsp in Struts2

I am working on a Struts2 application and facing a unique issue for which i need your help. The scenario is as below. I am also using Bootstrap for the same.
I have a form as below sample. In the page i can dynamically add New Rows to this form with the New button.
<form method="post" id="mainForm" action="editForm"/>
<body onload="Rows()">
<table id="mainTable" class="table table-striped table-hover table-condensed" cellspacing="0" width="100%">
<thead>
<tr>
<th>ProcessName</th>
<th>PDate</th>
<th>Description</th>
</tr>
</thead>
<tbody id="Row">
<s:iterator value="list" var="voDetails" status="rowStatus">
<tr>
<td><input size="8" value="<s:property value="processName" />"/></td>
<td><input size="8" value="<s:date name="date_dt" format="MM/dd/YYYY"/>"/> </td>
<td><input size="8" value="<s:property value="description"/>"/></td>
</tr>
</s:iterator>
</tbody>
<button type="button" class="btn btn-primary btn-xs" onclick="Save()">Save</button>
<button type="button" class="btn btn-primary btn-xs" onclick="AddNewRow()">AddNewRow</button>
<button type="button" class="btn btn-primary btn-xs" onclick="Close();">Cancel</button>
The Javascript function Save is as below
function Save()
{
document.forms[0].action = click_save_buttom';
document.forms[0].submit();
}
function AddNewRow()
{
// code to add row dynamically to the page
}
function Rows(){
rows = document.getElementById("Row").rows.length;
for (i = 0; i < rows ; i++) {
var row = document.getElementById("Row").rows[i];
row.setAttribute("rowNum", i);
//alert("ROW: " + i);
for (j = 0; j < 3; j++) {
if(document.getElementById("listSize")!=null || rows > 1)
row.cells[j].children[0].setAttribute("name", "list[" + i + "]." + names[j]);
}
}
}
When i sumbit this form the values are getting mapped to the action and Save is working properly. Save also works when i dynamically add new row to the form.
The issue is that sometimes when this page has for example 1 row and i dynamically add a new row and totally there are 2 rows in the form table. When i submit the form then additional more than 2 rows(mapped to VO's in action) are being passed to the action. These additional rows are present in the previous page which is having a similar form table from where i select a row and land on the current page. The save function is happening for these additional rows(VO's) and after save when the page re loads these additional rows appear in the table.
Not sure why this is happening. I checked the number of rows in the table by putting an alert in Save function and it shows 2 as the length before the form submission. It is after the form submission that additional rows(VO's in action) are being mapped to action.
Can you please help me resolve this issue as i am stuck with it for a very long time now.
Thanks
Vikeng
New Edit: Ok, to me it looks like your issue is how you are looping. The rows value gives you an accurate number of rows- but you are looping starting with zero until you're greater than the number of rows it returns (would be two extra... which is accurately the problem you describe) Try this instead:
for (i = 1; i = rows ; i++) {
OLD Edit: Maybe try to call your form by id instead of by form index and see if somehow the form index could be causing the issue in the browser you are working in?
document.getElementById("mainForm").action = click_save_button;
document.getElementById("mainForm").submit();
.. and make sure you correct your click_save_button typo, if it is a typo.
OLD: It is very unclear what you are doing here:
document.forms[0].action = click_save_buttom';
Do you have a code you are running in a document called 'click_save_buttom' ? I believe this adds a form action to the first form on the page... like
<form action='click_save_buttom'></form>
Also instead of using form index, its better to give the form an id. Instead of submitting a form this way:
document.forms[0].submit();
consider submitting a form by using button type=submit

Event click radio button JQuery in Sharepoint 2013

I want to hide a Sharepoint field based on radio button value. When i put my code, this doesn't work (the event on click doesn't trigger). If i don't put the code with the event, when i open my element the script works perfectly.
This is my code:
<p>
<script src="/sites/contsvil/jQuery/jquery-1.5.js">
</script><script type="text/javascript">
$(document).ready(function() {
$("input[name$='Richiesta 1']").click(function(){
var radio_value = $(this).val();
alert(radio_value);
});
var selectedValue = $("input[#name=Richiesta 1]:checked");
//alert(selectedValue.val())
if(selectedValue.val() == "No") {
$("input[Title='" + 'Data 1' + "']").closest('td.ms-formbody').closest("tr").hide();
}else {
$("input[Title='" + 'Data 1' + "']").closest('td.ms-formbody').closest("tr").show();
}
});
</script></p>
Could you help me?
Thank you very much.
Regards,
Francesco
Selecting radio buttons isn't as easy as other types on inputs on SharePoint. The following chunk of code gets all the radio buttons on a SharePoint New / Edit page and prints the label to the console.
$(":radio").each(function() {
var radioId = $(this).attr("id");
var lblText = $("label[for=\""+radioId+"\"]").text();
console.log(lblText);
});
Here is an example of attaching a click event to each radio button:
$(":radio").each(function() {
$(this).click(function() {
console.log($(this).attr("id"));
});
});
This should get you close enough to move forward. For others who wish to jump in, here is the rendered HTML for a radio input on SharePoint (ugly!):
<table cellpadding="0" cellspacing="1">
<tbody>
<tr>
<td><span class="ms-RadioText" title="Enter Choice #1"><input id="ctl00_m_g_6ccb25d5_91e9_45b3_bc48_b53a94f40a9a_ctl00_ctl05_ctl01_ctl00_ctl00_ctl04_ctl00_ctl00" type="radio" name="ctl00$m$g_6ccb25d5_91e9_45b3_bc48_b53a94f40a9a$ctl00$ctl05$ctl01$ctl00$ctl00$ctl04$ctl00$RadioButtons" value="ctl00" checked="checked"><label for="ctl00_m_g_6ccb25d5_91e9_45b3_bc48_b53a94f40a9a_ctl00_ctl05_ctl01_ctl00_ctl00_ctl04_ctl00_ctl00">Enter Choice #1</label></span>
</td>
</tr>
<tr>
<td><span class="ms-RadioText" title="Enter Choice #2"><input id="ctl00_m_g_6ccb25d5_91e9_45b3_bc48_b53a94f40a9a_ctl00_ctl05_ctl01_ctl00_ctl00_ctl04_ctl00_ctl01" type="radio" name="ctl00$m$g_6ccb25d5_91e9_45b3_bc48_b53a94f40a9a$ctl00$ctl05$ctl01$ctl00$ctl00$ctl04$ctl00$RadioButtons" value="ctl01"><label for="ctl00_m_g_6ccb25d5_91e9_45b3_bc48_b53a94f40a9a_ctl00_ctl05_ctl01_ctl00_ctl00_ctl04_ctl00_ctl01">Enter Choice #2</label></span>
</td>
</tr>
<tr>
<td><span class="ms-RadioText" title="Enter Choice #3"><input id="ctl00_m_g_6ccb25d5_91e9_45b3_bc48_b53a94f40a9a_ctl00_ctl05_ctl01_ctl00_ctl00_ctl04_ctl00_ctl02" type="radio" name="ctl00$m$g_6ccb25d5_91e9_45b3_bc48_b53a94f40a9a$ctl00$ctl05$ctl01$ctl00$ctl00$ctl04$ctl00$RadioButtons" value="ctl02"><label for="ctl00_m_g_6ccb25d5_91e9_45b3_bc48_b53a94f40a9a_ctl00_ctl05_ctl01_ctl00_ctl00_ctl04_ctl00_ctl02">Enter Choice #3</label></span>
</td>
</tr>
</tbody>
</table>
Here you go:
$("td[id='tdApproved'] input:radio[name*='ff4']").change(function(){
// do something});
"tdApproved" is the ID of the Radio button
For more information, read this article - Accessing Radio Buttons using JQuery in SharePoint

onChange triggers only once in a while

i have the following problem:
I have a table with 2 input elements. If one of them bigger than the other, the whole row is supposed to be colored accordingly to the comparison. I trigger this with an onchange event and the first time while loading the site. The procedures work fine, but the onchange event only get triggered in 1 of 4 changes.
The table statement is the following:
<div class="grid">
<table id="table" class="tableRegion w100">
<thead style="text-align:left">
<tr>
<fmt:bundle basename="res/web/ec_resources">
<td class="tableHeader">
...
</td> ...
</fmt:bundle>
</tr>
</thead>
<tbody>
<c:set var="i" value="0"/>
<c:forEach var="participation" items="${someForm.list}">
<tr id="participationRow${i}">
And in here the code for the table > tr > td:
<td class="right bottom nowrap">
<div>
<c:out value="${someForm.event.currency.code}"/>
<fmt:formatNumber maxFractionDigits="2" minFractionDigits="2" var="ovFee" value="${overallFee}" />
<c:if test="${someForm.array[i].feeDebit != 0.0}">
<spring:input class="right debit" path="array[${i}].feeDebit" maxlength="7" size="6" onchange="isPaid(${i});" />
</c:if><c:if test="${someForm.array[i].feeDebit == 0.0}">
<spring:input class="right debit" path="array[${i}].feeDebit" maxlength="7" size="6" onchange="isPaid(${i});" value="${ovFee}"/>
</c:if>
</div>
</td>
<td class="right bottom nowrap">
<div class="padT5"><c:out value="${someForm.event.currency.code}"/> <spring:input class="right paid" path="array[${i}].feePaid" maxlength="7" size="6" onchange="isPaid(${i});"/></div>
</td>
The skript being called is the following:
$(document).ready(function(){
$('#table > tbody > tr').each(function(i) {
var paid = parseFloat($(this).find('input.paid').val());
var debit = parseFloat($(this).find('input.debit').val());
if (paid == debit)
$('#participationRow'+i).addClass("green");
else if (paid > debit)
$('#participationRow'+i).addClass("yellow");
}
);
});
function isPaid(i){
var paid = parseFloat($('#participationRow'+i).find('input.paid').val());
var debit = parseFloat($('#participationRow'+i).find('input.debit').val());
if (paid == debit)
$('#participationRow'+i).addClass("green");
else if (paid > debit)
$('#participationRow'+i).addClass("yellow");
}
What is the reason for the event being triggered just once in a while? I cross-checked with jQuery and onclick. They all get only triggered once in a while. No matter if I leave by clicking away or tabbing away.
Your code lacks any definition of a trigger when this is supposed to run.
The first part (the .each() block) is only executed on $(document).ready();, which means it is executed once per page load (right after the document has finished loading.)
The isPaid() function is nothing more than a function, I don't see where it is being called as it is not present in the current code snippet.
Your code seems OK by itself, but it just lacks any form of trigger.
You would expect something like:
$("input").change(function() {
var the_row = $(this).parent().parent(); //finds the <tr> it belongs to.
var i = the_row.attr("id").replace("participationRow","");
isPaid(i);
});
There are ways to improve on this, but this is the vital key you're missing in your code.
function highlightIfPaid(i){
var paid = parseFloat($('#participationRow'+i).find('input.paid').val());
var debit = parseFloat($('#participationRow'+i).find('input.debit').val());
if (paid == debit)
$('#participationRow'+i).addClass("green");
else if (paid > debit)
$('#participationRow'+i).addClass("yellow");
}
$(document).ready(function(){
//just use jquery for binding to change event,
//my guess is that Spring doesn't have a value for i at the point and jquery is not loaded by then so $ is undefined
$('input.debit').change(function(){
//you need to get the index i based on your table structure
//I assumed this is just the index of the row
//I get this method from this other post http://stackoverflow.com/questions/1620391/find-table-row-index-using-jquery
var i = $(this).closest('tr').prevAll().length;
highlightIfPaid(i);
});
//Dry: highlight your rows on first load
$('#table > tbody > tr').each(highlightIfPaid);
});
Okay... looking a while and with the help of #kabaros und #Flater I found the following which worked:
$(document).ready(function(){
$('input.paid').change(function(){
var i = $(this).closest('tr')[0].sectionRowIndex;
isPaid(i);
});
The solution was the $('input.paid') which got triggered, rather than $('input'). And counting the row was not that easy as well, but the above code counts the rows right. Unfortunately the onchange in the input-field only triggers once in a while!

Categories

Resources