I need to select all the check boxes, that are checked and then get the value of id attribute.
I am doing the following way :
$("input:checkbox[class=selectioncheckbox]").each(function() {
console.log("Inside each block");
if($(this).is(":checked")) {
console.log("Inside if block");
pnames[c] = $(this).attr('id');
console.log(pnames[c] + " " + c);
c++;
}
});
But there is a problem. The code never enters the each block. What could be the reason for this?
EDIT:
Here is the code that adds checkboxes with class selectioncheckbox:
$('#teamcheckbox_a').change(function() {
if($(this).is(':checked')) {
$('#teamcheckbox_b').prop('checked',false);
$('#playerselect').empty();
team_a = $('#teamnames_a option:selected').text();
$.ajax( {
url : 'http://localhost:8081/Football/GetPlayerNames',
data : {
teamname : $('#teamnames_a option:selected').text()
},
dataType : 'json',
type : 'GET'
})
.done(function(message) {
$('#playerselect').html("<label>Select Players</label>");
$.each(message,function(index,row) {
$('#playerselect').append(
"<tr>" +
"<td class='text-center'>" + row.jnumber + "</td>" +
"<td>" + row.name + "</td>" +
"<td class='text-center'>" + row.position + "</td>" +
"<td> <input type='checkbox' class='selectioncheckbox form-control input-lg' id='" + row.jnumber + ":" + row.name + "' /> </td>" +
"</tr>");
});
$('.selectioncheckbox').change(function() {
if($(this).is(':checked')) {
count++;
} else {
count--;
}
$('#pcount').html("Count : " + count);
});
})
.fail(function(message) {
console.log(message);
})
}
});
$('#teamcheckbox_b').change(function() {
if($(this).is(':checked') ) {
$('#teamcheckbox_a').prop('checked',false);
$('#playerselect').empty();
team_a = $('#teamnames_b option:selected').text();
$.ajax( {
url : 'http://localhost:8081/Football/GetPlayerNames',
data : {
teamname : $('#teamnames_b option:selected').text()
},
dataType : 'json',
type : 'GET'
})
.done(function(message) {
$('#playerselect').html("<label>Select Players</label>");
$.each(message,function(index,row) {
$('#playerselect').append(
"<tr>" +
"<td class='text-center'>" + row.jnumber + "</td>" +
"<td>" + row.name + "</td>" +
"<td class='text-center'>" + row.position + "</td>" +
"<td> <input type='checkbox' class='selectioncheckbox form-control input-lg' id='" + row.jnumber + ":" + row.name + "' /> </td>" +
"</tr>");
});
$('.selectioncheckbox').change(function() {
if($(this).is(':checked')) {
count++;
} else {
count--;
}
$('#pcount').html("Count : " + count);
});
})
.fail(function(message) {
console.log(message);
})
}
});
Either the code isn't being called at all, or $("input:checkbox[class=selectioncheckbox]") has a length of 0 (which is most likely caused by running the code before the elements have been added to the DOM, in which case you can resolve it with a ready handler).
Use as selector: $(".selectioncheckbox:checked") because i guess selectioncheckbox is only applied to checkboxes and no need to check for checked state inside each loop.
And your issue was none element was matched because using attribute selector [class=selectioncheckbox] if more than one class set on same element, this doesn't match.
The script is calling before the elements added to the DOM. So the script is unable to identify the class name and the length will be 0. Call the script in the ready handler as follows.
$(document).ready(function(){
var c= 0;
var pnames = [];
$("input:checkbox[class=selectioncheckbox]").each(function() {
console.log("Inside each block");
if($(this).is(":checked")) {
console.log("Inside if block");
pnames[c] = $(this).attr('id');
console.log(pnames[c] + " " + c);
c++;
}
});
});
Related
I just created ajax response but i dont know how to give input fields here.. im new bie to Ajax, can you suggest any way please..
$.ajax({
type: "GET",
url: 'get/' + vouchno,
// cache: false,
success: function(data) {
alert(data);
alert(JSON.stringify(data));
$('#vochDate').val(data.strvouchdt);
$('#cashbill').val(data.billtype);
$('#cashref').val(data.refno);
$('#cashAc').val(data.acctname);
$('#refdate').val(data.refdt);
$('#payacc_code').val(data.acctcode);
$('#cashAc').val(data.acctname);
$('#cashAc').val(data.acctname);
for (var i = 0; i < data.cashpayments.length; i++) {
$("#tab_logic ").append('<tr><td>' + '<input type="text">' + data.cashpayments[i].acctcode + '</td>' +
'<td>' + '<input type="text">' + data.cashpayments[i].debit + '</td>' +
'<td>' + '<input type="text">' + data.cashpayments[i].acctcode + '</td>' +
'<td>' + '<input type="text">' + data.cashpayments[i].acctcode + '</td>' +
'<td>' + '<input type="text">' + data.cashpayments[i].acctcode + '</td>' + '</tr>');
}
},
failure: function(data) {
alert(data.responseText);
},
error: function(data) {
alert(data.responseText);
}
});
Completely a guess, you want text-fields in row columns with values prefilled in it:
$("#tab_logic").append(`<tr><td><input type="text" value="${data.cashpayments[i].acctcode}"></td>
<td><input type="text" value="${data.cashpayments[i].debit}"></td>
<td><input type="text" value="${data.cashpayments[i].acctcode}"></td>
<td><input type="text" value="${data.cashpayments[i].acctcode}"></td>
<td><input type="text" value="${data.cashpayments[i].acctcode}"></td></tr>`);
If you are talking about binding the data into input form from the response:
function populate(data) {
for (var i in data) {
if (typeof (data[i]) === 'object') {
//populate(data[i]);
} else {
$(
"input[type='text'][name='" + i + "']," +
" input[type='hidden'][name='" + i + "'], " +
"input[type='checkbox'][name='" + i + "'], " +
"select[name='" + i + "'], textarea[name='" + i + "']"
)
.val(data[i]);
$("input[type='radio'][name='" + i + "'][value='" + data[i] + "']").prop('checked', true);
if ($("input[name='" + i + "']").hasClass('datepicker')) {
$("input[name='" + i + "']").val($.datepicker.formatDate("dd-M-yy", new Date(data[i])));
}
if ($("input[name='" + i + "']").hasClass('financialValueFormat')) {
var formatedAmount = financialValFormat(data[i]);
$("input[name='" + i + "']").val(formatedAmount);
}
}
}
$('form').find('input[type="checkbox"]').each(
function () {
if ($(this).siblings('input[type="hidden"]').val() == "true" ||
$(this).siblings('input[type="hidden"]').val() == 1) {
$(this).prop('checked', true);
} else {
$(this).prop('checked', false);
}
}
);
}
You can define this function some where in your project which is available globally and then just call populate(response.data)
Please ignore the functions financialValFormat. This function is just used to format the value for money fields.
I want to make a switch for declaring variables inside each loop, like this
switch (label) {
case "Users":
content = item.username+ ' ' + item.firstname + ' '
+ item.lastname + '('+ item.organization + ')';
break;
default:
}
$.each(result, function (i, item) {
html += "<option value ='" + item.id + "'>" + content + "</option>";
});
But since item variable hasn't defined yet I will get an ReferenceError.
Moving switch inside loop will make It really slow.
Is this even possible to declare loop variables outside of scope?
function selectorAddEdit(label, tag, result, labelconf) {
var idtag = tag+"s";
var none = "<option value='None'>None</option>";
var labelHead = (labelconf=="head") ? "<div class='selectTitles'><label>"+label+"</label></div>" : "";
switch (label) {
case "Users":
var content = item.username + ' ' + item.firstname + ' ' + item.lastname + '('+ item.organization + ')';
break;
default:
}
var html = labelHead + "<select name='" + tag + "' class='" + tag + "'>";
$.each(result, function (i, item) {
html += "<option value ='" + item.id + "'>" + content + "</option>";
});
html += "</select></div>";
$("." + idtag).html(html);
}
Declare the content as a global variable
var content="";
switch (label) {
case "Users":
content = item.username+ ' ' + item.firstname + ' ' + item.lastname + '('+ item.organization + ')';
break;
default:
}
$.each(result, function (i, item) {
html += "<option value ='"+item.id+"'>"+content+"</option>";
});
This is assuming that item is distinct/unique and therefore you want the switch statement to be re-evaluated at each iteration of loop. What you can do is to use a method/function that returns the value, after evaluating a given condition:
var getOptionContent = function(item) {
switch (label) {
case "Users":
return item.username + ' ' + item.firstname + ' ' + item.lastname + '(' + item.organization + ')';
default:
return '';
}
}
var html = labelHead + "<select name='" + tag + "' class='" + tag + "'>";
$.each(result, function(i, item) {
html += "<option value ='" + item.id + "'>" + getOptionContent(item) + "</option>";
});
I am getting return json data from server,every value is inserted in table except status.
<script>
$(document).ready(function () {
$("#DomainID").change(function () {
var id = $(this).val();
$("#example tbody tr").remove();
$.ajax({
type: 'POST',
url: '#Url.Action("ViewModules")',
dataType: 'json',
data: { id: id },
success: function (data) {
var items = '';
$.each(data.EmpList, function (i, item) {
$("#findValue").show();
/*Find Role here - Comparing Emp List ModuleId to RoleList ModuleId*/
var RoleName = $(data.role).filter(function (index, item) {
return item.ModuleID == item.ModuleID
});
if (item.ParentModuleID == -1) {
item.ModuleName = " -- " + item.ModuleName
}
else {
item.ModuleName = item.ModuleName
}
if (item.Status == "Y") {
item.Status = + '<img src="~/img/Active.png" height="32" width="32"/>'
}
else (item.Status == "N")
{
item.Status = + '<img src="~/img/InActive.png" height="32" width="32"/>'
}
var t = i + 1;
var rows = "<tr>"
+ "<td>" + t + "</td>"
+ "<td>" + item.ModuleName + "</td>"
+ "<td>" + item.Url + "</td>"
+ "<td>" + RoleName[i].RoleName + "</td>"
+ "<td>" + '' + item.Status + "</td>"
+ "</tr>";
$('#example tbody').append(rows);
});
},
error: function (ex) {
var r = jQuery.parseJSON(response.responseText);
alert("Message: " + r.Message);
alert("StackTrace: " + r.StackTrace);
alert("ExceptionType: " + r.ExceptionType);
}
});
return false;
});
});
</script>
}
if item.Status == "N" means InActive image will display and if item.Status == "Y" means Active image will display
But in my code Status Value i didn't get any idea.?
Controller:
public ActionResult ViewModules(int id)
{
Domain_Bind();
dynamic mymodel = new ExpandoObject();
userType type = new userType();
List<ViewRoleModules> EmpList = type.GetRoleModulesViews(id);
List<ViewRoleModules> RoleList;
List<ViewRoleModules> role = new List<ViewRoleModules>();
foreach (ViewRoleModules emp in EmpList)
{
RoleList = type.GetSiteRoleModulesViews(emp.ModuleID);
foreach (ViewRoleModules vip in RoleList)
{
role.Add(new ViewRoleModules
{
RoleName = vip.RoleName,
ModuleID = vip.ModuleID
});
}
}
var data = new { EmpList = EmpList, role = role };
return Json(data, JsonRequestBehavior.AllowGet);
}
Your code is a bit of a mess to be honest with several syntax errors. Hope this helps:
$.ajax({
type: 'POST',
url: '#Url.Action("ViewModules")',
dataType: 'json',
data: { id: id },
success: function (data) {
$.each(data.EmpList, function (i, item) {
$("#findValue").show();
var roleName = $(data.role).filter(function (index, item) {
return item.ModuleID == item.ModuleID
});
var moduleName = item.ModuleName;
if (item.ParentModuleID == -1) {
moduleName = " -- " + moduleName;
}
var status = '';
if (item.Status == "Y") {
status = '<img src="~/img/Active.png" height="32" width="32"/>';
} else {
status = '<img src="~/img/InActive.png" height="32" width="32"/>';
}
var row = "<tr>" +
"<td>" + (i + 1) + "</td>" +
"<td>" + moduleName + "</td>" +
"<td>" + item.Url + "</td>" +
"<td>" + roleName[i].RoleName + "</td>" +
"<td>" + status + "</td>" +
"</tr>";
$('#example tbody').append(row);
});
},
error: function (ex) {
var r = jQuery.parseJSON(response.responseText);
alert("Message: " + r.Message);
alert("StackTrace: " + r.StackTrace);
alert("ExceptionType: " + r.ExceptionType);
}
});
I am trying to append options which are not null only, but i am getting both of the options appended, why?
jQuery:
success: function (data) {
var obj = JSON.parse(data);
$.each(obj, function (booking_price, value) {
if (value.AIRBNB_CONF.length > 0 ) {
$('.searchable').append("<option value=\"" + value.AIRBNB_CONF + "\">" + value.AIRBNB_CONF + "</option>");
}
if (value.DBASE_ID.length > 0 ) {
$('.searchable').append("<option value=\"" + value.DBASE_ID + "\">" + value.DBASE_ID + "</option>");
}
});
},
I am trying to append either value.AIRBNB_CONF or value.DBASE_ID but instead both of them getting appended. it should be like if DBASE_ID 1234 contains AIRBNB_CONF append the AIRBNB_CONF otherwise the DBASE_ID...
You need to use else if in the second case, otherwise it always go through second if
success: function(data) {
var obj = JSON.parse(data);
$.each(obj, function(booking_price, value) {
if (value.AIRBNB_CONF.length > 0) {
$('.searchable').append("<option value=\"" + value.AIRBNB_CONF + "\">" + value.AIRBNB_CONF + "</option>");
}
else if (value.DBASE_ID.length > 0) {
$('.searchable').append("<option value=\"" + value.DBASE_ID + "\">" + value.DBASE_ID + "</option>");
}
});
}
For better understanding of if...else read the documentation of if...else here
I have written the script as follows:
<script type="text/javascript">
$(document).ready(function(){
$("#Click").click(function(){
var data1 = new Object();
data1.name = $('#databases').val();
$.ajax({
url : "form_submit",
type : 'POST',
data : data1,
dataType : "text",
success : function(data){
data = JSON.parse(data);
var output="<table id=tableStyle>";
output+="<tr>" + "<th>" + "REPORTSUITE_ID" + "</th>" + "<th>" + "REPORTSUITE_NAME" + "</th>" + "<th>" + "STAGING_DATABASE" + "</th>" + "<th>" + "DWH_DATABASE" + "</th>" + "</tr>";
for (var i in data)
{
output+="<tr>" + "<td>" + data[i].REPORTSUITE_ID + "</td>" + "<td>" + "<button type = \"buttion\" id =\"tableList\">" + data[i].REPORTSUITE_NAME + "</button>" + "</td>" + "<td>" + data[i].STAGING_DATABASE + "</td>" + "<td>" + data[i].DWH_DATABASE + "</td>" + "</tr>";
}
output += "</table>";
document.getElementById("placeholder").innerHTML=output;
}
});
});
});
$("#tableList").click(function(){
alert("this is data");
});
</script>
On the clicking of button with id = tableList, i want the alert with message "this is data" to be displayed but it does not display anything.
I also tried with pasting the code related to click of button with id tableList between different tags, still it did not work.
Please help
Hi used event delegation for the above question as pointed out as follows:
<script>
$(document).on("ready",function(){
$("#placeholder").on("click","button",function(event){
alert("id is " + this.id + "for database " + $('#databases').val())
})
});
</script>
The value is being passed correctly. Thanks for the pointer.