Here's my button that calls the try again function
function tryagain(context) {
//alert(context.parent());
var somedata = context.parent().parent().find('td')[0].innerHTML;
//alert(somedata);
$.ajax({
type: "POST",
url: "checkagain.php",
data: {
somedata: somedata
},
success: function (data) {
var grandparent = context.parent().parent();
var parent = context.parent();
context.remove();
parent.remove(); * * grandparent.append("<td>" + data + "</td>");
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick='tryagain($(this))' class='btn btn-danger'></button>
When I append the td with grandparent, sometimes it appends it fine and most times it just adds another empty td at the end as attached in picture provided data is not empty.
Related
I want to get dynamic data in one <div id = "view"> </div>
I use ajax to take dynamic data from api and insert it with var a. I will try to describe with code what I want to get exactly
$.ajax({
url:'url', // [{id:"1",name:"name1"},{id:"2",name:"name2"},{id:"3",name:"name3"}];
method: 'get',
dataType: "json",
success: function (data) {
data.forEach(function(elem){
var a = "ID: " elem.id +"<b>" + elem.name"</b> ";
})
$('#view').html(a);
}
});
Here you are getting the result in a foreach loop which means "a" contains all the results returned by the ajax call, in order to show only one result in a single div we would need to put the value of each loop call in the div, one way is to append the div for each result inside a parent div. I have modified your code below hopefully it helps.
HTML:
<div id = "dataholder"> </div>
JS:
$.ajax({
url:'url', // [{id:"1",name:"name1"},{id:"2",name:"name2"},{id:"3",name:"name3"}];
method: 'get',
dataType: "json",
success: function (data) {
var j = 1;
data.forEach(function(elem){
var a = "ID: " elem.id +"<b>" + elem.name"</b> ";
var view_div_id = "view-"+j;
$( "#inner" ).append( "<div id ="+ view_div_id +"> </div>" );
$('#view-'+j).html(a);
j++;
})
}
});
I have this div
<div class='additional_comments'>
<input type="text" id='additional_comments_box', maxlength="200"/>
</div>
Which will only sometimes appear on the page if jinja renders it with an if statement.
This is the javascript i have to send an ajax request:
$(document).ready(function() {
var button = $("#send");
$(button).click(function() {
var vals = [];
$("#answers :input").each(function(index) {
vals.push($(this).val());
});
vals = JSON.stringify(vals);
console.log(vals);
var comment = $('#additional_comments_box').val();
var url = window.location.pathname;
$.ajax({
method: "POST",
url: url,
data: {
'vals': vals,
'comment': comment,
},
dataType: 'json',
success: function (data) {
location.href = data.url;//<--Redirect on success
}
});
});
});
As you can see i get the comments div, and I want to add it to data in my ajax request, however if it doesnt exist, how do I stop it being added.
Thanks
You can use .length property to check elements exists based on it populate the object.
//Define object
var data = {};
//Populate vals
data.vals = $("#answers :input").each(function (index) {
return $(this).val();
});
//Check element exists
var cbox = $('#additional_comments_box');
if (cbox.length){
//Define comment
data.comment = cbox.val();
}
$.ajax({
data: JSON.stringify(data)
});
I hope I can explain my issue clearly.
I am running a function to get values from a database using ajax, and adding each result as a row in a table. This is so the user can delete or edit any row they want. I'm adding IDs dynamically to the columns and also the edit and delete buttons which are generated. So it looks like this:
My code:
function getstationdata(){
var taildata1 = $('#tailnumber2').val();
var uid = $('#uid').val();
$.ajax({
// give your form the method POST
type: "POST",
// give your action attribute the value ajaxadd.php
url: "ajaxgetstationdata.php",
data: {tailnumber:taildata1, uid:uid},
dataType: 'json',
cache: false,
})
.success(function(response) {
// remove all errors
$('input').removeClass('error').next('.errormessage').html('');
// if there are no errors and there is a result
if(!response.errors && response.result) {
var trHTML = '';
$.each(response.result, function( index, value) {
trHTML += '<tr><td><input type="text" value="' + value[2] + '"></td><td><input type="text" class="weightinputclass"value="' + value[3] + '"></td><td><input type="text" class="arminputclass"value="' + value[4] + '"></td><td><input type="text" class="momentinputclass" value="' + value[5] + '"></td><td><button id="updatecgbtn" onclick="updatecg()"class="editbuttonclass">Edit</button></td><td><button id="deletecgbtn" class="deletebuttonclass"">Delete</button></td></tr>';
});
$('#mbtbody').html('');
$('#mbtbody').html(trHTML);
var ID = 0;
$('.weightinputclass').each(function() {
ID++;
$(this).attr('id', 'weightinputboxID'+ID);
});
var ID = 0;
$('.arminputclass').each(function() {
ID++;
$(this).attr('id', 'arminputboxID'+ID);
});
var ID = 0;
$('.momentinputclass').each(function() {
ID++;
$(this).attr('id', 'momentinputboxID'+ID);
});
var ID = 0;
$('.editbuttonclass').each(function() {
ID++;
$(this).attr('id', 'editbutton'+ID);
});
var ID = 0;
$('.deletebuttonclass').each(function() {
ID++;
$(this).attr('id', 'deletebutton'+ID);
});
} else {
// append the error to the form
$.each(response.errors, function( index, value) {
// add error classes
$('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
});
}
});
}
The code I have when adding the info is in a form and it looks like this:
$('#addstations').on('submit', function(e){
e.preventDefault();
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: 'json',
cache: false,
})
.success(function(response) {
$('input').removeClass('error').next('.errormessage').html('');
if(!response.errors && response.result) {
$.each(response.result, function( index, value) {
chartdata4=(tailnumber3.value)
});
} else {
// append the error to the form
$.each(response.errors, function( index, value) {
// add error classes
$('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
});
}
});
});
I searched a bit on the internet and found out that I can't add a form inside my table for each row which would have been easy to do and I can reuse my code which I use when adding new info.
So, can someone please point me in the right direction?
Here is the direction you could go
$('#formTable').on('click',"button" function(e){
var $row = $(this).closest("tr"), $form = $("#addstations");
var data = {
passenger:$row.find("passengerClass").val(),
weight :$row.find("weightClass").val()
} // no comma on the last item
data["type"]=this.className=="deletebuttonclass"?"delete":"edit";
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
dataType: 'json',
cache: false,
})
...
I assume that the problem is that you want to add a form as a child of a table / tbody element to wrap your row. You cannot do that and the browser will most likely strip the form tags, leaving you with nothing to serialize.
There are different solutions for that, for example:
Build the data object manually in javascript when a button on a row is clicked;
Use a non-form grid solution for your layout.
Add each row in its own table and have the form wrap that table
The third solution is a bit of a hack, I would use the first or the second myself.
I have a textbox in my view page. when i click on imageIcon,it will take data from db and return in alert successfully. But, when i try to bind this response data to textbox, it is not binded correctly. My code in view page is as following :
#foreach (var dateitem in list)
{
<td id="HoursTxt">
#Html.TextAreaFor(modelitem => dateitem.Hours, new { id = string.Format("txtHours"), style = "width:50%;height:70%;" })
#Html.Hidden("CuDate", dateitem.Date)
<img src="~/Images/comment.png" class="prevtest" />
<div style="border:solid;display:none;">
<input type="text" id="TxtNotess" />
<input type="button" id="BtnComment" value="Save" />
</div>
</td>
}
In my onclick event of imageIcon jquery is following:
$('.prevtest').on('click', function () {
var Cudate = $(this).prev('#CuDate').val();
var ProjId = parseInt($(this).parents('tr').find('input[type="hidden"]').val());
var TskId =parseInt($(this).parents('tr').find('td').find('#testTaskId').val());
$.ajax({
type: "POST",
url: "/Timesheet/GetComments?ProjectId=" + ProjId + "&TaskId= " + TskId + "&date= " + Cudate,
success : function(data)
{
alert(data);
$('#TxtNotess').val(data);
alert('success');
},
error:function()
{
alert('Error');
}
});
$(this).next().toggle();
});
the text box with id TxtNotess not bind with response value
Can anyone help me to do this..
Thanks in advance..
First: ID of an element must be unique so use class for the textfield TxtNotess.
<input type="text" class="TxtNotess" />
Then, in the success handler find the textfild with class TxtNotess inside the next sibling of the clicked element
$('.prevtest').on('click', function () {
var Cudate = $(this).prev('#CuDate').val();
var ProjId = parseInt($(this).parents('tr').find('input[type="hidden"]').val());
var TskId = parseInt($(this).parents('tr').find('td').find('#testTaskId').val());
$.ajax({
type: "POST",
url: "/Timesheet/GetComments?ProjectId=" + ProjId + "&TaskId= " + TskId + "&date= " + Cudate,
context: this,//pass a custom context to the ajax handlers - here the clicked element reference
success: function (data) {
alert(data);
$(this).next().find('.TxtNotess').val(data);//find the target textfield
alert('success');
},
error: function () {
alert('Error');
}
});
$(this).next().toggle();
});
$('.prevtest').on('click', function () {
var Cudate = $(this).prev('#CuDate').val();
var ProjId = parseInt($(this).parents('tr').find('input[type="hidden"]').val());
var TskId = parseInt($(this).parents('tr').find('td').find('#testTaskId').val());
$.ajax({
type: "POST",
url: "/Timesheet/GetComments?ProjectId=" + ProjId + "&TaskId= " + TskId + "&date= " + Cudate,
context: this,//pass a custom context to the ajax handlers - here the clicked element reference
success: function (data) {
alert(data);
$('.TxtNotess').val(data);//find the target textfield
alert('success');
},
error: function () {
alert('Error');
}
});
$(this).next().toggle();
});
I gets resolved by using class name for textbox..
I want to fetch data from div tag which set contenteditable=true
I have used autosuggestion in that..Data is successfully fetched but when I write item which is written in autosuggestion field then it wont be fetched because it add HTML tag and it wont save into database
My code
if data is changed:
var timeoutID;
$('[contenteditable]').bind('DOMCharacterDataModified', function () {
clearTimeout(timeoutID);
$that = $(this);
timeoutID = setTimeout(function () {
$that.trigger('change')
}, 50)
});
$('[contentEditable]').bind('change', function () {
getTextChangeContent();
});
UPDATE
function getTextChangeContent() {
var ma = document.getElementById('myAudio');
var remove = ma.src.slice(0, -4);
var path = remove.substring(remove.lastIndexOf("/") + 1);
var newPath = path.concat('.wav');
var text_id = document.getElementById('textbox');
var textdata = text_id.innerHTML;
$.ajax(
{
type: "POST",
url: '#Url.Action("getChangeContent")',
dataType: "json",
mtype: "post",
data: { arg: varid, content: textdata, path: newPath },
async: true,
success: function (data) {
alert(data + " DATA");
}
});
}
when I changed data and use autosuggestion then it will show data as
The door is blacl <span class="atwho-inserted">[[Ceilings]]</span>
How to ignore html tag and take only values of that?
Plz suggest me
Retrieve innerText rather than innerHTML in order to ignore the HTML content. If you want only the content inside the html tag with class .atwho-inserted, then retrieve only that content.
var textdata = text_id.innerText;