I want to create hidden field to put id in it and i have never done that before...
Here is my code:
$.ajax({
url: '/Home/GetCountries',
type: 'GET',
datatype: 'Json',
success: function (data) {
if (data.length > 0) {
var $data = $('<table id="mytable" class="t"> </table>').addClass('table table-responsive table-striped');
var header = "<thead><tr><th>Country ID</th><th>Country</th></tr></thead>";
$.each(data, function (i, row) {
var $row = $('<tr/>');
$row.append($('<td/>').html(row.CountryId))
$row.append($('<td/>').html(row.CountryName));
$hidden = $(' <input type="hidden" name="hid" value=""' + row.CountryId + '">');
$row.append($hidden);
and please tell me how to get id from the hidden field something like this:
$(document).on("click", '.editbtn', function () {
var associateID = $(this).parents("tr").find('td').find(":input").val();
alert(associateID);
});
Thanks in Advance
You can get the value of <input name='hid'> by using the selector $('input[name="hid"]').val(). However, it seems that you have an .editBtn in every row, so you can try using the selector
var associateID = $(this).parents('tr').find('input[name="hid"]').val();
I noticed there's an extra " after the assignment of value, there should only be one, e.g.
$hidden = $(' <input type="hidden" name="hid" value="' + row.CountryId + '">');
Related
I have JSON data from an MVC controller with the values
[{"OperationName":"All","PrivilegeName":"Roles Crud"},{"OperationName":"Read","PrivilegeName":"Roles Read Delete"},{"OperationName":"Delete","PrivilegeName":"Roles Read Delete"},{"OperationName":"Read","PrivilegeName":"Roles Update"},{"OperationName":"Update","PrivilegeName":"Roles Update"}]
I have Displayed this JSON data into an HTML table using AJAX.
$(document).ready(function () {
//debugger;
$.ajax({
url: "/Home/GetOpPriv",
type: "GET",
contentType: "application/json; charset=utf-8",
data: "source={}",
dataType: "json",
success: function (data) {
var row = "";
$.each(data, function (index, item) {
row += "<tr id='trName_" + index + "'>";
row += "<td id='td_OpName" + index + "'>" + item.OperationName + "</td>";
row += "<td id='td_PrivName" + index + "'>" + item.PrivilegeName + "</td>";
row += "<tr>";
});
$("#table1").html(row);
console.log(data);
var source = [];
source.push(data);
console.log(source);
},
error: function (result) {
alert("Error");
}
})
});
I'm Trying to select individual rows from the table when I click the particular row, it should display its value in the alert box
But instead, it's displaying the entire table JSON data onClick.
What correction should I make to this JQuery Function?
$(document).ready(function () {
$("#table1 tr").click(function () {
debugger;
$('.selected').removeClass('selected');
$(this).parents('tr').addClass('selected');
})
});
As I understand your question, you want to display the selected row data, for this scenario, you can try like this
$("#table1 tr").click(function () {
$('.selected').removeClass('selected');
$(this).addClass('selected');
var _index = $(this).attr("id").replace("trName_", "");
var _currentSelectedRow = source[_index];
console.log(_currentSelectedRow);
});
And in ajax success block you are declaring the variable as
var source = [];
source.push(data);
Instead of this declare the 'source' variable as global variable and assign the json data to 'source' in ajax success block.
source = data;
If I understand your question correctly, then the solution is this:
$(document).ready(function () {
$("#table1 tr").click(function () {
$('.selected').removeClass('selected');
$(this).addClass('selected'); // remove .parents('tr')
})
});
By making the change above, this will cause only the row that the user clicks in #table1 (i.e. the row element corresponding to $(this) ) to have the selected class applied.
You are guaranteed to have $(this) inside of your click handler correspond to a table row element, seeing that the click handler is bound to tr elements via the #table tr selector. Hope this helps!
I want to populate a table with PHP script data using jQuery. I am trying as
<script type="text/javascript" src="js/jquery.min.js"> </script>
<script type="text/javascript">
$(document).ready(function(){
$("#button").click(function(){
$.ajax({
url: "http://localhost/test.php",
type:"POST",
async:true,
data:{
"done":1,
"searchDat" : searchDat,
},
success: function(data){
//alert( JSON.parse(data));
var array = JSON.parse(data);
var trHTML = '';
$.each(array, function(ind,value) {
console.log(value);
trHTML += '<tr><td>' + value + '</td><td>' + value+ '</td></tr>';
});
$('#Table').append(trHTML);
}
});
});
});
</script>
HTML
<table id="Table">
<tbody>
<tr><td>ID</td></tr>
<tr><td>ID2</td></tr>
</tbody>
</table>
Button
<form>
<input type="submit" value="Search" id ="button" style="width:50%;border-radius:8px;padding: 15px 4px;"/>
</form>
The problem is that the table is populated for 1 second and then disappears in the webpage. What am I doing wrong?
Edit 1
<script type="text/javascript">
$("form").on('submit', function(e){
e.preventDefault();
$.ajax({
url: "http://localhost/bbcprg/getPrograms.php",
type:"POST",
data: {
"done": 1,
},
success: function(data){
//alert( JSON.parse(data));
var arrayData = JSON.parse(data);
var trHTML = '';
$.each(arrayData, function(ind,value) {
console.log(value);
trHTML += '<tr><td>' + value + '</td><td>' + value+ '</td></tr>';
});
$('#Table').append(trHTML);
}
});
});
</script>
The issue is because you've attached the event to the click of the button. This means that while your AJAX request works, the form is still being submit, and hence the page gets refreshed.
To fix this, hook to the submit event of the form instead, and call preventDefault() on the event passed to the handler. Try this:
$("form").on('submit', function(e){
e.preventDefault();
$.ajax({
url: "http://localhost/test.php",
type:"POST",
data: {
done: 1,
searchDat: searchDat,
},
dataType: 'json',
success: function(data) {
var html = data.map(d => '<tr><td>' + d + '</td><td>' + d + '</td></tr>').join('');
$('#Table tbody').append(html);
}
});
});
Also note that you can simplify the logic which builds the HTML to append by using map() on the data array. You also don't need to manually call JSON.parse() if you specify the correct dataType on the $.ajax request. I've also assumed that searchDat is defined outside the function.
Finally I'd suggest you place an id on the form to make the selector less generic, and also you should move the inline style rules in to an external stylesheet.
change
<input type="submit" value="Search" id ="button" style="width:50%;border-radius:8px;padding: 15px 4px;"/>
to this
<input type="button" value="Search" id ="button" style="width:50%;border-radius:8px;padding: 15px 4px;"/>
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.
Guys I have a function which uses ajax call to retrieve data dynamically based upon a value in div. Now lastNoticeID value in the function is not getting updated as its not in any loop..thus it keeps repeating the same data..
CODE :
function callMoreData() {
var lastNoticeID = $('#hiddenLastNoticeID').val();
$.ajax({
type: "GET",
url: "/api/values/getnotice?num=" + lastNoticeID,
dataType: "json",
crossDomain: true,
async: true,
cache: false,
success: function (data) {
$.each(data, function (index, value) {
BindNotice(value);
});
},
error: function (x, e) {
alert('problem while fetching records!');
}
});
}
function BindNotice(values) {
$('#divNotices').append('...some code...' +
'<input id="hiddenLastNoticeID" type="hidden" value="' + values.LastNoticeID +
'" />' + '...some code...');
}
As you can see in the code above, I am retrieving value from the above div and then passing it to webApi url... Now this is running fine and on the first scroll I get the values but then the function keeps repeating the same values over and over again i.e. var lastNoticeID is not getting updated. How do I get it to update per scroll event?
btw divNotices has the same html code as BindNotice function.
Use classes instead:
function BindNotice(values) {
$('#divNotices').append('...some code...' +
'<input class="hiddenNotice" type="hidden" value="' + values.LastNoticeID +
'" />' + '...some code...');
}
And then:
var lastNoticeID = $('.hiddenNotice').last().val();
Or, you could just store the LastNoticeID in a variable:
var lastNoticeID = 0;
function BindNotice(values) {
$('#divNotices').append('...some code...' +
'<input class="hiddenNotice" type="hidden" value="' + values.LastNoticeID +
'" />' + '...some code...');
lastNoticeID = values.LastNoticeID;
}
It would seem that you are adding more elements of the same ID. ID's are supposed to be single instance and Jquery will therefore only grab the first instance in the DOM. (Which is why $('#hiddenLastNoticeID').val(); is the same every time)
I have the following script which populates a table with data when a dropdown value is selected :
<script>
$(document).ready(function(){
$('#commodity_name').change(function (){
//picks the value of the selected commodity_name from the dropdown
option = $(this).find('option:selected').val();
html='';
htmlhead='';
// alert(option)
$.ajax({
type:"GET",
//gets data from the url specified based on the selected commodity_name in the dropdown
url:"<?php echo base_url();?>user_transactions/return_details/"+option,
dataType:"json",
success:function(data){
for(i=0;i<data.length;i++){
//Loops through the data to give out the data in a table format
//alert(data[i].transaction_type)
html += '<tr>\n\
<td><input type="text" id="commodity_name' + i + '" name="commodity_name[]" value="'+data[i].commodity_name+'"/></td>\n\
<td><input type="text" id="transaction_type' + i + '" name="transaction_type[]" value="'+data[i].transaction_type+'"/></td>\n\
<td><input type="text" id="total_quantity' + i + '" name="total_quantity[]" value="'+data[i].total_quantity+'"/></td>\n\
<td><input type="text" id="remarks' + i + '" name="remarks[]" value="'+data[i].remarks+'"/></td>\n\
<td><input type="text" id="unit_cost' + i + '" name="unit_cost[]" value="'+data[i].unit_cost+'"/></td>\n\
<td></td><td></td></tr> ';
}
htmlhead+='\n\
<th>Commodity Name</th>\n\
<th>Transaction Type</th> \n\
<th>Available Quantity</th> \n\
<th>Available Quantity</th> \n\
<th>Department</th>\n\
<th>Requestor Name</th>\n\
';
//alert(html);
//alert(htmlhead);
$('#thead').append(htmlhead);
$('#you').append(html);
//delegated submit handlers for the forms inside the table
$('#issue_1').on('click', function (e) {
e.preventDefault();
//read the form data ans submit it to someurl
$.post('<?php echo base_url()?>transactions/issues', $('#Issues_Form').serialize(), function () {
//success do something
alert("Success");
var url = "<?php echo base_url()?>transactions/view_request";
$(location).attr('href',url);
}).fail(function () {
//error do something
alert("Failed please try again later or contact the system Administrator");
})
})
},
error:function(data){
}
})
});
});
</script>
How can I clear the data from the html table that has been appended when I select the next commodity_name in the drop down list , I get only the data returned from the new select I have picked from the drop down list.
Just empty the html before appending.
...
$('#thead').empty();
$('#you').empty();
$('#thead').append(htmlhead);
$('#you').append(html);
...
Try to use the .detach() method of Jquery. Here the link: http://api.jquery.com/detach/