Update status of each dynamic row using checkbox - javascript

I have a form with dynamic rows, after fetching record I want to update status of selected rows by checkbox.
I'm successfully getting each row checkbox values and dynamic row id in console but when trying to update values, it's updating first row only.
HTML:
<button type="button" class="btn btn-info" id="update_status_btn">Update Status</button>
Fetched record:
success: function(data){
var trHTMLr = '';
$.each(data,function(i,row){
trHTMLr += '<tr>' +
'<td><input type="text" name="first_name" class="form-control text-center" value="' + row.first_name + '" /></td>' +
'<td><input type="checkbox" name="status" class="form-control text-center updatestatusclass" data-id="' + row.id + '" value="' + 'YES' + '"/></td>' +
'</tr>';
});
$('#mytable').append(trHTML);
}
Update status:
$("#update_status_btn").click(function(e) {
e.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var eachrow_value=[];
$('.updatestatusclass').each(function(){
if($(this).is(":checked"))
{
eachrow_value.push($(this).val());
}
});
eachrow_value=eachrow_value.toString();
var row_id = $('.updatestatusclass').attr('data-id');
$.ajax({
url: "{{ url('/updatestatus') }}",
method: 'POST',
data: {id: row_id, status: eachrow_value},
dataType: 'json',
success: function (response) {
alert('Updated Successfully!');
},
error: function (response) {
alert("Not Updated, Try again.");
}
});
});
Controller:
if ($request->ajax()) {
$stat = Services::where('id', $request->get('id'))
->update(array(
'status' => $request->get('status')
));
return Response::json($stat);
}
I want to update status of selected row by checkbox with it's respective row ID.

What you are looking for is to update multiple checkboxes in one go. So, you need to store both selected & unselected checkboxes.
Your jQuery
let checkedIds = [];
let unCheckedIds = [];
$('.updatestatusclass').each(function () {
if ($(this).is(":checked")) {
checkedIds.push($(this).attr('data-id'));
} else {
unCheckedIds.push($(this).attr('data-id'));
}
});
$.ajax({
url: "{{ url('/updatestatus') }}",
method: 'POST',
data: {
checkedIds: checkedIds,
checkedIdStatus: 'active', //do your thing
unCheckedIds: unCheckedIds,
unCheckedIdStatus: 'inactive', //do your thing
},
dataType: 'json',
success: function (response) {
alert('Updated Successfully!');
},
error: function (response) {
alert("Not Updated, Try again.");
}
});
In your Controller
if ($request->ajax()) {
Services::whereIn('id', $request->get('checkedIds'))
->update(array(
'status' => $request->get('checkedIdStatus')
));
Services::whereIn('id', $request->get('unCheckedIds'))
->update(array(
'status' => $request->get('unCheckedIdStatus')
));
}
Hope this helps. Cheers!

Related

Jquery repeater with select2 not working properly

I am seaching from 2 days about this issue.
The first element is working perfectly. But after repeat the element, previous element's select2 fields destroyed automatically.
There is two rop divs in repeater. When first one selected by the ajax request I am appending the options to values section.
Here is the screenshot for reference.
Here is the code for repeater and select2 initialization.
<script>
$(function () {
$(".attribute_list").on('change', ".attribute", function (e) {
var attr_name = $(this).attr('name');
var attr_id = $(this).val();
$.ajax({
type: "POST",
url: "{{ route('products.getValue') }}",
headers: {
'X-CSRF-TOKEN': "{{ csrf_token() }}"
},
contentType: "application/json",
dataType: "json",
data: '{"attr_id": "' + attr_id + '", "attr_name" : "' + attr_name + '"}',
success: function (data) {
var attribute_value = data.attribute_value;
var field_name = 'select[name="product_attribute[' + data.field_name + '][attribute_values][]"]';
if (attribute_value) {
$(field_name).empty();
$.each(attribute_value, function (key, value) {
$(field_name).append('<option value="' + value.id + '">' + value.value + '</option>');
});
// $(field_name).select2();
} else {
$(field_name).empty();
}
}
});
});
});
</script>
<script>
// $("#attribute_button").click(function(){
// $('#attribute_values').select2({
// placeholder: "select attribute value"
// });
// });
window.onload = function () {
$('.attribute_values').select2({
placeholder: "select attribute value",
allowClear: true
});
}
$('.repeater').repeater({
initEmpty: false,
show: function () {
$(this).slideDown();
$('.attribute_values').select2({
placeholder: "select attribute value"
});
},
hide: function (deleteElement) {
if (confirm('Are you sure you want to delete this element?')) {
$(this).slideUp(deleteElement);
}
},
ready: function (setIndexes) {
},
})

Delete data by ajax in laravel

