I am new to javascript and I jquery and I am trying to take the id of element and the value of the element.
So this is the first ajax request:
$.ajax({
type: "POST",
url: "Home/AddText",
data: JSON.stringify({ text: newText }),
contentType: "application/json",
success: function (result) {
idRow = result.id;
$("#myTable").append("<tr id = row" + idRow + "><td id = text>" +
result.text + "</td><td>" +
"<input type=checkbox id=checkbox onclick=CrossOut(" + idRow + ")>" + " " +
"<a class=btnEdit onclick=Edit(" + idRow + ")>Edit</a>" + " " +
//show this buttons only if the edit button is clicked
"<a class=btnSave onclick=Save(" + idRow + ")>Save</a>" + " " +
"<a class=btnCancel onclick=Cancel(" + idRow + ")>Cancel</a>" + " " +
"<a class=btnDelete onclick=Delete(" + idRow + ")>Delete</a>"
+ "</td> </tr>");
idRow++;
$(document).find('#text').attr('contenteditable', 'true');
$(document).find('.btnSave').hide();
$(document).find('.btnCancel').hide();
}
})
And this is the function:
function Save(idRow) {
var newText = $("#text").val();
console.log(newText);
$.ajax({
type: "POST",
url: "Home/Update",
data: JSON.stringify({ id: idRow, text: newText }),
contentType: "application/json",
success: function (result) {
$("#text").add(newText);
$(document).find('.btnSave').hide();
$(document).find('.btnCancel').hide();
$(document).find('.btnEdit').show();
}
})
}
So when I log the newText variable it doesn't display anything.
Since you are working with td you need to use .text()
var newText = $("#text").text();
Also note that you might have more than one unique id if you keep adding rows and the $(#text) would only get you the first one.
Related
I have two loops:
table loop: fills the table rows
dropdown loop: fills the dropdowns with typeid.data[i].TypeId, add a select in the last dropdown
My dropdown does not fill according to its record and I don't understand why.
var QuestionId = data[i].QuestionOid;
var fkid = data[i].FkSource;
var selectdata = data[i];
var selectinnerhtml = "<span><select id = \"answer" + QuestionId + "\" name = \"answer" + QuestionId + "\" class=\"answer" + QuestionId + " form-control input-small\" > </select></span>";
$.ajax({
type: "GET",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
url: '/MYaPI/EmployeeDetails/' + data[i].TypeId,
success: function(datasa) {
var optionhtmls = '<option value="' +
0 + '">' + "--Select--" + '</option>';
$(".answer" + QuestionId).append(optionhtmls);
$.each(datasa, function(j) {
var optionhtmls = '<option value="' +
datasa[j].Oid + '">' + datasa[j].Title + '</option>';
$(".answer" + QuestionId).append(optionhtmls);
});
}
});
var newRows2select = "<tr class='rows'><a href = '' >" +
" <td QuestionCategoryTitle = " + selectdata.QuestionCategoryTitle + " QuestionHeader = " + selectdata.QuestionHeader + " ContentTypeId=" + selectdata.FkSource + " QuestionTypeId=" + selectdata.FkQuestionType + " QuestionOID=" + selectdata.QuestionOid + " CategoryOID=" + selectdata.FkQuestionCategory + " class=\"question-block\"><small style=\"color:slateblue;font-weight: bolder;display:none\">CATEGORY: " + selectdata.QuestionCategoryTitle + ",</small>" +
" <i class=\"deleteRow fas fa-trash float-right\"></i> " +
"<p> " + selectdata.QuestionHeader + "</p>" + selectinnerhtml + " </td></a> \"</tr>";
$("#table23").append(newRows2select);
I don't know the jQuery way, however it is easily achievable with plain JavaScript
var select = document.createElement("select");
var selectinnerhtml = document.createElement("span");
selectinnerhtml.appendChild(select);
$.each(datasa, function(j) {
//create a new option element
var option = document.createElement("option");
//set the value attribute
option.setAttribute("value", datasa[j].oid);
//fill the HTML tag
option.value = datasa[j].Title
//add the option to the select dropdown
select.add(option);
});
So, I have a button. When I click on it, It'd retrieve ids by ajax method. While the ids are being generated, I'm using another ajax to get some data using the id's as parameter. it's basically an ajax inside an ajax response.
JS:
$("#btn_add").click(function() {
var val_txt = $('#i_minta').find('option:selected').val().replace(/\s{2,}/g, ' ').trim();
var val = val_txt.split("|");
var val_no = val[0];
var val_tgl = val[1];
var val_kc = val[2];
$.ajax({
type: "POST",
url: "<?php echo site_url('con_atk/get_minta'); ?>",
cache: false,
dataType: "json",
data: {
x: val_no /*this is the parameter to get the ID List*/
},
success: function(response) {
var no = 1;
var col_no, col_brg, col_pnh, col_mnt, col_hrg, col_tot, tableData;
$.each(response, function(index, data) {
var txt_harga = [];
var select_txt = "<select id=combo_harga class='form-control'></select>";
$.ajax({
type: "POST",
url: "<?php echo site_url('con_atk/get_harga'); ?>",
cache: false,
dataType: "json",
data: {
y: data.KodeBarang /* this is the ID to get another data */
},
success: function(outputs) {
$.each(outputs, function(i, value) {
//$('#combo_harga').append($('<option></option>').val(index).html(value.harga));
//txt_harga.push('<option value="'+ value.stok +'">'+ value.harga +'</option>');
txt_harga[i] = "<option value='" + value.stok + "'>" + value.harga + "</option>";
});
$('#combo_harga').append(txt_harga.join(''));
}
});
var rowCount = $("#t_output tbody tr").length;
var in_kode = "<input type='hidden' id='i_kb' name='detail[" + rowCount + "][in_kb]' value='" + data.KodeBarang + "' />";
var in_pmnh = "<input type='text' id='i_pnh' name='detail[" + rowCount + "][in_pnh]' onCopy='return false' onDrag='return false' onDrop='return false' onPaste='return false' autocomplete='off' onkeypress='return isNumber(event)' />";
col_no = "<tr><td style='text-align:right; vertical-align:middle'>" + no++ + "</td>";
col_brg = "<td style='text-align:left; vertical-align:middle'>" + data.KodeBarang + " " + in_kode + "<br />" + data.NamaBarang + "</td>";
col_pnh = "<td class='mid'>" + in_pmnh + "</td>";
col_mnt = "<td class='mid'><input type='text' id='o_pmnt' value='" + data.jumlah_minta + "' style='font-weight:bold; width:70%; text-align:right; background-color:#DE5862 !important' readonly /></td>";
col_hrg = "<td style='text-align:right; vertical-align:middle'>" + select_txt + "</td>";
col_tot = "<td style='text-align:right; vertical-align:middle'>xxx</td></tr>";
tableData += col_no + col_brg + col_pnh + col_mnt + col_hrg + col_tot;
$('#t_output tbody tr').remove();
$('#t_output tbody').append(tableData);
});
}
});
});
The end result is a table with each row has a combobox with the value of each id. Like this:
no id somecolumn somecolumn harga somecolumn
1 A xxx xxx value_of_A_1 xxx
2 B xxx xxx value_of_B_1,value_of_B_2 xxx
3 C xxx xxx value_of_C_1,value_of_C_2,value_of_C_3 xxx
the combobox should be inside the harga column.
Thank you for your help :)
Hope It will success you.(it's my old code. don't worry about code format)
var as = $(this).val();
var val = as;
as = as.replace(/\s/g, '');
if (this.checked) {
var a = "_" + as;
var viewName = { viewName: a }
var billingFieldId = '#A' + as + '_BillingCycleId';
var vatFieldid = '#A' + as + '_VatcalculationProcessId';
var serviceType = '#A' + as + '_ServiceType';
$.ajax({
url: '#Url.Action("GetPartialView", "Customers")',
contentType: "application/json;charset=utf-8",
data: JSON.stringify(viewName),
type: 'POST',
dataType: 'html'
}).success(function (result) {
$('#' + as).html(result);
if (billningCycle != null && vatCalculation != null) {
$.ajax({
url: '#Url.Action("GetCommonValue", "Customers")',
contentType: "application/json;charset=utf-8",
data: JSON.stringify(viewName),
type: 'POST',
dataType: 'json',
success: function (data) {
$.each(data.BillingCycles, function (index, value) {
$(billingFieldId).append($('<option />', {
value: value.Id,
text: value.Name
}));
});
$.each(data.Vats, function (index, value) {
$(vatFieldid).append($('<option />', {
value: value.Id,
text: value.Name
}));
});
Under an ajax get method i need to generate table programatically.why actionlink not work with my table
ajax method
$(document).ready(function () {
//click event
$('.delete-logo').on('click', function () {
var id = $(this).data('key');
alert(id);
});
//click event
$('.edit-logo').on('click', function () {
var id = $(this).data('key');
alert(id);
});
$('.submitDetailForm').on('click', function () {
//get value from control
var ProductID = $('#ProductID').val();
var Qty = $('#Qty').val();
var Unit = $('#Unit').val();
var Amount = $('#Amount').val();
var ICMS = $('#ICMS').val();
var IPI = $('#IPI').val();
var ProductName = $('#ProductID option:selected').text();
var booksDiv = $("#booksDiv");
$.ajax({
cache: false,
type: "GET",
url: '#Url.Action("AddToCard", "Sales")',
data: { ProductID: ProductID, ProductName: ProductName, Qty: Qty, Unit: Unit, Amount: Amount, ICMS: ICMS, IPI: IPI },
success: function (data) {
console.log(data);
var result = "";
booksDiv.html('');
$.each(data, function (SalesOrderID, OrderDetails) {
result += '<tr> <td>' + OrderDetails.Name + '</td>' +
'<td>' + OrderDetails.Qty + '</td>' +
'<td>' + OrderDetails.Unit + '</td>' +
'<td>' + OrderDetails.Amount + '</td>' +
'<td>' + OrderDetails.ICMS + '</td>' +
'<td>' + OrderDetails.IPI + '</td>' +
'<td><a class="edit-logo" data-key=' + OrderDetails.SalesOrderDetailID + ' href="javascript:void(0);">' + 'Edit' + '</a></td>' +
'<td><a class="delete-logo" data-key=' + OrderDetails.SalesOrderDetailID + ' href="javascript:void(0);">' + 'Delete' + '</a></td>' +
' </tr>';
});
booksDiv.html(result);
},
error: function (xhr, AJAXOptions, thrownError) {
alert('Failed to retrieve books.');
}
});
});
});
Hyper link content
'<td><a class="edit-logo" data-key=' + OrderDetails.SalesOrderDetailID + ' href="javascript:void(0);">' + 'Edit' + '</a></td>'
'<td><a class="delete-logo" data-key=' + OrderDetails.SalesOrderDetailID + ' href="javascript:void(0);">' + 'Delete' + '</a></td>'
hyperlink display perfectly in browser but can not invoke click events
why my actionlink click event are not fired?
You need to use event delegation (using the .on() function) when adding dynamic content
$('#booksDiv').on('click', '.delete-logo', function() {
....
});
$('#booksDiv').on('click', '.edit-logo', function() {
....
});
where the element with id="booksDiv" is the closest ancestor that exists when the page is first generated.
Side note: Rather than manually generating your javascript object, you can simply use data: $('form').serialize(),
I'm using javascript to dynamically generate a dialogue box (it's a div element), containing a textbox .
THE PROBLEM: I can generate my textbox just fine, but I can't get the value from it. innerHTML comes back blank every time. I'm not sure what I'm doing wrong.
intTextBox = intTextBox + 1;
var contentID = document.getElementById('content');
var newTBDiv = document.createElement('div');
newTBDiv.setAttribute('id', 'strText' + intTextBox);
newTBDiv.innerHTML = String.fromCharCode(64 + (intTextBox + 2)) + ' :'
+ "<input style='margin-top:10px;margin-left:10px;width: 250px;'"
+ " class='txt3_double' type='text' id='"
+ intTextBox + "' name='" + intTextBox
+ "' placeholder='Next Location Point'/>"
+ "<img src='img/Add.png' onclick='addElement();return false;' />"
+ "<img src='img/Minus.png' onclick='removeElement();return false;' />";
contentID.appendChild(newTBDiv);
textboxes = intTextBox;
TextBoxloc = TextBoxloc + 1;
var contentIDloc = document.getElementById('content');
var newTBDivloc = document.createElement('div');
newTBDivloc.setAttribute('id', 'strText' + TextBoxloc);
newTBDivloc.innerHTML = String.fromCharCode(64 + (TextBoxloc + 2))
+ ' :' + "<input class='txt3_double' type='text' id='"
+ TextBoxloc + "' name='" + TextBoxloc + "' />";
contentIDloc.appendChild(newTBDivloc);
textboxesloc = TextBoxloc ;
$(document.getElementById(intTextBox)).autocomplete({
source: function (request, response) {
debugger
$.ajax({
url: '<%=ResolveUrl("~/Root.aspx/GetAutoCompleteData") %>',
data: "{ 'Address': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.d.length == 0) {
$('.ui-autocomplete').hide();
}
else {
$(".pac-container").remove();
response($.map(data.d, function (item) {
debugger
return {
label: item.split('-')[0],
val: item.split('-')[1],
long: item.split('-')[2]
}
}))
}
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
select: function (e, i) {
debugger
document.getElementById(TextBoxloc).value = i.item.val;
},
minLength: 2
});
In your code I can see where you're creating individual textboxes with unique ids coming from intTextBox, so to get at the text in the textboxes just use the value:
var textboxVal = $(intTextBox).value;
Try this
document.getElementById(TextBoxloc).value = i.item.value;
i.item.val should be i.item.value
I see you are adding "strText" in id attribute and trying to set the value using
document.getElementById(TextBoxloc).value = i.item.val;
and are you getting the right value in i.item.val??
good luck...
Code:
function fillChooseCompInAddDeviceDiv(){
$.ajax({
url: "${pageContext.request.contextPath}/StoreServlet",
type: "get",
data: {ajaxId: "2"},
dataType: "json",
success: function(data) {
$("table#choseComponentAddDeviceDiv").find("td").remove();
for(var i = 0; i<data.length; i++) {
$("table#choseComponentAddDeviceDiv").append("<tr>" + "<td>" + data[i].name + "</td>" + "<td>" + data[i].price + "</td>" + "<td>" + data[i].amount + "</td>" + "<td>" + data[i].description + "</td>" + "<td>" + data[i].categoryName + "</td>" + "<td>" + "<a href='" + data[i].link + "'>" + data[i].link + "</a>" + "</td>" + "<td>" + "<img src = '" + data[i].imagePath + "' />" + "</td>" + "<td>" + "<input type='checkbox' class='checkBoxCol' value='" + data[i].name + "'>" + "</td>" + "</tr>");
}
alert("ALERT 1");
},
error: function(status) {
//Do something
}
});
}
//any edit clicked in eny table
function anyEditOnCLick(buttonId, buttonVal){
window.editIsClicked = true;
$("input.nameInput").attr("readonly", true);
if (buttonId === "device"){
$("#addDeviceDiv").css("visibility", "visible");
window.location.hash = "#addDeviceDiv";
fillChooseCompInAddDeviceDiv();
$.ajax({
url: "${pageContext.request.contextPath}/StoreServlet",
type: "get",
data: {ajaxId: "11", toEdit: buttonVal},
dataType: "json",
success: function(data) {
// puni text area
$("#addDeviceFieldName").val(data.name);
$("#addDeviceFieldDescription").val(data.description);
// cekira odgovarajuce komponente, jedan samo data se ocekuje, ne data[]
//fillChooseCompInAddDeviceDiv();
for (var i = 0; i<data.components.length; i++){
$("table#choseComponentAddDeviceDiv td input").filter(function(){return this.value == data.components[i].name}).attr("checked", true);
}
alert("ALERT 2");
},
error: function(status) {
//Do something
}
});
//name is unique - cannot be changed
$("#addDeviceDiv input#addDeviceFieldName").attr("readonly", true);
} else if (buttonId === "component"){
$("#addComponentDiv").css("visibility", "visible");
window.location.hash = "#addComponentDiv";
fillCategorySelection();
$.ajax({
url: "${pageContext.request.contextPath}/StoreServlet",
type: "get",
data: {ajaxId: "21", toEdit: buttonVal},
dataType: "json",
success: function(data) {
$("#addComponentFieldName").val(data.name);
$("#addComponentFieldPrice").val(data.price);
$("#addComponentFieldAmount").val(data.amount);
$("#addComponentFieldDescription").val(data.description);
$("#addComponentFieldLink").val(data.link);
$("#form#uploadForm #imageFile").attr("value", data.imagePath);
//fillCategorySelection();
$("#addComponentDiv select.categorySelect option").filter(function(){return this.value == data.categoryName}).attr("selected", "selected");
},
error: function(status) {
//Do something
}
});
//name is unique - cannot be changed
$("#addComponentDiv input#addComponentFieldName").attr("readonly", true);
} else if (buttonId === "category"){
$("#addCategoryDiv").css("visibility", "visible");
window.location.hash = "#addCategoryDiv";
fillChoseSubCategoriesinAddCategoriesDiv();
$.ajax({
url: "${pageContext.request.contextPath}/StoreServlet",
type: "get",
data: {ajaxId: "31", toEdit: buttonVal},
dataType: "json",
success: function(data) {
$("#addCategoryFieldName").val(data.name);
$("#addCategoryFieldDescription").val(data.description);
//fillChoseSubCategoriesinAddCategoriesDiv();
for (var i = 0; i<data.subCategories.length; i++){
$("table#choseSubCategoriesinAddCategoriesDiv td input").filter(function(){return this.value == data.subCategories[i].name}).attr("checked", true);
}
},
error: function(status) {
//Do something
}
});
//name is unique - cannot be changed
$("#addCategoryDiv input#addCategoryFieldName").attr("readonly", true);
}
}
Function anyEditOnCLick(arg1, arg2) is event function and is placed in onClick tag of a button.
When I click on this button browser always first shows ALERT 2 message and after that go execute fillChooseCompInAddDeviceDiv() and shows ALERT 1. Can someone explain what is really happend here and how can I "persuade" javascript first execute fillChooseCompInAddDeviceDiv()? Before this, i thought function call provides executing whole function body before resuming execution of outer code.