Jquery closest input in dynamic table - javascript

I am a beginner in Jquery and Rails.
I am trying to fetch data from rails controller and set the same to text fields located in Dynamic table.
HTML
<tbody id="template">
<tr>
<td>
<select name="order[order_placed][][itemname]" id="order_place_id" class="form-control delete-comment" style="width: 300px">
<option value=""></option>
<% Item.all.each do |item| %>
<option value="<%= item.item_name %>">
<%= item.item_name %>
</option>
<% end %>
</select>
</td>
<td><input name="order[order_placed][][quantity]" type="text" size='10' class="form-control" /></td>
<td><input name="order[order_placed][][unitprice]" type="text" size='10' class="form-control" /></td>
<td><input name="order[order_placed][][tax]" type="text" size='10' class="form-control"/></td>
<td><input name="order[order_placed][][discount]" type="text" size='10' class="form-control"/></td>
<td><input name="order[order_placed][][itemtotalprice]" type="text" size='10' class="form-control" /></td>
<td>
<button type="button" class="btn btn-default btn-sm sub" onClick="$(this).closest('tr').remove();">
<span class="glyphicon glyphicon-minus"></span>
</button>
</td>
</tr>
</tbody>
JS
$(document).on('change', 'select', function() { //var url = $('.delete-comment').attr('data-url');
$.ajax({
url: "/items/getdata",
type: 'get',
data: {data_value: $(this).val()},
dataType: 'json',
success: function (data) { $(this).closest('tr').next('td').next('td').next('td').find('input[name="order[order_placed][][unitprice]"]').val(data.unit_price);
$('input[name="order[order_placed][][tax]"]').val(data.tax);
$('input[name="order[order_placed][][discount]"]').val(data.discount);
}, error: function () {
alert('error');
}
});
});
Data is fetched properly and is set to the text boxes if we assign them directly(data.tax and data.discount are set properly).
As the table is dynamic, i am trying to put data by finding the closest tr element followed by next td(Select element) again next td(Quantity) again next td(Unit Price). [This is the text field i wanted to place data.]
But this is not working properly.
Can some one please help.
Advance Thanks...!!!

this doesn't refers to current element the success callback, thus $(this) will not work.
You can cache the reference of TR in a variable which can be used is the success callback
$(document).on('change', 'select', function() { //var url = $('.delete-comment').attr('data-url');
//Keep a reference of current element
var tr = $(this).closest('tr');
$.ajax({
...
success: function(data) {
tr.find('input[name="order[order_placed][][unitprice]"]').val(data.unit_price);
tr.find('input[name="order[order_placed][][tax]"]').val(data.tax);
tr.find('input[name="order[order_placed][][discount]"]').val(data.discount);
},
});
});
OR, You can set context option of $.ajax()
$(document).on('change', 'select', function() {
$.ajax({
...
context: $(this).closest('tr'), // Set context to TR
success: function(data) {
$(this).find('input[name="order[order_placed][][unitprice]"]').val(data.unit_price);
$(this).find('input[name="order[order_placed][][tax]"]').val(data.tax);
$(this).find('input[name="order[order_placed][][discount]"]').val(data.discount);
},
});
});

Related

SelectPicker adding options dynamically depend input value

Morning,
I'm trying to create a table with dropdown (selectpicker A) fill dynamically with data selected with result of other input (selectpicker B) not into this table.
Filling (SelectPicker A) its OK for first row of table after selected value into SelectPicker B.
But when i add new line (by clone), SelectPicker A is empty for second row.
Need your help, thks !
My view code :
<select class="form-control selectpicker" name="nc_A" id="nc_A" onchange="select_B(this)" type="string" required>
<option disabled> </option>
</select>
...
<table id="sub_table" class="table">
<thead">
<tr>
<th>{{__('test.B')}}</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<select class="form-control" name="nc_B[]" id="nc_B" type="string" required>
<option> </option>
</select>
</td>
</tr>
</tbody>
</table>
<i class="btn" onclick="add_row()">{{" + ".__('home.ajoutligne')}}</i>
My Jquery code :
var clonednc = $("#sub_table tbody tr:first").clone()
$("select[name*=nc_B]").selectpicker()
function add_row() {
$(clonednc).find("input").val("")
$("<tr>" + $(clonednc).html() + "</tr>").appendTo($("#sub_table tbody"))
$("#sub_table tbody tr:last select").selectpicker()
}
function select_B(e)
{
var selectionA = e.value;
$.ajax({
type: "POST",
url: "/production/selectionB",
data: {_token: CSRF_TOKEN, ncA : selectionA },
dataType: "JSON",
success: function (data) {
$(e).parents('div').find('#nc_B').empty();
$.each(data, function(key,value){
$(e).parents('div').find('#nc_B').append('<option value="'+value.NumB+'">'+ value.NumB +'</option>');
});
$("select[name*=nc_B]").selectpicker('refresh');
}
});
}