I'm trying to delete items by ajax, so far i can get each item id but somehow when i click on delete button it just getting first item id.
code
controller
public function delqtydisc(Request $request,$id)
{
$dele = QtyDiscount::find($id)->delete();
return response()->json($dele);
}
route
Route::post('/delqtydisc/{id}', 'QtyDiscountController#delqtydisc')->name('delqtydisc');
script
<script>
$(document).ready(function() {
$("#addnewqtydiscmsgsave").click(function(e){
e.preventDefault();
//this adds new items to database (no issue here)
$.ajax({
type: "post",
url: "{{ url('admin/addnewqtydisc') }}",
data: {
'_token': $('input[name=_token]').val(),
'product_id': $('#product_id').val(),
'amount': $('#amount').val(),
'min': $('.min').val(),
'max': $('.max').val(),
},
success: function (data) {
$('#addnewqtydiscmsg').empty();
$('#addnewqtydiscmsg').append('<span class="text-success">Discount created successfully.</span>');
var $tr = $('<tr/>');
$tr.append($('<td/>').html(data.min));
$tr.append($('<td/>').html(data.max));
$tr.append($('<td/>').html(data.amount));
// This adds delete button to my table
$tr.append($('<td/>').html("<button class='qtyitemid btn btn-xs btn-danger' data-id='" + data.id + "' type='button'>Delete this</button>"));
$('.list-order tr:last').before($tr);
$("#min").val('');
$("#max").val('');
$("#amount").val('');
// From this part delete function adds
$('.qtyitemid').on('click', function() {
e.preventDefault();
var QtyitemID = $('.qtyitemid').data('id');
console.log(QtyitemID);
$.ajax({
type: 'post',
url: '{{ url('admin/delqtydisc') }}/'+encodeURI(QtyitemID),
data: {
'_token': $('input[name=_token]').val(),
'id': QtyitemID
},
success: function(data) {
$('#addnewqtydiscmsg').empty();
$('#addnewqtydiscmsg').append('<span class="text-danger">Discount deleted successfully.</span>');
}
});
});
// end of delete fuction
},
error: function (data) {
console.log('Error:', data);
}
});
});
});
</script>
PS: I commented each part of my JavaScript code that I thought should
bring your attention
// This adds delete button to my table and // From this part delete function adds
Error
when I hit delete button I get 3 results (if i have 3 inputs) in my network, first one return true the other 2 return
"message": "Call to a member function delete() on null",
Any idea?
Update
with code below my problem is solved some how, the only issue is remained is that i still get my row id's multiple. e.g. when i delete id=1 network show it one time but when after that i delete id=2 network shows two times id=2
<script>
$(document).ready(function() {
$("#addnewqtydiscmsgsave").click(function(e){
e.preventDefault();
$.ajax({
type: "post",
url: "{{ url('admin/addnewqtydisc') }}",
data: {
'_token': $('input[name=_token]').val(),
'product_id': $('#product_id').val(),
'amount': $('#amount').val(),
'min': $('.min').val(),
'max': $('.max').val(),
},
success: function (data) {
$('#addnewqtydiscmsg').empty();
$('#addnewqtydiscmsg').append('<span class="text-success">Discount created successfully.</span>').fadeIn().delay(4000).fadeOut();
var $tr = $("<tr id='" + data.id + "'>");
$tr.append($('<td>').html(data.min));
$tr.append($('<td>').html(data.max));
$tr.append($('<td>').html(data.amount));
$tr.append($('<td>').html("<button class='qtyitemid btn btn-xs btn-danger' data-id='" + data.id + "' type='button'>Delete this</button>"));
$('.list-order tr:last').before($tr);
$("#min").val('');
$("#max").val('');
$("#amount").val('');
//delete item
$('.qtyitemid').on('click', function() {
e.preventDefault();
var QtyitemID = $(this).data('id');
console.log(QtyitemID);
$.ajax({
type: 'post',
url: '{{ url('admin/delqtydisc') }}/'+encodeURI(QtyitemID),
data: {
'_token': $('input[name=_token]').val(),
'id': QtyitemID
},
success: function(data) {
$('#addnewqtydiscmsg').empty();
$('#addnewqtydiscmsg').append('<span class="text-danger">Discount deleted successfully.</span>').fadeIn().delay(3000).fadeOut();
$('table tr#'+QtyitemID+'').remove();
}
});
});
//
},
error: function (data) {
console.log('Error:', data);
}
});
});
});
</script>
PS: basically most of my problem is solved i'm just looking for answer
to avoid this multiple id in network.
The error occurred in your qtyitemid on click event. Specifically this line: var QtyitemID = $('.qtyitemid').data('id');
This JS code will always return the data of the first qtyitemid class. You must use the keyword this to determine what element is clicked. This code hopefully fix the problem:
$('.qtyitemid').on('click', function() {
e.preventDefault();
var QtyitemID = $(this).data('id');
console.log(QtyitemID);
$.ajax({
type: 'post',
url: '{{ url('admin/delqtydisc') }}/'+encodeURI(QtyitemID),
data: {
'_token': $('input[name=_token]').val(),
'id': QtyitemID
},
success: function(data) {
$('#addnewqtydiscmsg').empty();
$('#addnewqtydiscmsg').append('<span class="text-danger">Discount deleted successfully.</span>');
}
});
});

