I'm trying to save the value of the check box in laravel. I can save all the text fields and all the code works. When I try to save the value of the checkbox the code breaks. Here is what I've tried. All the help is appreciated.
Here is my controller I've
public function addTodo(Request $request)
{
$status = Todo::has('status') ? true: false;
$todo = new Todo;
$todo->item = $request->item;
$todo->description = $request->description;
$todo->status = $request->status;
$todo->save();
return response()->json($todo);
}
Here is my HTML
<div class="form-group">
<div class="col-sm-10">
<input type="checkbox" name="status" id="status" value="1"
placeholder="Your description Here" required>
</div>
</div>
</div>
Here is my script
$(document).on('click','.create-modal', function() {
$('#create').modal('show');
$('.form-horizontal').show();
$('.modal-title').text('Add Item');
});
$("#add").click(function() {
$.ajax({
type: 'POST',
url: '/addTodo',
data: {
'_token': $('input[name=_token]').val(),
'item': $('input[name=item]').val(),
'status':$('input[name="status[]:checked'].val()
},
success: function(data){
if ((data.errors)) {
$('.error').removeClass('hidden');
$('.error').text(data.errors.item);
} else {
$('.error').remove();
$('#table').append("<tr class='post" + data.id + "'>"+
"<td>" + data.id + "</td>"+
"<td>" + data.item + "</td>"+
"<td>" + data.status + "</td>"+
"<td><button class='show-modal btn btn-info btn-sm' data-id='" + data.id +
"' data-item='" + data.item + "' data-status='" + data.status + "'> +
<span class='fa fa-eye'></span></button> +
<button class='edit-modal btn btn-warning btn-sm' data-id='" +
data.id + "' data-item='" + data.item + "' data-status='" +
data.status + "'><span class='glyphicon glyphicon-pencil'></span></button> +
<button class='delete-modal btn btn-danger btn-sm' data-id='" +
data.id + "' data-item='" + data.item + "' data-status='" + data.status +
"'><span class='glyphicon glyphicon-trash'></span></button> +
</td>"+ "</tr>");
}
},
});
$('#item').val('');
$('#status').val('');
location.reload();
});
try this
$('input[name="status"]:checked').val()
Related
I have to dynamically create buttons in an Ajax success function. There isn't a fixed number of buttons and
each time the number is different.
I can do it, but not knowing the exact number of elements that will be created, I don't know how to add the correct number of button listener.
AJAX:
success : function(data, status, xhr) {
$("#risultatoLibriCercati").empty();
var divContent = "";
for (var i = 0; i < data.length; i++) {
divContent +=
"<div class='col-sm-2 mt-4'><a data-toggle='modal' data-target='#bookPage" +
[i] +
"'><div class='card shadow-sm'><img style='height:250px' src='" +
data[i].imgLink +
"' class='img-thumbnail rounded'></div></a></div><div class='modal fade' id='bookPage" +
[i] +
"'><div class='modal-dialog'><div class='modal-content'><div class='modal-header text-center'><h4 class='modal-title w-100 dark-grey-text font-weight-bold'>" +
data[i].titolo +
"</h4><button type='button' class='close' data-dismiss='modal' aria-lable='close'>×</button></div><div class='mt-4' style='background: url(" +
data[i].imgLink +
") no-repeat;background-size: contain; background-position: center; min-height: 300px;'></div><div class='modal-body mx-4'><div class='md-form'><p class='font-small'>" +
data[i].autore +
"</p></div><div class='md-form'><p>" +
data[i].descrizione +
"</p></div><div class='text-center mb-3'><button class='btn btn-primary btn-block z-depth-1a' id='aggiungi" +
[i] +
"'>Aggiungi a libreria</button><a href='" +
data[i].isbn13.replace("'", " ") +
"' target='_blank' style='border:none;text-decoration:none'><img src='https://www.niftybuttons.com/amazon/amazon-button2.png'></a></div></div></div></div></div><input type='hidden' id='categoria" +
[i] +
"' value='" +
data[i].categoria +
"'><input type='hidden' id='googleID" +
[i] +
"' value='" +
data[i].googleID +
"'><input type='hidden' id='titolo" +
[i] +
"' value='" +
data[i].titolo.replace("'", " ") +
"'><input type='hidden' id='descrizione" +
[i] +
"' value='" +
data[i].descrizione.replace("'", " ") +
"'><input type='hidden' id='autore" +
[i] +
"' value='" +
data[i].autore +
"'><input type='hidden' id='isbn" +
[i] +
"' value='" +
data[i].isbn13.replace("'", " ") +
"'><input type='hidden' id='voto" +
[i] +
"' value='" +
data[i].voto +
"'><input type='hidden' id='imgLink" +
[i] +
"' value='" +
data[i].imgLink +
"'>";
}
$("#risultatoLibriCercati").append(divContent);
}
BUTTON ON CLICK LISTENER:
$(document).on('click', '#aggiungi0', function(){
var book = {
googleID: $("#googleID0").val(),
titolo: $("#titolo0").val(),
descrizione: $("#descrizione0").val(),
isbn13: $("#isbn0").val(),
voto: $("#voto0").val(),
imgLink: $("#imgLink0").val(),
autore: $("#autore0").val(),
categoria: $("#categoria0").val(),
userId: getCookie("userId"),
};
$.ajax({
[...]
You can add class attribute for those buttons and attach event and index for them as below
var btnIndex = 0;
$('#add').on('click', function() {
$('.container').append(`<button class="new-btn" data-index=${btnIndex++}>Button test</button>`);
});
$('.container').on('click', '.new-btn', function(e) {
console.log("clicked" + $(e.target).data("index"));
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="add">Add</button>
<div class="container"></div>
And passing these values by index into ajax call like this:
$(document).on('click', '.new-btn', function(e){
const idx = $(e.target).data("index");
var book = {
googleID: $("#googleID" + idx).val(),
titolo: $("#titolo" + idx).val(),
descrizione: $("#descrizione" + idx).val(),
isbn13: $("#isbn" + idx).val(),
voto: $("#voto" + idx).val(),
imgLink: $("#imgLink0" + idx).val(),
autore: $("#autore" + idx).val(),
categoria: $("#categoria" + idx).val(),
userId: getCookie("userId"),
};
$.ajax({
[...]
i want to show the bill number when user click it from list,
i have already fetch the data as well but i dont know how can i add this url /api/sales_bill_info/{$bill_number} to show that bill number details.
$.each(resultData, function(index, row) {
// var editUrl = url+'/'+row.id+"/edit";
bodyData += "<tr style='font-size: 0.78em;'>"
bodyData += "<td>" + i++ + "</td>" +
"<td><a href=" {
{
url('/api/sales_bill_info/'. + row.bill_number + )
}
}
" class='btn btn-success btn-sm printbill' value='" + row.bill_number + "' style='margin-left:20px;'>PRINT</a></td>" +
"<td><button class='btn btn-sm btn-danger cancelbill' id='cancelbill' value='" + row.SID + "' style='margin-left:20px;'>CANCEL BILL" + row.SID + "</button></td>" +
"<td>" + row.bill_number + "</td>" +
"<td>" + row.compy_name + "</td>" +
"<td>" + row.truck_number + "/" + row.trailer_number + "</td>" +
"<td>" + row.Devicenumber + "</td>" +
"<td>" + row.slavename + "</td>" +
"<td>" + row.name + "</td>" +
"<td>" + row.tag_area + "</td>" +
"<td>" + row.Lname + "</td>" +
"<td>" + row.bill_number + "</td>" +
"<td>" + row.driverPhone + "</td>" +
"<td>" + row.created_at_sale + "</td>" +
"<td><button class='btn btn-danger delete' value='" + row.id + "' style='margin-left:20px;'>Delete</button></td>";
bodyData += "</tr>";
})
$("#bodyData").append(bodyData);
}
});
i tried to add this "<td><a href="{{url('/api/sales_bill_info/'.+row.bill_number+)}}" class='btn btn-success btn-sm printbill' value='"+row.bill_number+"' style='margin-left:20px;'>PRINT</a></td>"
but does not works.
someone can help me on this
You can try assigning the value of edit url to a variable and then use the same.
$.each(resultData, function(index, row) {
let editUrl = `/api/sales_bill_info/${row.bill_number}`;
// var editUrl = url+'/'+row.id+"/edit";
bodyData += "<tr style='font-size: 0.78em;'>"
bodyData += "<td>" + i++ + "</td>" +
"<td><a href=" + editUrl + "class='btn btn-success btn-sm printbill' value='" + row.bill_number + "' style='margin-left:20px;'>PRINT</a></td>" +
"<td><button class='btn btn-sm btn-danger cancelbill' id='cancelbill' value='" + row.SID + "' style='margin-left:20px;'>CANCEL BILL" + row.SID + "</button></td>" +
"<td>" + row.bill_number + "</td>" +
"<td>" + row.compy_name + "</td>" +
"<td>" + row.truck_number + "/" + row.trailer_number + "</td>" +
"<td>" + row.Devicenumber + "</td>" +
"<td>" + row.slavename + "</td>" +
"<td>" + row.name + "</td>" +
"<td>" + row.tag_area + "</td>" +
"<td>" + row.Lname + "</td>" +
"<td>" + row.bill_number + "</td>" +
"<td>" + row.driverPhone + "</td>" +
"<td>" + row.created_at_sale + "</td>" +
"<td><button class='btn btn-danger delete' value='" + row.id + "' style='margin-left:20px;'>Delete</button></td>";
bodyData += "</tr>";
});
$("#bodyData").append(bodyData);
Maybe it could be useful to consider template strings in JavaScript. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
They can really simplify your code and avoid some problems like the ones with quotes or double quotes.
I hope this could help you! Happy coding 😀
const resultData = [{
bill_number: 1,
SID: 2,
compy_name: 'xxx',
truck_number: '54125',
Devicenumber: '123456',
slavename: 'fff',
trailer_number: 'yyy',
name: 'pluto',
tag_area: 'A51',
Lname: 'xxx',
bill_number: '1234',
driverPhone: '+0236851545',
created_at_sale: '2020-01-01',
}];
function url(path) {
return 'http://...'
}
$.each(resultData, function(i, row) {
$(`#bodyData`).append(
`<tr style='font-size: 0.78em;'>
<td>${i++}</td>
<td>
<a
href="${url('/api/sales_bill_info/'+row.bill_number)}}"
class='btn btn-success btn-sm printbill'
value='${row.bill_number}' style='margin-left:20px;'>
PRINT
</a>
</td>
<td>
<button
class='btn btn-sm btn-danger cancelbill'
id='cancelbill' value='${row.SID}'
style='margin-left:20px;'>
CANCEL BILL ${row.SID}
</button>
</td>
<td>${row.bill_number}</td>
<td>${row.compy_name}</td>
<td>${row.truck_number} ${row.trailer_number}</td>
<td>${row.Devicenumber}</td>
<td>${row.slavename}</td>
<td>${row.name}</td>
<td>${row.tag_area}</td>
<td>${row.Lname}</td>
<td>${row.bill_number}</td>
<td>${row.driverPhone}</td>
<td>${row.created_at_sale}</td>
<td>
<button
class='btn btn-danger delete'
value='${row.id}'
style='margin-left:20px;'>
Delete
</button>
</td>
</tr>`);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id='bodyData'></table>
I have initial value on my table and I created a button that supposedly clear and override new value to my table. But what happening in my current script is if I clicked my button the table will just append a new row.
Here is my current loader:
function RefreshData() {
$.ajax({
url: '/Home/GetItemList',
type: 'GET',
dataType: 'json',
success: function (data) {
console.log(data);
var row = '';
$('.table tbody').html("");
$.each(data, function (i, item) {
row += '<tr><td style="display:none;" >' + item.empSerial + '</td><td width="50%">' + item.name
+ '</td><td width="30%">' + item.dept
+ '</td><td style="display:none;" >' + item.fname
+ '</td><td style="display:none;" >' + item.lname
+ '</td><td>' + '<button onclick="delete(this, ' + item.empSerial + ",'" + item.name + "'" + ')" type="button" class="btn btn-danger"> Remove </button >'
+ '</td><td>' + '<button onclick="update(this, ' + item.empSerial + ",'" + item.fname + ",'" + item.lname + ",'" + item.dept + ",'" + item.name + "'" + ')" type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModalPMA"> Update </button >' + '</td></tr>';
});
$('.table tbody').html(row); // override previous results
},
error: function (jqXhr, textStatus, errorThrown) {
console.log(errorThrown.toString());
}
});
}
table is a element not a class .table so remove dot . from it.
$('table tbody').html("");
I have Generated Dynamic Table Using Following Code in C# + Mongodb
for (var i = 0; i < data.length; i++) {
strData += "<tr>\
<td>"+ data[i].sid + "</td> <td> " + data[i].fname + " </td><td>" + data[i].lname + "</td><td>" + data[i].email + "</td><td>" + data[i].pass + "</td><td>" + data[i].address + "</td>\
<td><input type='button' id='delete' value='delete' sid='" + data[i].sid + "' onclick='deleteRecord()'></td>\
<td><input type='button' id='update' value='update' sid='" + data[i].sid + "' onclick='updateRecord();'></td>\
</tr>";
}
//$("#data").append(tabelHerader);
$("#data").html(strData);
Now I Want To delete Record when I click To Delete Button the Following Function Will Execute
function deleteRecord() {
var sid = $("#delete").attr("sid");
alert(sid);
// console.log("yes we are in");
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'Home.aspx/deleteData',
data: "{'id':'" + sid + "'}",
async: false,
success: function (response) {
alert("you have successfully deleted record");
},
error: function () {
console.log('there is some error');
}
});
}
But The Problem Is That When I Click To Delete Button I get Same Id For Each Record ,So If I Click Any Button Only First Record Will Delete.
Anyone Have Solution?
Id must be unique for each element use class instead of id or simply pass id to the function as below
for (var i = 0; i < data.length; i++) {
var sid = data[i].sid;
strData += "<tr>\
<td>"+ data[i].sid + "</td> <td> " + data[i].fname + " </td><td>" + data[i].lname + "</td><td>" + data[i].email + "</td><td>" + data[i].pass + "</td><td>" + data[i].address + "</td>\
<td><input type='button' value='delete' sid='" + data[i].sid + "' onclick='deleteRecord("+ sid +")'></td>\
<td><input type='button' value='update' sid='" + data[i].sid + "' onclick='updateRecord("+ sid +");'></td>\
</tr>";
}
//$("#data").append(tabelHerader);
$("#data").html(strData);
and in your update record or delete record function do as below
function deleteRecord(sid) {
alert(sid);
// console.log("yes we are in");
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'Home.aspx/deleteData',
data: "{'id':'" + sid + "'}",
async: false,
success: function (response) {
alert("you have successfully deleted record");
},
error: function () {
console.log('there is some error');
}
});
}
first, you need to change your function, add 1 argument to your function
function deleteRecord(id) {
then change var sid value to be var sid = id;
With onclick, you can use
onclick="deleteRecord(pass_some_id from data[i].sid)"
Without onclick, var sid = $("#delete").attr("sid"); will choose first sid attribute value from input list, so what you need is
$("#delete").each(function(){
$(this).onclick(function(){
var sid = $(this).attr("sid"); // get attr value from specify clicked button
deleteRecord(sid); // call delete record with specify id
})
})
or simply way :
change
var sid = $("#delete").attr("sid");
to
var sid = $(this).attr("sid"); // select attribute value from current clicked element
Full Example from #lukesUbuntu :
https://jsfiddle.net/mvLwymvb/
here some good reference :
http://api.jquery.com/jquery.each/
https://api.jquery.com/category/selectors/
You can append the value of i with the id and onclick you can pass the context using this
"<tr>" +
"<td>" + data[i].sid + "</td>" +
"<td> " + data[i].fname + " </td>" +
"<td>" + data[i].lname + "</td>" +
"<td>" + data[i].email + "</td>" +
"<td>" + data[i].pass + "</td>" +
"<td>" + data[i].address + "</td>" +
"<td><input type='button' id='delete_'"+i+" value='delete' " +
// ^ changed here
"sid='" + data[i].sid + "' onclick='deleteRecord(this)'></td>" +
"<td><input type='button' id='update_'"+i+" value='update'" +
// ^ Changed here
" sid='" + data[i].sid + "' onclick='updateRecord(this);'></td>" +
"</tr>";
in deleteRecord function
function deleteRecord(elem){
var getId = elem.id // id of the clicked element
}
Working example here https://jsfiddle.net/mvLwymvb/1/
for (var i = 0; i < data.length; i++) {
strData += "<tr>\
<td>" + data[i].sid + "</td> <td> " + data[i].fname + " </td><td>" + data[i].lname + "</td><td>" + data[i].email + "</td><td>" + data[i].pass + "</td><td>" + data[i].address + "</td>\
<td><input class='delete' type='button' id='delete' value='delete' sid='" + data[i].sid + "'></td>\
<td><input type='button' id='update' value='update' sid='" + data[i].sid + "' onclick='updateRecord();'></td>\
</tr>";
}
//$("#data").append(tabelHerader);
$("#data").html(strData);
$(".delete").click(function() {
var sid = $(this).attr("sid");
alert(sid);
// console.log("yes we are in");
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'Home.aspx/deleteData',
data: "{'id':'" + sid + "'}",
async: false,
success: function(response) {
alert("you have successfully deleted record");
},
error: function() {
console.log('there is some error');
}
});
})
Finally I Got The Solution
And That Solution is A Deligets
function check()
{
$(document).on('click', '#delete', function (event) {
var element = event.target;
var sid = $(element).attr("sid");
console.log(sid);
deleteRecord(sid);
});
}
function deleteRecord(sid) {
// console.log("yes we are in");
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'Home.aspx/deleteData',
data: "{'id':'" + sid + "'}",
async: false,
success: function (response) {
alert("you have successfully deleted record");
} ,
error: function () {
console.log('there is some error');
}
});
This Is Html Part
for (var i = 0; i < data.length; i++) {
var sid = data[i].sid
strData += "<tr>\
<td>"+ data[i].sid + "</td> <td> " + data[i].fname + " </td><td>" + data[i].lname + "</td><td>" + data[i].email + "</td><td>" + data[i].pass + "</td><td>" + data[i].address + "</td>\
<td><input type='button' id='delete' value='delete' sid='" + sid + "' onclick='check()' ></td>\
<td><input type='button' id='update' value='update' sid='" + data[i].sid + "' onclick='updateRecord();'></td>\
</tr>";
}
Thank You so much Every One
Don't mess up with native JavaScript and jQuery. You will confuse later.
First don't do inline onclick when you have jQuery, use $(elem).click(function) instead.
Second id must be unique (1 id must be used by 1 element only), class is general (1 class can be used by many element).
Try to edit this line
...
<td><input type='button' id='delete' value='delete' class="btn-delete" sid='" + data[i].sid + "' ></td>\
...
and your script
<script>
$(function(){
$('body').on('click', '.btn-delete', function(){
var sid = $(this).attr("sid");
var tr = $(this).closest('tr');
//alert(sid);
$.ajax({
type: 'POST',
dataType: 'json',
url: 'Home.aspx/deleteData',
data: {id: sid},
//async: false, why you need to do this????
success: function (response) {
console.log(response);
alert("you have successfully deleted record");
tr.remove();
},
error: function (response) {
console.log('there is some error');
console.log(response);
}
});
})
});
</script>
First, my innerHTML looks like this:
function viewMusicFeed() {
$.ajax({
url: "getMusicFeed",
method: "GET",
dataType: "JSON",
contentType: "application/json; charset=UTF-8",
success: function(obj) {
getMusicFeed(obj);
}
});
}
function getMusicFeed(obj) {
var userId = $("#userId").val();
var list = '<section class="comment-list block">';
$(obj).each(function(i, item) {
if (item.musicfeedtitle == "Message") {
list = list + '<article id="comment-id" class="comment-item">' + '<a class="pull-left thumb-sm avatar"><img src="resources/images/a9.png" alt="..."></a>' + '<span class="arrow left"></span>' + '<section class="comment-body panel panel-default">' + '<header class="panel-heading">';
if (item.writerUser == userId) {
list = list + 'My ' + item.musicfeedtitle + '' + '<span class="text-muted m-l-sm pull-right">' + '<i class="fa fa-clock-o"></i>' + item.writedate + '</span></header>' + '<div class="panel-body">' + '<div><pre>' + item.writemessage + '</pre></div>' + '<div class="comment-action m-t-sm">' + '<a class="btn btn-default btn-xs" check="delete" data-index="' + item.musicfeedid + '">' + '<i class="fa fa-trash-o text-muted"></i> Remove</a></div></div></section></article>';
} else {
list = list + item.writerUser + '\'s ' + item.musicfeedtitle + '' + '<span class="text-muted m-l-sm pull-right">' + '<i class="fa fa-clock-o"></i>' + item.writedate + '</span></header>' + '<div class="panel-body">' + '<div><pre>' + item.writemessage + '</pre></div>' + '<div class="comment-action m-t-sm pull-right">' + '<a class="btn btn-default btn-xs" check="report" data-toggle="modal" data-target="#reportModal" data-index="' + item.musicfeedid + '">' + '<i class="icon-flag text-muted"></i> Report</a>' + '</div></div></section></article>';
}
} else {
list = list + '<article id="comment-id" class="comment-item">' + '<a class="pull-left thumb-sm avatar"><img src="resources/images/a9.png" alt="..."></a>' + '<span class="arrow left"></span>' + '<section class="comment-body panel panel-default">' + '<header class="panel-heading">' + '' + item.writemessage + '' + '<span class="text-muted m-l-sm pull-right">' + '<i class="fa fa-clock-o"></i>' + item.writedate + '</span>' + '<a class="btn btn-default btn-xs pull-right" data-index="' + item.musicfeedid + '">' + '<i class="fa fa-trash-o text-muted"></i></a></header></section></article>';
}
});
list = list + '</section>';
$("div.col-lg-12").html(list);
}
It's in innerHTML because I have another different set of this and those need to change at the click of a button. The outcome looks like that of Facebook. Since there will be a load of data, I need to paginate this. The problem is, all the paginate tutorial do not explain how paginate innerHTML. Is there a way to paginate innerHTML, or any other way to avoid innerHTML and start paginate from there?
Here's the JSON data(I'm getting this from Spring MVC Controller):
Array[11]
0 : Object
musicfeedid : "a120160427104913919"
musicfeedtitle : "da15737e-3eb3-31e4-97f0-fe46299f75fb"
reportmusicfeedSet : null
writedate : "2016-04-27 10:49:13"
writemessage : "I liked New Generation"
writerUser : "a1"
__proto__ : Object
1 : Object
musicfeedid : "a220160425190136417"
musicfeedtitle : "Message"
reportmusicfeedSet : null
writedate : "2016-04-25 19:01:36"
writemessage : "asdasdasdasdasdasdasdsd<div>report report report</div>"
writerUser : "a2"
__proto__ : Object
2 : Object
musicfeedid : "a120160424190033326"
musicfeedtitle : "60bc9b01-196c-4849-bd6b-5894ed53521d"
reportmusicfeedSet : null
writedate : "2016-04-24 19:00:33"
writemessage : "a2 liked Outsiders"
writerUser : "a1"
__proto__ : Object
.
.
.