How to render the AJAX response in the JSP/HTML element (returned from db)

enter image description hereenter image description hereHow to render a ajax response from db (map) in jsp screen
I am getting response in browser console but not sure how to render it in jsp on the browser screen like a table or any better suggestion
$('#submit_btn').click(function(){
var problemId = $('#search_data').val();
$.ajax({
type: "GET",
dataType : "json",
url : "http://localhost:8080/bugs/" + bugId,
success: function(data){
$("#response").html(data);
console.log('response data',data);
},
error : function(err){
console.log('error',err)
}
});
});
JSP
<body>
<div>
<div>
<h1>Lookup from Oracle database</h1>
Click on this <strong>link</strong> to visit home page.
</div>
<div>
<h2>${message}</h2>
<table>
<tr>
<td>Search Category:</td>
<td>
<select name="searchcategories">
<option value="-1">-Select Category-</option>
<option value="bug">bug</option>
<option value="attachment">attachment</option>
</select>
</td>
</tr>
<tr>
<td>Entity Id:</td>
<td><input type="text" name="bugId" id="search_data" class="form-control" placeholder="Search bug no..">
</td>
</tr>
<tr>
<td></td>
<td><button type="button" id="submit_btn" onclick="">Search</button>
</td>
</tr>
<tr>
<td>Bug Id:</td>
<td><input type="text" id="bugId" class="form-control">
</td>
</tr>
<tr>
<td>Prob State Name:</td>
<td><input type="text" id="probStateName" class="form-control">
</td>
</tr>
<tr>
<td>Priority Name:</td>
<td><input type="text" id="priorityName" class="form-control">
</td>
</tr>
</div>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
});
$('#submit_btn').click(function(){
var bugId = $('#search_data').val();
$.ajax({
type: "GET",
dataType : "json",
url : "http://localhost:8080/bugs/" + bugId,
success: function(data){
$("#response").html(data);
console.log('response data',data);
var bugDetails = data;
renderDetails(data);
},
error : function(err){
console.log('error',err)
}
});
});
function renderDetails(data)
{
var id = document.getElementById("bugId");
var name = document.getElementById("probStateName");
var priority = document.getElementById("priorityName");
id.innerHTML = data.bugId;
name.innerHTML = data.probStateName;
priority.innerHTML = data.priorityName;
};
</script>
</html>
below is the response object that I see in console that has data fetched from backend. I want to render this ajax response below the search box
[Log] response data (oracle-lookup, line 65)
Object
data: {bugId: 298, stateCode: "2", …}
Object Prototype
You can populate data to any field from the following code. Probably best to also add a check to see whether the returned values are not empty.
<script type="text/javascript">
var bugDetails;
$(document).ready(function(){
$("#submit_btn").click(function(event){
event.preventDefault();
var bugId = document.getElementById("search_data").value;
$.ajax({
type: 'GET',
url: "http://localhost:8080/bugs/" + bugId,
dataType: 'json',
success: function(data, textStatus, jqXHR) {
bugDetails = data;
renderDetails(bugDetails);
alert(data);
alert(jqXHR.status);
alert(textStatus);
},
error: function(jqXHR, textStatus, errorThrown) {
alert(textStatus);
alert(jqXHR.status);
alert(errorThrown);
}
});
});
});
function renderDetails(bugs)
{
var id = document.getElementById("problemId");
var name = document.getElementById("probStateName");
var priority = document.getElementById("priorityName");
id.value = bugs.bugId;
name.value = bugs.probStateName;
priority.value = bugs.priorityName;
};
</script>
So now your code should be like this,
<body>
<div>
<div>
<h1>Lookup from Oracle database</h1>
Click on this <strong>link</strong> to visit home page.
</div>
<div>
<h2>${message}</h2>
<table>
<tr>
<td>Search Category:</td>
<td>
<select name="searchcategories">
<option value="-1">-Select Category-</option>
<option value="bug">bug</option>
<option value="attachment">attachment</option>
</select>
</td>
</tr>
<tr>
<td>Entity Id:</td>
<td><input type="text" name="bugId" id="search_data" class="form-control" placeholder="Search bug no..">
</td>
</tr>
<tr>
<td></td>
<td><button type="button" id="submit_btn">Search</button>
</td>
</tr>
<tr>
<td>Bug Id:</td>
<td><input type="text" id="problemId" class="form-control">
</td>
</tr>
<tr>
<td>Prob State Name:</td>
<td><input type="text" id="probStateName" class="form-control">
</td>
</tr>
<tr>
<td>Priority Name:</td>
<td><input type="text" id="priorityName" class="form-control">
</td>
</tr>
</div>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
var bugDetails;
$(document).ready(function(){
$("#submit_btn").click(function(event){
event.preventDefault();
var bugId = document.getElementById("search_data").value;
$.ajax({
type: 'GET',
url: "http://localhost:8080/bugs/" + bugId,
dataType: 'json',
success: function(data, textStatus, jqXHR) {
bugDetails = data;
renderDetails(bugDetails);
alert(data);
alert(jqXHR.status);
alert(textStatus);
},
error: function(jqXHR, textStatus, errorThrown) {
alert(textStatus);
alert(jqXHR.status);
alert(errorThrown);
}
});
});
});
function renderDetails(bugs)
{
var id = document.getElementById("problemId");
var name = document.getElementById("probStateName");
var priority = document.getElementById("priorityName");
id.value = bugs.bugId;
name.value = bugs.probStateName;
priority.value = bugs.priorityName;
};
</script>
</html>
I have created Text Fields to fetch the data coming from AJAX call. Make sure you are using these ids.
<tr>
<td>Bug Id:</td>
<td><input type="text" id="problemId" class="form-control">
</td>
</tr>
<tr>
<td>Prob State Name:</td>
<td><input type="text" id="probStateName" class="form-control">
</td>
</tr>
<tr>
<td>Priority Name:</td>
<td><input type="text" id="priorityName" class="form-control">
</td>
</tr>
And when data comes from the AJAX call it will fetch to above fields using this method,
function renderDetails(bugs)
{
var id = document.getElementById("problemId");
var name = document.getElementById("probStateName");
var priority = document.getElementById("priorityName");
id.value = bugs.bugId;
name.value = bugs.probStateName;
priority.value = bugs.priorityName;
};
So what you need to care about is make sure text field ids are correct.