How to set multiple selected values for multi-select picker?

I have the following multi-select picker which is populated with data. I want to be able to set multiple selected values that I get from the database.
<div class="form-group col-md-6 col-lg-6 col-sm-6">
<label>Choose Skills</label>
<select id="DDLSkills" name="selValue" data-live-search="true" data-style="btn-default form-control" class="selectpicker form-control" data-size="5" multiple data-max-options="2"></select>
</div>
This is the code that I use to populate the multi-select picker:
$('.selectpicker').selectpicker();
$.ajax({
type: "POST",
url: '/TutorSkills/FetchTutorSkills',
success: function (data) {
//console.dir(data);
for (var i = 0; i < data.length; i++) {
$("#DDLSkills").append('<option data-tokens="' + data[i].Skill.SkillName + '" value="' + data[i].Skill.Id + '">' + data[i].Skill.SkillName + '</option>');
}
$("#DDLSkills").selectpicker("refresh");
},
error: function (error) {
alert('Failed to get the logged-in tutor skills!');
}
})
However, I want to be able to set selected values that I get from the database but the code below only sets the last value that I get from the database.
$.ajax({
type: "POST",
url: '/ClassSkills/GetClassSelectedSkills',
data: { 'id': selectedEvent.id },
success: function (data) {
console.dir(data);
for (var i = 0; i < data.length; i++) {
$('.selectpicker').selectpicker('val', [data[i].Skill.Id]);
}
$('.DDLSkills').selectpicker('refresh')
},
error: function (error) {
alert('Failed');
}
})
Thank you
Try if this work
$.ajax({
type: "POST",
url: '/ClassSkills/GetClassSelectedSkills',
data: { 'id': selectedEvent.id },
success: function (data) {
console.dir(data);
let optArr = [];
for (var i = 0; i < data.length; i++) {
optArr.push(data[i].Skill.Id);
}
$('.selectpicker').selectpicker('val', optArr);
$('.DDLSkills').selectpicker('refresh')
},
error: function (error) {
alert('Failed');
}
})

Javascript Won't Work On Duplicated Row [duplicate]

I'm having an issue using jQuery autocomplete with dynamically created inputs (again created with jQuery). I can't get autocomplete to bind to the new inputs.
Autocomplete
$("#description").autocomplete({
source: function(request, response) {
$.ajax({
url: "../../works_search",
dataType: "json",
type: "post",
data: {
maxRows: 15,
term: request.term
},
success: function(data) {
response($.map(data.works, function(item) {
return {
label: item.description,
value: item.description
}
}))
}
})
},
minLength: 2,
});
New table row with inputs
var i = 1;
var $table = $("#works");
var $tableBody = $("tbody",$table);
$('a#add').click(function() {
var newtr = $('<tr class="jobs"><td><input type="text" name="item[' + i + '][quantity]" /></td><td><input type="text" id="description" name="item[' + i + '][works_description]" /></td></tr>');
$tableBody.append(newtr);
i++;
});
I'm aware that the problem is due to the content being created after the page has been loaded but I can't figure out how to get around it. I've read several related questions and come across the jQuery live method but I'm still in a jam!
Any advice?
First you'll want to store the options for .autocomplete() like :
var autocomp_opt={
source: function(request, response) {
$.ajax({
url: "../../works_search",
dataType: "json",
type: "post",
data: {
maxRows: 15,
term: request.term
},
success: function(data) {
response($.map(data.works, function(item) {
return {
label: item.description,
value: item.description
}
}))
}
})
},
minLength: 2,
};
It's more neat to use the class attribute for marking the input, like:
<input type="text" class="description" name="item[' + i + '][works_description]" />
Last, when you create a new table row apply the .autocomplete() with the options already stored in autocomp_opt:
$('a#add').click(function() {
var newtr = $('<tr class="jobs"><td><input type="text" name="item[' + i + '][quantity]" /></td><td><input type="text" class="description" name="item[' + i + '][works_description]" /></td></tr>');
$('.description', newtr).autocomplete(autocomp_opt);
$tableBody.append(newtr);
i++;
});
I found that I needed to put teh autocomplete after the append so:
$tableBody.append(newtr);
$('.description', newtr).autocomplete(autocomp_opt);

dynamically create radiobuttons and labels

