I'm trying to sort out this problem but have yet to get results. I tried to get the exact id values of the row which I edit in order to perform an update.
I can get get my current cell value but I can't get the corresponding id values of the cell. I iterate over the table id value which in turn get's all the id values of the table.
I'm using this jquery code for iteration:
$('#table').ready(function() {
$(this).find('.filename').each( function() {
alert($(this).html());
})
})
Then I tried this simple JavaScript:
var fid= document.getElementById("filename").textContent;
It gets only the first id value of the table.
For example, if I edit the first row the id value is 53.
If I edit the second row the id value should be 52 but it gets only 53.
See this link, I have posted this question previously.
getElementById gets the element and not the id. The id is what you are providing as parameter.
You could simply do:
$('#table').ready(function() {
$(this).find('.filename').each( function() {
alert(this.id);
}) ;
});
Instead of cluttering the DOM with id's (which should always be unique) you could always use the data-attributes of elements:
<tr data-identifier="53"><td></td></tr>
$('#table').ready(function() {
$(this).find('.filename').each( function() {
// if this is the row
alert($(this).data('identifier'));
}) ;
});
I am not quite sure that i understand your question but this will give you ids of all cells within a table:
$("#table > td").each(function(){
alert($(this).attr("id"));
});
hi thanks for ur response ,i tried a different script and it was working as i thought
here is the code
function doubleclick(table,id1)
{
table.innerHTML="<input type=text name=tab onBlur=\"javascript:submitNewName(this,'"+id1+ "');\" value=\""+table.innerHTML+"\">";
table.firstChild.focus();
// alert(id1);
}
function submitNewName(text,id2)
{
text.parentNode.innerHTML=text.value;
$.ajax({
url: 'update',
data:{text1:text.value,fileid1:id2},
type:"POST",
dataType:"json",
error:function(data){
//alert('error')
},
success: function(data) {
//alert('updated!')
}
});
}
html:
//when double clicked it will pass both ${item.filedesc},${item.id}
<td ondblclick="javascript:doubleclick(this,${item.id});" >${item.filedesc}</td>
Related
On a project I'm currently working on, I'm using radio buttons and AJAX to change the posts displayed on a custom WordPress template page. It works perfectly, however, the client would like it to be checkboxes instead of radio inputs so that each time a user selected a new category, it adds to the posts being displayed instead of replacing it.
For example: currently, if you click category1, category1 posts show up. Click category2, and category2 posts replace the category1 posts. The client would like BOTH category1 and category2 to show up if both checkboxes are selected.
Here's my JS currently:
jQuery(document).ready(function ($) {
// AJAX Post Filter scripts
var $checkbox = $("#filter input:checkbox");
var $checked = $("#filter input:checkbox:checked");
var $unchecked = $("#filter input:checkbox:not(:checked)");
$checkbox.change(function () {
if ($checked) {
var catID = $(this).val();
$.ajax({
type: 'POST',
url: afp_vars.afp_ajax_url,
data: {
"action": "load-filter",
category__in: catID
},
success: function (response) {
$(".filter-section").empty().html(response);
return false;
console.log('success!');
}
});
console.log(catID);
}
});
});
I'm pretty sure I need to do something with .map() with my variable catID as I've seen in some other threads, but I haven't been able to find a solution that works quite right for me.
edit: I realized I needed to clarify what I have tried.
I've used the following code:
var catID = $(this).map(function () {
return $(this).val();
}).get();
But all it does is replace the variable value with the new checkbox value. I need to add to the value without erasing the already checked values. Then if a checkbox is unchecked, I need to remove the value from the array.
I would try something like this:
let categoryIDs = [];
$('.checkbox').click((e) => {
let id = e.currentTarget.id
$(selector).html('')
categoryIDs.indexOf(id) === - 1 ? (
categoryIDs.push(Number(id))
) : (
categoryIDs = categoryIDs.filter((item) => item !== id )
)
console.log(categoryIDs)
categoryIDs.forEach((item) => {
//ajax calls here
//$.ajax({blah blah}).done(res => {
//$(selector).append(res)
//})
console.log(item);
})
})
See it in action here:
https://jsfiddle.net/mwypd9ve/
This way the IDs you want to display are always in the array, and every time the array changes the page will reflect only the content matching the IDs in the array (because you clear the section .html('') then in the loop append each ajax response
I have a Jquery DataTable with multiselect ability. Moreover there is a button and a div element:
<script>
$(document).ready(function() {
var tablemovChAf = $('#movChAf').DataTable({
//multiselect
$('#movChAf tbody').on('click', 'tr', function () {
$(this).toggleClass('selected');
} );
})
</script>
<button name="sbmsimulate" class="button-input btn btn-info" id="sbmsimulate" style="info" type="button" >
<div id="divAccMovement"></div>
What I want is to send all the selected rows to "accMovement.jsp" by clicking on the button.
$('#sbmsimulate').click( function () {
$('#divAccMovement').load('accMovement.jsp',{
mode:"2",
arrayData:tablemovChAf.rows('.selected').data()
});
} );
my jsp accMovement.jsp looks like this;
<%
String str_mode=request.getParameter("mode").toString();
String[] arrayData=null;
if (str_mode.equals("2")) {
arrayData=request.getParameterValues("arrayData[]");
}
%>
I tried the solution of : Passing javascript array to servlet (In fact, that is what I have done) but it didnt work for me. Nothing happens when I click the button.
I was debugging, and it seems the problem is with:
arrayData:tablemovChAf.rows('.selected').data()
because, if it is commented (and the "if" statement in the jsp is commented also) it is working. However what I need is to send the selected rows to the jsp page.
What is the correct way to send the array from the client and receive the array on the server?
Thanks in advance.
I found a solution not so smart for my case (following this jQuery DataTables Getting selected row values), it does not exactly what I need, but I can add some statements later in order to achive my goal
$('#sbmsimulate').click( function () {
var ids = $.map(tablemovChAf.rows('.selected').data(), function (item) {
return item[11]
});
$('#divAccMovement').load('accMovement.jsp',{
mode:"2",
arrayData:ids
});
} );
The column of index 11 is the id of my dataTable, so in the server side I can get all the information about every row.
However I would like to avoid that step:
var ids = $.map(tablemovChAf.rows('.selected').data(), function (item) {
return item[11]
});
and specify everything in the parameter, something like this :
arrayData:tablemovChAf.rows('.selected').data()
So I have this gridview:
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'symptoms-grid',
'selectableRows'=>1, //ability to select one symptom at a time
'dataProvider'=>$model->search(),
'htmlOptions'=>array('id'=>'symptomsSearchgrid'),
'columns'=>array(
'symptomCode',
'title',
'inclusions',
'exclusions',
'symptomCategory',
),
)); ?>
And this javascript....script:
Yii::app()->clientScript->registerScript('search', "
$( document ).ready(function() {
$('#symptomSelectDiv').hide();
$('#categorySelectDropDown').change(function(){
$('#symptomSelectDiv').show();
$('#symptoms-grid').yiiGridView('update', {
data: $(this).serialize()
});
return false;
});
$('#symptomsSearchgrid table tbody tr').on('click', function() {
var firstColVal = $(this).find('td:first-child').html();
$('#symptomToBeSearched').val(firstColVal);
});
});
");
My problem is that I can only either get the
$('#symptoms-grid').yiiGridView('update', {
data: $(this).serialize()
});
function to work or the:
$('#symptomsSearchgrid table tbody tr').on('click', function() {
var firstColVal = $(this).find('td:first-child').html();
$('#symptomToBeSearched').val(firstColVal);
});
one, and it seems quite random too. Basically in order to get the other function to "start working" I have to change the id (either the grid id or the DOM id) of one function to something different for the other function to work (while the other doesn't).
So let's say at first the update function works and the click function doesn't. Then I change the ID of update to something wrong and click works. Then I change the id of update back to the correct one, but it still doesn't work, yet click works. THen I change click to a wrong id and update starts working correctly. But again, if I change click to the correct id it doesn't work.....
Any ideas what I'm doing wrong?
I think your issue is that your are giving your grid two id's one when creating it and one in htmloption.
On my page I want the user to be able to mouseover a td element, have the page make an Ajax call to the server, and then append a title attribute to the td to serve as a tooltip for the remainder of the time the user is on the page.
The information the page needs to retrieve is very basic so there's nothing too complicated about this... however I cannot get the code to append the data I receive from the Ajax call onto the td element.
Jquery/Ajax
$('.ChannelCodeDesc').mouseover(function () {
//Only append if we don't have a title
if (!$(this).attr('title')) {
//Let me know when we're about to make Ajax call
console.log('ajax');
$.ajax({
type: 'GET',
url: '#Url.Action("GetDesc", "ZipCodeTerritory")',
data: { channel: $.trim($(this).text()) },
success: function (data) {
//Append to td
$(this).attr('title', data);
//Display what we got back
console.log(data);
}
});
}
//What does the title look like when we're done?
console.log($(this).attr('title'));
});
Unfortunately I can see, in the console, the 'ajax' entry, followed by the exact value I'm expecting for the data object, but undefined appears as the value for the td title attribute from the final console.log statement (end of the mouseover).
HTML/Razor
<td class="ChannelCodeDesc">
#Html.DisplayFor(model => model.displayForPaging[i].ChannelCode)
#Html.HiddenFor(model => model.displayForPaging[i].ChannelCode)
</td>
Ajax Controller Method
public JsonResult GetDesc(string channel)
{
var description = (from c in db.Channel
where c.ChannelCode.Equals(channel)
select c.ChannelLongDescription).FirstOrDefault();
return Json(description, JsonRequestBehavior.AllowGet);
}
The problem is that the this object in the success function is not the td element. By default the context of the jquery ajax callbacks is set as an object representing the ajax options. However you can change that using the context option:
$('.ChannelCodeDesc').mouseover(function () {
//Only append if we don't have a title
if (!$(this).attr('title')) {
//Let me know when we're about to make Ajax call
console.log('ajax');
$.ajax({
type: 'GET',
url: '#Url.Action("GetDesc", "ZipCodeTerritory")',
data: { channel: $.trim($(this).text()) },
context: this, //make sure "this" inside the success callback is the td element
success: function (data) {
//Append to td
$(this).attr('title', data);
//Display what we got back
console.log(data);
}
});
}
//What does the title look like when we're done?
console.log($(this).attr('title')); });
I am assuming that the data returned by Ajax is valid....
the $(this) within success does not refer to the td anymore.
do this outside the ajax call:
var me = $(this);
Then in your success code do this:
me.attr('title', data);
The final console.log statement shows undefined because it occurs before the AJAX request is complete (because AJAX requests are Asynchronous).
Also, a td can't have a title attribute, might need to look at a different option:
how to apply style to 'title' attribute of 'td' tag
And others have stated, can't use $this inside the ajax success function like that.
In my html page, I have a select with some options.
When selecting an option, an ajax call is fired passing the option's value to a php script, which returns an html fragment (another select) with a certain id that is appended to the page.
When the user selects another option from the first select, the event is fired again, the ajax call is executed and another html fragment (with the same id) gets appended to the page.
I want that, if the event is fired a second time, the appended element is removed form the page before appending the new one.
At the moment I'm using this code:
$(document).ready(function() {
$("#id_serie").change(function() { //#id_serie is the if of the first select
if ($("#id_subserie_label")) { //#id_subserie_label is the id of the html element returned by the ajax call
console.log("Removing");
$("#id_subserie_label").empty().remove();
}
var url = 'myscript.php';
var id_s = $(this).val();
$.post(url, {id_serie: id_s}, function(data) {
$("#id_serie").parent().after(data);
});
});
});
This is not working though, the html element returned by the second ajax call is appended after the element returned from the first call (because the element with id #id_subserie_label is not in the page when the script is loaded?).
How can I achieve what I need?
You're very close.
Just change if ($("#id_subserie_label")) to if ($("#id_subserie_label").length):
$(document).ready(function() {
$("#id_serie").change(function() {
if ($("#id_subserie_label").length) { // <=== change this line
console.log("Removing");
$("#id_subserie_label").empty().remove();
}
var url = 'myscript.php';
var id_s = $(this).val();
$.post(url, {id_serie: id_s}, function(data) {
$("#id_serie").parent().after(data);
});
});
});
See The jQuery FAQ: How do I test whether an element exists?.
This is because, as Ivo points out:
$("#id_subserie_label") is an object, and objects always evaluate to true.
As per Andy E's comment, you can simplify your code to this, if you don't need the console.log() call:
$(document).ready(function() {
$("#id_serie").change(function() {
$("#id_subserie_label").empty().remove();
var url = 'myscript.php';
var id_s = $(this).val();
$.post(url, {id_serie: id_s}, function(data) {
$("#id_serie").parent().after(data);
});
});
});