How to count from 1 when remove a row ajax? - html

I have to make a functionality that users can add and remove rows with input fields. Problem is that I need a row index (number) in front of each row incorrect order(1., 2., 3. etc.) also when one or more rows are removed and then added again. I can add rows but I can`t get the counting right because If I remove them then the count starts with 4 but I need 1 or if the second row gets removed then I need 2 instead of 4.
I have made it with append() and so far so good but I also need row cont in front of each row. I have a counter but let's say I add 1 row and it gives numbers 1 and 2. If I remove the second row and add another again, now the count is 1 and 3
Note that the "add" button is only one and separated from append();
I have three lines that are 1, 2, and 3, respectively
Now I will delete one of them. For example, I delete row number 2. I see this demo,
This should not happen. It should show the numbers 1 and 2, respectively.
<script>
$(document).ready(function() {
$('#educationalForm').submit(function(event){
event.preventDefault();
var formData = new FormData($('#educationalForm')[0]);
$.ajax({
url:'{{ route('educational.store') }}',
method: 'POST',
data: formData,
cache:false,
contentType: false,
processData: false,
success:function(data){
const variables = ['grade', 'major', 'end'];
variables.forEach(variable => {
if(data[variable] === null) data[variable] = '';
});
const newRowNum = $('#educationalForm tr').length + 2;
let html = '' +
'<tr>'+
'<td class="fw-normal" id="demo">'+ (newRowNum) +'</td>'+
'<td class="fw-normal">'+data.grade+'</td>'+
'<td class="fw-normal">'+data.major+'</td>'+
'<td class="fw-normal">'+data.end+'</td>'+
'<td>'+
'<form method="post" id="educational-destroy">'+
'#csrf'+
'#method('DELETE')'+
'<div class="btn-group">'+
'<a data-id="'+data.id+'" class="btn btn-info btn-sm" id="educationalEdit" data-bs-toggle="modal" data-bs-target="#educationalModal">ویرایش</a>'+
'<button data-id="'+data.id+'" type="button" class="btn btn-danger btn-sm" id="educationalDestroy">حذف</button>'+
'</div>'+
'</form>'+
'</td>'+
'</tr>';
$('#educationalTable').append(html);
$('#educationalForm').trigger('reset');
},
});
});
showEducationals();
function showEducationals() {
$.get('{{ route('educational.index') }}', function (data) {
$('#educationalTable').html("");
$.each(data, function (key, val) {
const variables = ['grade', 'major', 'end'];
variables.forEach(variable => {
if(val[variable] === null) val[variable] = '';
});
$('#educationalTable').append('<tr>'+
'<td class="fw-normal">'+ (key+1) +'</td>'+
'<td class="fw-normal">'+val.grade+'</td>'+
'<td class="fw-normal">'+val.major+'</td>'+
'<td class="fw-normal">'+val.end+'</td>'+
'<td>'+
'<form method="post" id="educational-destroy">'+
'#csrf'+
'#method('DELETE')'+
'<div class="btn-group">'+
'<a data-id="'+val.id+'" class="btn btn-info btn-sm" id="educationalEdit" data-bs-toggle="modal" data-bs-target="#educationalModal">ویرایش</a>'+
'<button data-id="'+val.id+'" type="button" class="btn btn-danger btn-sm" id="educationalDestroy">حذف</button>'+
'</div>'+
'</form>'+
'</td>'+
'</tr>'
);
});
});
}
$(document).on('click', '#educationalEdit', function(event) {
event.preventDefault();
var id = $(this).data('id');
$.ajax({
type:'get',
url:'/educational/'+id+'/edit',
contentType: "application/json; charset=utf-8",
dataType: "json",
success:function (data) {
console.log(data);
$('#id').val(data.educational.id);
$('#edit_grade').val(data.educational.grade);
$('#edit_major').val(data.educational.major);
$('#edit_avg').val(data.educational.avg);
$("input[name='edit_start']").val(data.educational.start);
$("input[name='edit_end']").val(data.educational.end);
$('#edit_docPlaceName').val(data.educational.docPlaceName);
$('#edit_thesisTitle').val(data.educational.thesisTitle);
$('#edit_docPlaceCountry').val(data.educational.docPlaceCountry);
$('#edit_docPlaceCity').val(data.educational.docPlaceCity);
},
});
});
$(document).on('click', '#educationalUpdate', function(event) {
event.preventDefault();
var id = $('#id').val();
var file = $('#edit_upload_doc').prop('files')[0];
var formData = new FormData($('#educationalFormUpdate')[0]);
formData.append('file', file);
$.ajax({
type: 'POST',
url: '/educational/'+id,
dataType: 'JSON',
data: formData,
cache: false,
contentType: false,
processData: false,
success: function (response) {
console.log(response);
$('#educationalModal').modal('hide');
showEducationals();
},
});
});
$(document).on('click', '#educationalDestroy', function(event) {
event.preventDefault();
$.ajax({
url:'educational/'+$(this).data('id'),
type: 'DELETE',
dataType: 'json',
data: {
_token: '{{ csrf_token() }}'
},
success: function(response) {
$('#educationalsTable').html('');
showEducationals();
},
error: function(response) {
console.log(response);
},
});
});
});
</script>
So in general I can get counting right until elements are getting removed. If I got 3 rows I got a count of 1. 2. 3. but if I remove all of them and add again 3 rows I got 4. 5. 6. BUT I need 1. 2. 3. again

You should reset the counter every time you re-render the whole table.
You could move the count to inside your rendering function, but it is not strictly necessary, because jQuery's each function already provides an index (you are naming it key) which you could use instead of count.
Therefore, you can do:
function showEducationals() {
$.get('{{ route('educational.index') }}', function (data) {
$('#educationalTable').html("");
$.each(data, function (key, val) {
const variables = ['grade', 'major', 'end'];
variables.forEach(variable => {
if(val[variable] === null) val[variable] = '';
});
$('#educationalTable').append('<tr>'+
'<td class="fw-normal">'+ (key+1) +'</td>'+ // using key instead of count
Notice I also removed id=demo. This is because you are creating several cells with the id=demo (in '<td class="fw-normal" id="demo">'+count+++'</td>'+) and ideally ids should be unique.
About adding new rows use, instead of i, the number of rows the table actually has:
$('#educationalForm').submit(function(event){
event.preventDefault();
var formData = new FormData($('#educationalForm')[0]);
$.ajax({
url:'{{ route('educational.store') }}',
method: 'POST',
data: formData,
cache:false,
contentType: false,
processData: false,
success:function(data){
const variables = ['grade', 'major', 'end'];
variables.forEach(variable => {
if(data[variable] === null) data[variable] = '';
});
const newRowNum = $('#educationalTable tr').length + 1; // added this
let html = '' +
'<tr>'+
'<td class="fw-normal">'+ (newRowNum) +'</td>'+ // edited this
In addition, you should remove the i and count variables, as they are no longer necessary:
showEducationals();
let i; // remove this
let count = 1; // remove this
function showEducationals() {
// ...
);
i = count // remove this
});

Related

Calculate the json's value then show in html

I have a json array:
[{"value": "1"},{"value": "2"},{"value": "3"},{"value": "4"},{"value": "5"},{"value": "6"}]
My code is :
$.ajax({
url: "120.58.243.11:8080/needCal/myJson.json",
dataType: 'json',
success: function(data) {
var items = [];
$.each(data, function(key, value) {
items.push("<tr>");
items.push("<td id=''" + key + "''>" + value.value+ < /td>");
items.push("<td id=''" + key + "''>" + total of values + < /td>");
items.push("</tr>");
});
}
});
I want to calculate the values, how to do with that?
$.ajax({
url: "120.58.243.11:8080/needCal/myJson.json",
dataType:'json',
success: function(data){
var items = [];
var totalOfValue = 0;
$.each(data,function(key,value){
totalOfValue = totalOfValue + parseInt(value.value);
});
$.each(data,function(key,value){
items.push("<tr>");
items.push("<td id='" +key+ "'>" + value.value+</td>");
items.push("<td id='" +key+ "'>" + totalOfValue +</td>");
items.push("</tr>");
});
}
}
);
A simple way is to use the reduce method:
Something like this:
var total = arr.reduce(function(t, v) {
return t += Number(v.value);
}, 0);

Refresh dropdown with Jquery

I have one dropdown for displaying the month from January to current month in jQuery mobile. I'm getting the data using JSON. But the problem is selected option is not getting refresh.
$.ajax({
type: "POST",
url: "../modules/loadmonth.php?id=getoption&studid=" + $('#studentids').val(),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$.each(data, function (i, item) {
var sel;
if (date[i].optval == date[i].curmon) {
sel = "selected";
} else {
sel = "";
}
result = '<option value=' + data[i].optval + '' + sel + '>' + data[i].opt + '</option>';
});
$('#getmon').append(result);
}
});
The value attribute should be in quotes, but more importantly you'll need a space between it and your selected attribute.
I have added selectmenu after append then it works.
$.ajax({
type: "POST",
url: "../modules/loadmonth.php?id=getoption&studid=" + $('#studentids').val(),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$.each(data, function (i, item) {
var sel;
if (date[i].optval == date[i].curmon) {
sel = "selected";
} else {
sel = "";
}
result = '<option value=' + data[i].optval + '' + sel + '>' + data[i].opt + '</option>';
});
$('#getmon').append(result).selectmenu('refresh',true);
}
});

How to maintain the dynamic generated textboxes after postback

I am generating dynamic html textboxes in my aspx page. I add a button for do some functionality. now whenever I click on my button it post back and all the dynamic generated textboxes go from my form for this I have to add it again. But I want to maintain these textboxes after postback. Here is the code how i am generating textboxes
<script type="text/javascript">
var textid = null;
var textid1 = null;
$(document).ready(function () {
setupAutoComplete(textid);
setupAutoComplete1(textid1);
var counter = 2;
$("#addButton").click(function () {
if (counter > 5) {
alert("Limit Exceeds");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
textid = "textbox" + counter;
textid1 = "textbox" + counter+1;
// newTextBoxDiv.after().html('<label>Textbox #' + counter + ' : </label>' +
// '<input type="text" name="textbox' + counter +
// '" id="textbox' + counter + '" value="" class="auto">');
newTextBoxDiv.after().html('<div class="fields-left"><label> Leaving from</label><input type="text" name="textbox' + counter + '" id="textbox' + counter + '" class="auto"/> </div><div class="fields-right"> <label> Going to</label> <input type="text" name="textbox' + counter + '" id="textbox' + counter + 1 + '" class="auto"/> </div>');
newTextBoxDiv.appendTo("#TextBoxesGroup");
setupAutoComplete(textid);
setupAutoComplete1(textid1);
counter++;
});
$("#removeButton").click(function () {
if (counter == 1) {
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
});
var setupAutoComplete= function SearchText2(textid) {
$('.auto').autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Home.aspx/GetAutoCompleteData",
data: "{'code':'" + document.getElementById(textid).value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
var setupAutoComplete1 = function SearchText3(textid1) {
$('.auto').autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Home.aspx/GetAutoCompleteData",
data: "{'code':'" + document.getElementById(textid1).value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
</script>
now in this code I am generating maximun 10 textboxes two in each row and after that I write some code for json autocomplete for each dynamic generated textbox. Now problem is this when i click on my button after that its postback and all the textboxes and its values goes away. I am unable to maintain these textboxes. Can anybody tell me how can we maintain the dymanic generated textboxes after postback?
Thanks

jQuery POST refreshing the page

I have some jQuery that takes the value of a text input and puts it into a MySQL database. However, when the jQuery runs, the page refreshes and the variables in the form appear in the URL almost as GET variables. However, none of the variables are GET. Ideally, I would like the page not to refresh.
jQuery:
$('.commentBox').keypress(function(e) {
if(e.which == 13) {
if ($.trim($(this).val()) == ""){
$('#nocomment').modal('show');
}
else {
var form = $(this).siblings('.commentForm');
var commentbox = $(this).val();
$.ajax({
type: "POST",
url: "../comment",
data: form.serialize(),
success: function(){
commentbox.val('');
form.siblings('.commentContainer').append(response);
}
});
}
}
});
HTML (echoed from PHP):
<form class='commentForm'>
<input type='hidden' name='record_id' value='$answerid[$f]' />
<input type='hidden' name='question_id' value='$q' />";
<input type='text' class='commentBox' placeholder='...comment' name='comment' autocomplete='off' />";
</form>
You have to either return false or prevent default, which will stop the form from submitting:
$('.commentBox').keypress(function(e)
{
if(e.which == 13)
{
e.preventDefault(); // <-- This will stop the form from submitting.
if ($.trim($(this).val()) == "")
{
$('#nocomment').modal('show');
}
else
{
var form = $(this).closest('.commentForm');
var commentbox = $(this).val();
$.ajax({
type: "POST",
url: "../comment",
data: form.serialize(),
success: function(){
commentbox.val('');
form.siblings('.commentContainer').append(response);
}
});
}
}
});
You need to prevent the default action from taking place when hitting the enter key, which is form submission via GET.
e.preventDefault();
$( '.commentBox' ).keypress(function( e ) {
if( e.which === 13 ) {
// Prevent the default only when it's the enter key
e.preventDefault();
if ( $.trim($(this).val()) === '' ){
$('#nocomment').modal( 'show' );
}
else {
var form = $( this ).siblings( '.commentForm' );
var commentbox = $( this ).val();
$.ajax({
type: "POST",
url: "../comment",
data: form.serialize(),
success: function(){
commentbox.val( '' ;
form.siblings( '.commentContainer' ).append( response );
}
});
}
}
});

Reading from JSONP

I have the following script which is able to access a jsonp feed and get data from it:
$(document).ready(function() {
get_jsonp_feed();
function get_jsonp_feed() {
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?q=%20SELECT%20*%20FROM%20html%20WHERE%20url%3D%22http%3A%2F%2Fnews.bbc.co.uk%2Fweather%2Fforecast%2F4276%3Fsearch%3Dgerrards%2520cross%26itemsPerPage%3D10%26region%3Dworld%26area%3DGerrards%2520Cross%22%20and%20xpath%20%3D%20'%2F%2Ftable%2Ftbody%2Ftr'&format=json&diagnostics=true&callback=cbfunc",
type: 'GET',
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: 'cbfunc',
error: function(xhr, status, error) {
alert(xhr.responseText);
},
success: function(data) {
var itemList = data.query;
alert(itemList.count);
/*
var buildHTML = [];
for (var i = 0; i < 5; i++) {
buildHTML.push('<div class="container">' + itemList[i].title + '<br /><span class="dateandtime">' + itemList[i].pubDate + '</span></div>');
}
$('.portlet-content').empty().append(buildHTML.join('<hr />'))
*/
}
});
}
});
That gives me 5 which is right. I now want to get data which is more embedded in the jsonp, but I have having difficulty. For example, I want to get:
data.query.results.tr.td.div.abbr.title
How would I go about getting that?
Here is a jsfiddle of it returning 5:
http://jsfiddle.net/B6hRG/1/
Here is some fixed code to get JSONP instead of XML:
$(document).ready(function() {
get_jsonp_feed();
function get_jsonp_feed() {
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%20%3D%20'http%3A%2F%2Fnews.bbc.co.uk%2Fweather%2Fforecast%2F4276%3F%26search%3Dgerrards%2520cross%26itemsPerPage%3D10%26region%3Dworld%26area%3DGerrards%2520Cross'%20and%20xpath%20%3D%20'%2F%2Ftbody%2Ftr'&format=json&callback=?",
type: 'GET',
dataType: 'jsonp',
error: function(xhr, status, error) {
alert(xhr.responseText);
},
success: function(data) {
var itemList = data.query;
alert(itemList.count);
/*
var buildHTML = [];
for (var i = 0; i < 5; i++) {
buildHTML.push('<div class="container">' + itemList[i].title + '<br /><span class="dateandtime">' + itemList[i].pubDate + '</span></div>');
}
$('.portlet-content').empty().append(buildHTML.join('<hr />'))
*/
}
});
}
});
To get data like data.query.results.tr.td.div.abbr.title you'd have to either use a for loop on the data.query.results.tr.td object, and any others with siblings, or use XML and get the raw html, put it into a document fragment and use jQuery on that.