jQuery.ajax - Updating a table cell with new value

Good evening. The code below is intended to update a couple of table cells with a new quantity and new checked date. However, it only updates the first row in the table. Any help appreciated.
$(document).ready(function() {
$("form").on("submit", function(event) {
event.preventDefault();
var res = $(this).serialize();
var req = $.ajax({
url: '/stock/update',
type: 'POST',
data: res,
dataType: 'json',
success: function(response) {
//console.log(response);
$('#qty').text(response.qty_new);
$('#date').text(response.date);
}
});
});
});
Here is the HTML as requested:
<table>
<th>Part</th>
<th>Location</th>
<th>Quantity</th>
<th>Date Checked</th>
<th>New Quantity</th>
<th>Update</th>
% for row in stock:
<tr>
<td id='part'>{{row['part']}}</td>
<td id='location'>{{row['location']}}</td>
<td id='qty'>{{row['qty']}}</td>
<td id='date'>{{row['date']}}</td>
<form>
<input type='hidden' name='part' value="{{row['part']}}">
<input type='hidden' name='location' value="{{row['location']}}">
<td><input type='number' name='qty_new' style='width: 4em;'></td>
<td><button id='update_qty'>Save</button></td>
</form>
</tr>
% end
</table>
Firstly, the cells should have classes instead of IDs because there are duplicates.
<td class='part'>{{row['part']}}</td>
<td class='location'>{{row['location']}}</td>
<td class='qty'>{{row['qty']}}</td>
<td class='date'>{{row['date']}}</td>
<form>
<input type='hidden' name='part' value="{{row['part']}}">
<input type='hidden' name='location' value="{{row['location']}}">
<td><input type='number' name='qty_new' style='width: 4em;'></td>
<td><button class='update_qty'>Save</button></td>
</form>
Next, you'll need a way to select these based on the form that's being submitted.
$(document).ready(function() {
$("form").on("submit", function(event) {
event.preventDefault();
var $form = $(this);
var res = $form.serialize();
var req = $.ajax({
url: '/stock/update',
type: 'POST',
data: res,
dataType: 'json',
success: function(response) {
$form.siblings('.qty').text(response.qty_new);
$form.siblings('.date').text(response.date);
}
});
});
});
$(this) gets the jQuery-equivalent current scope of this, which is the form. Then the form's siblings are searched for the correct classes and the elements are modified.