Ok what I want to achieve is that it creates this automatically for each record I got back from my webservice.
<label for="ZAALID_1">Zaal 1</label>
<input id="ZAALID_1" type="radio" name="RESERVATIE.ZAALID" value="1" MSGCHECKED="~IF(CHKPROP(#RESERVATIE.ZAALID,'1'),CHECKED,)~" />
I am calling this webservice with an ajax call. There is nothing wrong with this call. I tested it with printing down the values.
$.ajax({
url: "~SYSTEM.URL~~CAMPAIGN.URL~/SelligentMobile/Webservice/WebService.asmx/getReservaties",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{'DATUM_BEGIN':'2012-05-09 10:10:36','DATUM_EINDE':'2012-05-09 12:10:45'}",
success: function (response) {
var zalen = response.d;
if (zalen.length > 0) {
$.each(zalen, function (index, zaal) {
createRadioElement(zaal.zaalId);
createLabel(zaal.zaalNaam,zaal.zaalId);
});
}
}
});
So I think there is an mistake in CreateRadioElement and createLabel.
Here are these two functions.
function createRadioElement( id ) {
var radioInput;
try {
var radioHtml = '<input id="ZAALID_' + id + '" type="radio" name="RESERVATION.ZAALID" value="' + id + '" MSGCHECKED="~IF(CHKPROP(#RESERVATIE.ZAALID,' + 1 + '),CHECKED,)~ ';
radioHtml += '/>';
radioInput = document.createElement(radioHtml);
} catch( err ) {
radioInput = document.createElement('input');
radioInput.setAttribute('type', 'radio');
radioInput.setAttribute('name', 'RESERVATION.ZAALID');
}
return radioInput;
}
function createLabel(name,id) {
var label;
var labelHTML = '<label for="ZAALID_' + id + '">'+ name +'</label>';
label = document.createElement(labelHTML);
return label;
}
Now another thing that I want to do is that is places these radiobuttons inside the div with id=zaalField
here is the HTML of that div
<div id=ZaalField data-role="fieldcontain" class="knoppen_boven">
<LABEL for=zaal>Zalen ter beschikking: </LABEL>
//Here should go the radiobuttons and labels.
</div>
Can anybody help ?
Kind regards
---EDIT---
function getZalen()
{
var dateB = $("#DATUM_BEGIN").val();
var dateE = $("#DATUM_EINDE").val();
console.log(dateB);
$.ajax({
url: "~SYSTEM.URL~~CAMPAIGN.URL~/SelligentMobile/Webservice/WebService.asmx/getReservaties",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{'DATUM_BEGIN':'2012-05-09 10:10:36','DATUM_EINDE':'2012-05-09 12:10:45'}",
success: function (response) {
var zalen = response.d;
alert(JSON.stringify(zalen));
if (zalen.length > 0) {
$.each(zalen, function (i, entity) {
$('ZaalField ').append(
$('<label />', { 'for': 'ZAALID_' + entity.zaalId, 'text': entity.zaalNaam }),
$('<input />', { 'id': 'ZAALID_' + entity.zaalId, 'type': 'radio', 'name': 'RESERVATION.ZAALID', 'value': entity.zaalId, 'MSGCHECKED': '~IF(CHKPROP(#RESERVATIE.ZAALID,' + 1 + '),CHECKED,)~ ' }), $('<br />'));
});
}
}
});
}
$(document).ready(function () {
var data = { "d": [{ "__type": "Reservatie", "zaalId": 2, "opmerking": null, "zaalNaam": "Zaal 2" }, { "__type": "Reservatie", "zaalId": 3, "opmerking": null, "zaalNaam": "Zaal 3"}] };
// $.ajax({
// url: "/SelligentMobile/Webservice/WebService.asmx/getReservaties",
// type: "POST", contentType: "application/json; charset=utf-8",
// dataType: "json", data: { 'DATUM_BEGIN': '2012-05-09 10:10:36', 'DATUM_EINDE': '2012-05-09 12:10:45' },
// success: function (data) {
if (data.d.length > 0) {
$.each(data.d, function (i, entity) {
$('body').append(
$('<label />', { 'for': 'ZAALID_' + entity.zaalId, 'text': entity.zaalNaam }),
$('<input />', { 'id': 'ZAALID_' + entity.zaalId, 'type': 'radio', 'name': 'RESERVATION.ZAALID', 'value': entity.zaalId, 'MSGCHECKED': '~IF(CHKPROP(#RESERVATIE.ZAALID,' + 1 + '),CHECKED,)~ ' }), $('<br />'));
});
}
// }
// });
});
function createLabel(id, name){
var name = "Zaal 2";
var label = document.createElement("label");
label.setAttribute("for","RANDOM"+id);
label.innerHTML = name;
return label;
}
var label = createLabel(2, "Zaal 2");
$(document.body).append(label); //add it to the body, or to whatever else you want to add it to.
This code works for me, while the code you have written doesn't.

Categories