Thanks For viewing this post.i am facing a jquery issue .After a successful AJAX call, I want to update an element on page. However, it is not being updated.
what am i doing i am opening a text box on click of span then add text and and on focus out event i am making Ajax call but cant update new text to same span when that i clicked before please help me
here is my js code
$(document).on('click', '.td-edit', (function (e0) {
var thisObj = $(this);
var olddata = thisObj.html();
var newDom = '<input type="text" value="' + olddata + '" class="new-value" style="border:#bbb 1px solid;padding-left:5px;width:75%;"/ >';
thisObj.parent('td').html(newDom);
}));
$(document).on('focusout', '.new-value', (function (e1) {
var thisObj = $(this);
var type = thisObj.parent('td').attr('class');
var newData = thisObj.val();
var santanceId = thisObj.parent('td').parent('tr').attr('id');
santanceId = parseInt(santanceId.replace('tr', ''));
thisObj.parent('td').html('\'<img src="uploads/loading.gif">\'');
if (type === 'sentnc') {
$.ajax({
type: "POST",
url: "operations.php",
data: {
santanceId: santanceId,
sentnc: newData
},
success: function () {
var newDom = '<span class="td-edit">' + newData + '</span>';
thisObj.parent('td').html(newDom);
}
});
}
}));
HTML:
<div class="chat-space nano nscroller">
<div id="table-row">
<table id="rep-data">
<tbody>
<tr>
<th align="left">Sentences</th>
<th align="left" colspan="3">Reps</th>
</tr>
<tr id="tr1" rowspan="2">
<td class="sentnc"><span class="td-edit">Rana is working</span></td>
<td colspan="3" class="senrep"><span class="td-edit">p1.ref = I, p1.name = julie</span><br>
<br>
<span style="color:#000;">Guess Rep1: </span><span id="1gr1">p1.ref = I, p1.has = name1, p1.name.made_from = rana</span><br>
<span style="color:#000;">Guess Rep2: </span><span id="2gr1">p1.ref = I, p1.name = rana</span><br>
<span><a style="color:#3399FF !important;" alt="1" rel="1 " class="updateGuess" id="upd1" href="javascript:void(0);">Update Guess Rep</a></span><br>
<br></td>
</tr>
</tbody>
</table>
</div>
Your success handler should be:
success: function (data) {
var newDom = '<span class="td-edit">' + data + '</span>';
thisObj.parent('td').html(newDom);
}
Here, the data is the data returned by your server, after the ajax Call
Related
function getAnnoDetailsForTeacher(){
var tcounter = 1;
$.ajax({
url:'<%=contextPath%>/show/announcementsForTeacher',
headers: {
'Authorization':'${sessionScope.token}'
},
type:'GET',
data: {
'loginId' : '${loginId}'
},
success:function(data){
$('#annoTable tbody').empty();
for(var i=0; i<data.length;i++)
{
var aid = data[i].id;
var date = data[i].date;
var subject = data[i].subject;
var details = data[i].details;
var status = data[i].status;
$('#annoTable tbody').append('<tr data-toggle="modal" data-target="#viewTAnnoModal"><td id="tCounter'+aid+'"><strong>'+tcounter+
'</strong></td><td id="tDate'+aid+'"><strong>'+date+
'</strong></td><td id="tSubject'+aid+'"><strong>'+ subject +
'</strong></td><td id="tDetails'+aid+'" class="cell expand-small-on-hover"><strong>'+ details +
'</strong></td><td><button type="button" id="tAnnoBtn'+aid+'" onclick="viewTAnno()" class="viewbtn" data-toggle="modal" data-target="#" style="display:block;">View</button>'+
'</td>'+
......+
'</tr>');
tcounter += 1;
}
$('#tnoti').empty();
$('#tnoti').css('display','block');
$('#tnoti').append(tcounter-1);
},
error:function(e){
console.log(e)
}
});
return tcounter;
}
my goal is to unbold a row when clicked on view btn (where id is dynamic:i d="tAnnoBtn'+aid+'") inside the jQuery.
Here is the unbold jQuery
$('#tAnnoForm').on('click', '.viewbtn', function() {
const fooTCounter = document.getElementById("tCounter");
fooTCounter.innerHTML = fooTCounter
.innerHTML
.replace(/<strong>/g, "")
.replace(/<\/strong>/g, "");
const fooTDate = document.getElementById("tDate");
fooTDate.innerHTML = fooTDate
.innerHTML
.replace(/<strong>/g, "")
.replace(/<\/strong>/g, "");
const fooTSubject = document.getElementById("tSubject");
fooTSubject.innerHTML = fooTSubject
.innerHTML
.replace(/<strong>/g, "")
.replace(/<\/strong>/g, "");
const fooTDetails = document.getElementById("tDetails");
fooTDetails.innerHTML = fooTDetails
.innerHTML
.replace(/<strong>/g, "")
.replace(/<\/strong>/g, "");
});
problem is every element is created dynamically with dynamic id (td cells and buttons)
so how can i input the dynamic ids inside the unbold jQuery??
like in jQuery it should go like document.getElementById("tCounter1") where 1 is concatenated with tCounter.
also in '.viewbtn', it should go like '#tAnnoBtn1' where 1 is dynamically concatenated with tAnnoBtn.
check this viewTAnno(aid) function
function viewTAnno(aid)
{
var viewed;
$.ajax({
url:'<%=contextPath%>/show/annoViewedForTeacher',
headers: {
'Authorization':'${sessionScope.token}'
},
type:'GET',
data: {
'loginId' : '${loginId}',
'anno_id' : aid
},
success:function(data){
//alert("New Announcement Added Successsfully");
console.log(data);
viewed =data;
$('#tAnnoTable').on('click', '.viewbtn', function() {
if(viewed==0){
//get closest tr > loop through tds
$(this).closest("tr").find("td:not(:last)").each(function() {
//replace text
$(this).text($(this).text().replace(/<strong>/g, "")
.replace(/<\/strong>/g, ""))
//tcounter=tcounter-1;
$.ajax({
url:'<%=contextPath%>/show/annoViewedForTeacher',
headers: {
'Authorization':'${sessionScope.token}'
},
type:'POST',
data: {
'loginId' : '${loginId}',
'anno_id' : aid
},
success:function(data){
console.log(data);
},
error:function(e){
console.log(e)
}
});
})
}
})
},
error:function(e){
console.log(e)
}
});
return viewed;
}
i want to unbold a particular row upon clicking on view so that it also changes in db just like gmail inbox. how can i do that?
You can simply iterate through your tds where view button has been clicked then using $(this).text(..) replace <strong> tag with ''
Demo Code :
$('#annoTable').on('click', '.viewbtn', function() {
//get closest tr > loop through tds
$(this).closest("tr").find("td:not(:last)").each(function() {
//replace text
$(this).text($(this).text().replace(/<strong>/g, "")
.replace(/<\/strong>/g, ""))
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="annoTable">
<tbody>
<tr data-toggle="modal" data-target="#viewTAnnoModal">
<td id="tCounter1"><strong>1</strong></td>
<td id="tDate1"><strong>0.005997001499250375</strong></td>
<td id="tSubject1"><strong>Abc</strong></td>
<td id="tDetails1" class="cell expand-small-on-hover"><strong>Somwthing..</strong></td>
<td><button type="button" id="tAnnoBtn1" onclick="viewTAnno()" class="viewbtn" data-toggle="modal" data-target="#" style="display:block;">View</button></td>
</tr>
<tr data-toggle="modal" data-target="#viewTAnnoModal">
<td id="tCounter2"><strong>2</strong></td>
<td id="tDate2"><strong>0.005997001499250375</strong></td>
<td id="tSubject2"><strong>Abc</strong></td>
<td id="tDetails2" class="cell expand-small-on-hover"><strong>Somwthing..</strong></td>
<td><button type="button" id="tAnnoBtn2" onclick="viewTAnno()" class="viewbtn" data-toggle="modal" data-target="#" style="display:block;">View</button></td>
</tr>
</tbody>
</table>
I'm starting to fiddle with jquery and I'm going kind of crazy... I am making a little script to fetch football players from a fantasy football website. I have the following html and JS to work with:
<table class="table table-striped">
<thead>
<tr>
<th>Jugador</th>
<th>Equipo</th>
<th>Puntos</th>
</tr>
</thead>
<tbody>
<tr class="jugador">
<td>Sergio-Ramos</td>
<td>Real Madrid</td>
<td></td>
</tr>
<tr class="jugador">
<td>Messi</td>
<td>F.C. Barcelona</td>
<td></td>
</tr>
<tr class="jugador">
<td>Morales</td>
<td>Levante</td>
<td></td>
</tr>
<tr class="jugador">
<td>Bale</td>
<td>Real Madrid</td>
<td></td>
</tr>
</tbody>
</table>
And the following JS:
<script>
var puntos_jugador = [];
$(".jugador").each(function(index) {
var nombre = $(this).find("td").eq(0).text();
puntos_jugador = puntosJugador(nombre);
console.log(nombre);
console.log(puntos_jugador);
$(this).find("td").eq(2).text("Hola");
});
function puntosJugador(nombre) {
var puntos = [];
$.get('https://www.comuniazo.com/comunio/jugadores/' + nombre, function(response) {
$(response).find('.tr-points, .tr-status').each(function(fila) {
//var jornada = $(this).find("td").eq(0).text();
var puntos_jornada = $(this).find(".bar").text();
puntos.push(puntos_jornada);
//console.log('Jornada ' + jornada + ' ' + puntos);
});
});
return puntos;
}
</script>
The thing is the console.log(puntos_jugador) does return an array filled with the information:
However I cannot access puntos_jugador[0] or try puntos_jugador.toString() .
Could anyone tell me what am I doing wrong (maybe everything) or give me some orientation on how to fix this?
Thanks on beforehand and sorry for my low JS level, I'm working on it.
The problem in your code is that you are doing an asynchronous call with $.get and then you return the result directly without waiting for the response, which will always be the empty array define above.
You should wait for the response and then call a callback (or use promises)
Something like this:
var puntos_jugador = [];
$(".jugador").each(function(index) {
var nombre = $(this).find("td").eq(0).text();
puntosJugador(nombre, function(result) {
console.log('done');
puntos_jugador = result;
console.log(nombre);
console.log(puntos_jugador);
});
$(this).find("td").eq(2).text("Hola");
});
// <---- HERE pass a callback and then call it when you have all results.
function puntosJugador(nombre, cb) {
var puntos = [];
$.get('https://www.comuniazo.com/comunio/jugadores/' + nombre, function(response) {
console.log('response ',response)
$(response).find('.tr-points, .tr-status').each(function(fila) {
//var jornada = $(this).find("td").eq(0).text();
var puntos_jornada = $(this).find(".bar").text();
puntos.push(puntos_jornada);
//console.log('Jornada ' + jornada + ' ' + puntos);
console.log('here', puntos);
});
cb(puntos);
});
}
Refactor your method to this:
function puntosJugador(nombre) {
var puntos = [];
$.get('https://www.comuniazo.com/comunio/jugadores/' + nombre, function(response) {
$(response).find('.tr-points, .tr-status').each(function(fila) {
//var jornada = $(this).find("td").eq(0).text();
var puntos_jornada = $(this).find(".bar").text();
puntos.push(puntos_jornada);
//console.log('Jornada ' + jornada + ' ' + puntos);
});
return puntos;
});
}
I am relatively new to front.
I managed to make my table dynamic which becomes textarea when clicked and back to static table cell when lose the focus.
What I want to do here is sending the value every time it loses focus.
It does with Ajax, but the value in clicked cell is always disappearing when loses control. it happens at any cell.
Here is my code.
HTML
<body>
<div class="container">
<br>
<h2>English lines are under here</h2>
<h5>Click each row to modify</h5>
<br>
<table id="btable" class="bg-light table table-hover">
<th class= "text-center">No</th>
<th class= "text-center">Word</th>
<th class= "text-center">Dialogue</th>
<th class= "text-center">Practice</th>
<c:forEach items="${list}" var="engboardVO">
<tr>
<td class="bid" data-name="bid">${engboardVO.bid}</td>
<td class="word" data-name="word" data-editable>${engboardVO.word}</td>
<td class="dialogue" data-name="dialogue" data-editable>${engboardVO.dialogue}</td>
<td class="practice" data-name="practice" data-editable>${engboardVO.practice}</td>
</tr>
</c:forEach>
</table>
Script
$("table").on("click", "[data-editable]", function(){
var $el = $(this);
var str = $el.text();
console.log(str);
var $input = $('<textarea rows=5 style="width:500px"/>').val( str );
$el.html($input);
$input.focus();
var field_name = $el.attr('data-name');
var save = function(bid, newWord, newDialogue, newPractice){
var $td = $input.val();
$.ajax({
type : "POST",
url : "/tight",
data : JSON.stringify({
bid : bid,
word : newWord,
dialogue : newDialogue,
practice : newPractice
}),
dataType: "json",
success : function(msg){
if (msg["status"] == 'success'){
$input.replaceWith($td);
} else {
alert("Fail");
$input.replaceWith($el);
}
},
error : function(msg) {
alert("ajax fail to get data from server");
}
});
};
$($input).blur(function(){
var bid = $(this).closest('tr').find('td.bid').text();
var newWord = $(this).closest('tr').find('td.word').text();
var newDialogue = $(this).closest('tr').find('td.dialogue').text();
var newPractice = $(this).closest('tr').find('td.practice').text();
console.log(newPractice);
save(bid, newWord, newDialogue, newPractice)
})
});
We cannot use .text() on input and textarea, in which case we would have to use the function .val().
I noticed that you stored the field name but never used it so it would come in handy when trying to get the value of the field that is in edit mode.
Below is a working snippet
$("table").on("click", "[data-editable]", function(){
var $el = $(this);
if ($el.find("textarea").length)
return;
var str = $el.text();
console.log(str);
var $input = $('<textarea rows=5 style="width:500px"/>').val( str );
$el.html($input);
$input.focus();
var field_name = $el.attr('data-name');
var save = function(bid, newWord, newDialogue, newPractice){
var $td = $input.val();
$input.replaceWith($td);
alert("saving bid: " + bid + ", newWord: " + newWord + ", newDialougue: " + newDialogue + ", newPractice: " + newPractice);
};
$($input).blur(function(){
var row = $(this).closest('tr');
var bid = row.find('td.bid').text();
var newWord = field_name == "word" ? row.find("td.word textarea").val() : row.find('td.word').text();
var newDialogue = field_name == "dialogue" ? row.find("td.dialogue textarea").val() : row.find('td.dialogue').text();
var newPractice = field_name == "practice" ? row.find("td.practice textarea").val() : row.find('td.practice').text();
save(bid, newWord, newDialogue, newPractice)
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="btable" class="bg-light table table-hover">
<th class= "text-center">No</th>
<th class= "text-center">Word</th>
<th class= "text-center">Dialogue</th>
<th class= "text-center">Practice</th>
<tr>
<td class="bid" data-name="bid">100</td>
<td class="word" data-name="word" data-editable>word 1</td>
<td class="dialogue" data-name="dialogue" data-editable>dialogue 1</td>
<td class="practice" data-name="practice" data-editable>practice 1</td>
</tr>
<tr>
<td class="bid" data-name="bid">200</td>
<td class="word" data-name="word" data-editable>word 2</td>
<td class="dialogue" data-name="dialogue" data-editable>dialogue 2</td>
<td class="practice" data-name="practice" data-editable>practice 2</td>
</tr>
</table>
I'm trying to compare an old value in a <td> with the new value entered by the end user. I'm using ng-blur to detect when there is focus out of the field rather than calling the function. The problem is I can't get this very simple logic to work and I can't figure out why.
This is my table:
<main ng-controller="mainCtrl">
<table class="table table-bordered table-hover" ng-controller="tableCtrl">
<p ng-model="old">{{old}}</p>
<thead>
<th>user name</th>
<th>script name</th>
<th>cron format<span class="glyphicon glyphicon-question-sign" data-toggle="tooltip" data-original-title="Min|Hour|Day Of Month|Month|Day Of Week"></span></th>
</thead>
<tbody ng-repeat="(user_id,script_id) in data">
<tr ng-repeat="(script_id, cron_format) in script_id">
<td class="userName">{{user(user_id)}}</td>
<td class="scriptName">{{script(script_id)}}</td>
<td class="cronFormat"><input type="text" ng-model="cron_format" ng-blur="saveCron(user_id,script_id,cron_format)"/></td>
</tr>
</tbody>
</table>
and this is the comparison :
$scope.old = $scope.cron_format = "";
$scope.saveCron(user_id, script_id, cron_format) {
if ($scope.old == $scope.cron_format) {
return; //value was unchanged
}
$.post("updateCronChange.php", "user_id=" + userId + "&script_id=" + scriptId + "&cron_format=" + cronFormat, function (data) {
alert('cron format changed to:' + cronFormat);
});
$scope.old = $scope.cron_format;
});
Currently, the function executes each time the field is out of focus. What am I missing here?
You can use ng-init for each iteration of the ng-repeat to store the old value, and then use it in the function to compare:
<tr ng-repeat="row in data" ng-init="oldCron = row.cron_format">
And in the function call:
ng-click="saveCron(row.user_id,row.script_id,row.cron_format,oldCron)"
And finally inside the function itself:
$scope.saveCron = function(userId,scriptId,cronFormat,oldCron){
console.log("old cron: " + oldCron);
console.log("new cron: " + cronFormat);
if (oldCron != cronFormat) {
//assign
}
}
Fiddle.
If I understand you correctly, you are trying to save an old value and print it out. You can try changing it to this -
if ($scope.old != $scope.cron_format) {
$.post("updateCronChange.php", "user_id=" + userId + "&script_id=" + scriptId + "&cron_format=" + cronFormat, function(data) {
alert('cron format changed to:' + cronFormat);
});
$scope.old = $scope.cron_format;
}
Here is a working example if you like -
var test = angular.module('test', []);
test.controller('TestCtrl', ['$scope',
function($scope) {
$scope.myModel = '';
$scope.old = '';
$scope.getNewValue = 'false'
$scope.saveModel = function(value) {
if ($scope.old != value) {
$scope.getNewValue = 'true';
$scope.old = value;
$scope.myModel = '';
// Here you can do your post request
} else {
$scope.getNewValue = 'false';
}
};
}
]);
.green {
color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js"></script>
<div ng-app='test'>
<div ng-controller="TestCtrl">Enter Some Text
<input type="text" ng-model="myModel" ng-blur="saveModel(myModel)">
<p>Old Value - {{old}}</p>
<p>Current Value - {{myModel}}</p>
<p class="green">Get New Value - {{getNewValue}}</p>
</div>
</div>
I'm binding a dynamic table in angularjs using following script:
$http.get('../Services/ReportServ.asmx/GetSelectedIndex', {
params: {InterviewId: InterviewId, EmpId: EmpId, ClientId: ClientId, Itype: '6'}
}).success(function (data) {
var myjson = JSON.parse(data);
$scope.ReportReviews = JSON.parse(myjson);
});
HTML:
<table id="tableReport" class="reportGrid">
<tr>
<th>
<input type="checkbox" ng-model="ReportReviews.allReviewed" ng-change="selectAllInivited()"/></th>
<th>Name</th>
<th ng-repeat="Header in Headers">{{Header.QUESTIONName}}
</th>
<th>OverAll</th>
</tr>
<tr ng-repeat="ReportReview in ReportReviews" ng-class="{selected: ReportReview.isReviewChecked}">
<td>
<input type="checkbox" ng-model="ReportReview.isReviewChecked" ng-change="selectInivited(ReportReview)"/>
</td>
<td>{{ReportReview.Name}}</td>
<td ng-repeat="Header in Headers">
<%--
<a runat="server" id="a1" ng-show="HideResult(interview)"
ng-class="{'checkedClass': (interview.R=='1' || interview.I=='1') , 'uncheckedClass': interview.I !='1'}">
<img class="imgResult" src="../Lib/img/Result.png" height="55px"/></a>
--%>
<input type="image" id="imgResult{{$index}}" ng-src="{{GetFolderPath(ReportReview,Header)}}" prevent-default
ng-click="imgResultClick(ReportReview,Header)" height="20px"/>
</td>
<td>
<input type="image" class="imgOverall" ng-src="{{GetOverallPath(ReportReview)}}" height="10px"/>
</td>
</tr>
</table>
I have used this script to bind imagebutton src. Now, I want to change the src of specific Image Button on click. I have tried the following method,
$scope.imgResultClick = function (fieldReport, fieldHeader) {
var id = event.target.id;
var imgPath = $('#' + id).attr('src');
$('#' + id).attr('src', ImgPath);
var output = imgPath.substr(0, imgPath.lastIndexOf('.')) || imgPath;
$('#' + id).attr('src', output + '_selected.png');
}
However, it has lot of issues. Example:
Can't reset the image path again on click back.
clicking on the same button agian will append the 'selected.png' string to the image path.
Can anyone guide me? Please let me know, if I need to provide further details.
Basically u should swap DOM-Manipulation into a Directive. In the directive you cna use the link Function to access the specific DOM-Element.But to solve your problem, you have just to use $scope.$apply it "forces" the manipulation
$scope.imgResultClick = function (fieldReport, fieldHeader) {
var id = event.target.id;
var imgPath = $('#' + id).attr('src');
$scope.$apply($('#' + id).attr('src', ImgPath));
var output = imgPath.substr(0, imgPath.lastIndexOf('.')) || imgPath;
$scope.$apply($('#' + id).attr('src', output+'_selected.png'));
}
If u want to toggle the Image, u have to set a flag and get the specific image. A tip u should work with directives' link function. Then u can get all the specific images. And handle them easily. A directive looks like:
app.directive('test', function() {
return {
restrict: 'AE',
link: function(scope, elem, attrs, event) {
elem.bind('click', function() {
//your logic to the image
var id = event.target.id;
var imgPath = $('#' + id).attr('src');
$scope.$apply($('#' + id).attr('src', ImgPath));
var output = imgPath.substr(0, imgPath.lastIndexOf('.')) || imgPath;
$scope.$apply($('#' + id).attr('src', output+'_selected.png'));
});
}}});