Combine Checkbox value with Selection Option value in form

I have a form that has a list of checkboxes and selection option. It's basically an order form. When a customer clicks on a checkbox I'd like the value of the Select Option as well as the Checkbox's value to be sent with the form.
I really don't know AJAX. I'm using a script I found to get all the data to a php file. What do I need to add to the jquery to make the option and checkbox value of all the checked items combine as one variable?
<table>
<tr>
<td>
<select class="qty" name="qty" id="qty">
<option value="1">1</option>
</select>
</td>
</tr>
<tr>
<td>
<input id="Part1_1" name="Part[]" type="checkbox" value="Part 1">
</td>
</tr>
<tr>
<td>
<select class="qty" name="qty" id="qty1">
<option value="1">1</option>
<option value="2">2</option>
</select>
</td>
</tr>
<tr>
<td>
<input id="Part1_2" name="Part[]" type="checkbox" value="Part 2">
</td>
</tr>
</table>
<script>
$(document).ready(function(){
$("#contact-form").on("submit",function(e){
e.preventDefault();
var sendData = $( this ).serialize();
$.ajax({
type: "POST",
url: "orderform.php",
data: sendData,
success: function(data){
$(".response_msg").text(data);
$(".response_msg").slideDown();
}
});
});
});
</script>
EDIT:
I'd like to pass along to the php a variable for each part. So if Part 1 is checked then the value of the checkbox and the value of the quantity will be grouped together.
You could use a FormData object which would allow you to append the value of the ComboBox and Select list and send that in an ajax request.
Check this FormData
You need to add the select value this way. And you should also add the new parameter in your method on the server. In the example I named it as select_param.
$(document).ready(function() {
$("#contact-form").on("submit", function(e) {
e.preventDefault();
var sendData = $(this).serialize();
$.ajax({
type: "POST",
url: "orderform.php",
data: sendData + "&select_param1=" + $("#qty option:selected").text() +
"&select_param2=" + $("#qty1 option:selected").text(),
success: function(data) {
$(".response_msg").text(data);
$(".response_msg").slideDown();
}
});
});
});

jQuery set value to delegated input fields

I have the HTML code as follows.
<table id="items">
<tr class="item-row">
<td class="item-name"><div class="delete-wpr"><a class="delete" href="javascript:;" title="Remove row">-</a></div></td>
<td><input type="text" id="slslno" class="slno"/></td>
<td><input type="text" class="cost"/></td>
<td><input type="text" class="qty"/></td>
<!-- <td><span class="price"></span></td>-->
<td class="price"></td>
<a class="add" id="addrow" href="javascript:;" title="Add a row">+</a> </tr>
</table>
It has a button named "Add a row" which adds more rows dynamically.
Then I have this bind, which calls an update function during blur of the slno field.
function bind()
{
$(".slno").blur(update_unitcost);
}
The function update_unitcost is as follows.
function update_unitcost()
{
var unitprice1=$(this).val();
unitprice={"unitpricereal":unitprice1};
$.ajax({
type: "POST",
url: "findcost.php",
data: unitprice,
success: function(unitp){
$( ".cost" ).val(unitp);
}
});
}
In the above function, I am able to get the values of with the this selector, but when it comes to setting the value in the following line,
$( ".cost" ).val(unitp);
It just resets every ".cost" classes to that particular number. How can I set values to individual delegated rows? I tried the following approach too, but it failed.
var row = $(this).parents('.item-row');
row.find('.cost').val(unitp);
Set a variable in your function to only target the specific .cost element you wish to update instead of all of them.
function update_unitcost()
{
var unitprice1=$(this).val();
var costItem = $(this).parent().parent().find('td input.cost');
unitprice={"unitpricereal":unitprice1};
$.ajax({
type: "POST",
url: "findcost.php",
data: unitprice,
success: function(unitp){
costItem.val(unitp);
}
});
}

Categories