How can I select multiple checkboxes at once? - javascript

I have a html table which is created dynamically. Im adding check box for each row.
$.each(data, function(id, value) {
rows.push('<tr><td><input type="checkbox" autocomplete="off" class="chkbox" name="chkbox" value="'+value.site+':'+value.client+'"></td><td>' + id + '</td><td>' + value.machine + '</td><td>' + value.state + '</td><td>' + value.date_processed + '</td><td><button type="button" onclick="resetSite(\''+ value.site+'\',\''+value.client+'\')">Reset</td></tr>');
});
I want to select multiple rows at once and need to POST the values to my backend service.
Currently my JavaScript function is like;
$(document).on('change','.chkbox',function () {
var sites = [];
var value = $(this).val();
var res = value.split(":");
$.each($("input[class='chkbox']:checked"), function(){
sites.push(res[0]);
});
alert("sites are: " + sites.join(", "));
$.ajax({
type: "POST",
url: "http://localhost:8080/cache/setProcessing?site="+res[0]+"&client="+res[1],
/*data: {
chkbox: value
},*/
error : function(xhr, textStatus, errorThrown) {
alert("Failed. Error : " + errorThrown);
}
});
});
in the above function my alert box shows same site multiple times if I selecet more than one row.
How can I overcome this?

Change
$(document).on('change','.chkbox',function () {
var sites = [];
var value = $(this).val();
var res = value.split(":");
$.each($("input[class='chkbox']:checked"), function(){
sites.push(res[0]);
});
alert("sites are: " + sites.join(", "));
$.ajax({
type: "POST",
url: "http://localhost:8080/cache/setProcessing?site="+res[0]+"&client="+res[1],
/*data: {
chkbox: value
},*/
error : function(xhr, textStatus, errorThrown) {
alert("Failed. Error : " + errorThrown);
}
});
});
cor·re·spond·ing
$(document).on('change','.chkbox',function () {
var sites = [];
$.each($("input[class='chkbox']:checked"), function(){
var value = $(this).val(); // must me be inside the each
var res = value.split(":"); // must me be inside the each
sites.push(res[0]);
});
alert("sites are: " + sites.join(", "));
$.ajax({
type: "POST",
url: "http://localhost:8080/cache/setProcessing?site="+res[0]+"&client="+res[1],
/*data: {
chkbox: value
},*/
error : function(xhr, textStatus, errorThrown) {
alert("Failed. Error : " + errorThrown);
}
});
});
Because in the previous code it only gets the value of the current checkbox you've clicked.
So you must put the value and res inside the each function to know all checkboxes that have been checked and get there corresponding value..

Related

How can i check User Role in javascript (without razor or controller)

I'm trying to use User.IsInRole() with javascript like on the razor page. I don't want use Controller, if this can be done, How can i do this in MVC5?
Edit: I want to display button by user role. I can do this with the razor page. There are fields in javascript where I add elements to the table, I will try to use them here.
You can do like below as shown below in for price
#{var price=20;}
<html>
<body>
#if (price>30)
{
<p>The price is too high.</p>
}
else
{
<p>The price is OK.</p>
}
</body>
</html>
try like this:
//Check login User has 'System Administrator' role
function CheckUserRole() {
var currentUserRoles = Xrm.Page.context.getUserRoles();
for (var i = 0; i < currentUserRoles.length; i++) {
var userRoleId = currentUserRoles[i];
var userRoleName = GetRoleName(userRoleId);
if (userRoleName == "System Administrator") {
return true;
}
}
return false;
}
//Get Rolename based on RoleId
function GetRoleName(roleId) {
//var serverUrl = Xrm.Page.context.getServerUrl();
var serverUrl = location.protocol + "//" + location.host + "/" + Xrm.Page.context.getOrgUniqueName();
var odataSelect = serverUrl + "/XRMServices/2011/OrganizationData.svc" + "/" + "RoleSet?$filter=RoleId eq guid'" + roleId + "'";
var roleName = null;
$.ajax(
{
type: "GET",
async: false,
contentType: "application/json; charset=utf-8",
datatype: "json",
url: odataSelect,
beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "application/json"); },
success: function (data, textStatus, XmlHttpRequest) {
roleName = data.d.results[0].Name;
},
error: function (XmlHttpRequest, textStatus, errorThrown) { alert('OData Select Failed: ' + textStatus + errorThrown + odataSelect); }
}
);
return roleName;
}
https://msdynamicscrmblog.wordpress.com/2013/03/10/get-login-user-role-names-in-javascript-in-dynamics-crm-2011/

Dropdown's onchange is not triggered when selected value is set server side

I have a drop down list with a client side onchange that I use to populate a jQuery data table. If the value of another drop down is changed and on server side I repopulate the first drop down and set its selected value, its onchange is not triggered and data table not updated with new data.
$(document).on('change', '#ddlFacility', function () {debugger
var facilityID = this.value;
if (facilityID > -1) {
var facCertUrl = "services/easg.asmx/GetSomethingByFacilityID";
var facCertParams = "{ 'FacilityID': '" + facilityID + "', 'Date': '" + $("#hfStartDate").val() + "' }";
populteTable(facCertUrl, facCertParams, tblFacCert);
}
});
function populteTable(ws_url, parameters, table) {
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: ws_url,
cache: false,
data: parameters,
}).done(function (result) {debugger
table.clear().draw();
if (!result || result.d === "") {
$('#divGrid').hide();
}
else {
jResult = JSON.parse(result.d);
table.rows.add(jResult).draw();
table.columns([4, 5, 6, 7, 8, 9, 10, 11]).visible(false);
$('#divGrid').show();
}
}).fail(function (jqXHR, textStatus, errorThrown) {debugger
$('#divGrid').hide();
alert(textStatus + ' - ' + errorThrown + '\n' + jqXHR.responseText);
});
}
var tblFacCert = $("#fcTable").DataTable({
....
});
Server side, when second drop down's value is changed:
protected void ddlDistrict_SelectedIndexChanged(object sender, EventArgs e)
{
string sFacID = somehow_get_FacID();
ListItem li = ddlFacility.Items.FindByValue(sFacID);
if (null != li)
{
li.Selected = true; // This does not trigger onchange
// This changes the selection and runs the onChange() event; but data table is now empty!
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "ddlFacility", "$(\"#ddlFacility\").val(\"" + li.Value + "\").change();", true);
}
}

jQuery AJAX function call

I have a problem with jQuery calling an AJAX function, basically everytime a user changes a select box, I want it to call the getSubCategories function, but for some reason, nothing is happening. Any ideas?
If I load the page and add console.log inside the getSubCategories function it logs it, should that even be happening?
function getSubCategories() {
var id = $("#category").prop('selectedIndex');
var selectedCategory = $("#category").val();
//should change this into a response from AJAX and grab the slug from there, this is fine for now.
var slugOfCategory = convertToSlug(selectedCategory);
id++;
console.log('here');
$.ajax({
method: 'GET', // Type of response and matches what we said in the route
url: '/product/get_subcategories', // This is the url we gave in the route
data: {
'id': id
}, // a JSON object to send back
success: function(response) { // What to do if we succeed
$("#sub_category option").remove(); //Remove all the subcategory options
$.each(response, function() {
$("#sub_category").append('<option value="' + this.body + '">' + this.body + '</option>'); //add the sub categories to the options
});
$("#category_slug").attr('value', slugOfCategory);
},
error: function(jqXHR, textStatus, errorThrown) { // What to do if we fail
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
}
function getCategories() {
var id = $("#type").prop('selectedIndex');
var selectedType = $("#type").val();
//should change this into a response from AJAX and grab the slug from there, this is fine for now.
var slugOfType = convertToSlug(selectedType);
console.log(slugOfType);
//add one to the ID because indexes dont start at 0 as the id on the model
id++;
$.ajax({
method: 'GET', // Type of response and matches what we said in the route
url: '/product/get_categories', // This is the url we gave in the route
data: {
'id': id
}, // a JSON object to send back
success: function(response) { // What to do if we succeed
$("#category option").remove(); //Remove all the subcategory options
$.each(response, function() {
$("#category").append('<option value="' + this.name + '">' + this.name + '</option>'); //add the sub categories to the options
});
$("#type_slug").attr('value', slugOfType);
},
error: function(jqXHR, textStatus, errorThrown) { // What to do if we fail
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
}
function convertToSlug(Text) {
return Text
.toLowerCase()
.replace(/ /g, '_')
.replace(/[^\w-]+/g, '');
}
$(document).ready(function() {
var firstCatgegory = $("#category").val();
var slugOfFirstCategory = convertToSlug(firstCatgegory);
$("#category_slug").attr('value', slugOfFirstCategory);
var firstType = $("#type").val();
var slugOfFirstType = convertToSlug(firstType);
$("#type_slug").attr('value', slugOfFirstType);
$("#type").change(getCategories());
$("#category").change(getSubCategories());
});
Thanks for any help. (Sorry the code is a little messy, i've just been trying to get it to work so far)
This is due to the fact that the ajax call you are trying to make is asynchronous. When you call getSubCategories() it returns undefined which is why your code is not working.
To make this work you need to put your code within the success callback function instead.
<script>
function getSubCategories()
{
var id= $("#category").prop('selectedIndex');
$.ajax({
method: 'GET',
url: '/product/get_subcategories',
data: {'id' : id},
success: function(response){
// DO SOMETHING HERE
},
error: function(jqXHR, textStatus, errorThrown) { }
});
}
$( document ).ready(function() {
// This is also wrong. Currently you're passing
// whatever is returned from getSubCategories
// (which is undefined) as the callback function
// that the "change" event will call. This instead
// should be the reference to the function. Which
// in this case is getSubCategories
$("#category").change(getSubCategories);
});
Please put getCategories() and getSubCategories() Methods inside Change function like this.Sorry for not code formatting.
<script>
$(document).ready(function(){
$("#category").change(function(){
getSubCategories();
});
$("#type").change(function(){
getCategories();
});
});
</script>

How to extract and add the JSON data received as a AJAX response to the HTML select drop down using jQuery?

I've following HTML code :
<select id="student" name="student" class="form-control"></select>
The jQuery-AJAX function I've written for adding the options to the above HTML select control is as follows :
var mod_url = $('#mod_url').val();
$.ajax({
url : mod_url,
cache: false,
dataType: "json",
type: "GET",
async: false,
data: {
'request_type':'ajax',
},
success: function(result, success) {
$('#student').html(result);
},
error: function() {
alert("Error is occured");
}
});
From PHP file I've received a big array encoded into JSON format(i.e. the result variable from jQuery-AJAX function). For your reference I'm showing below only the first four records from that array. In HTML select control actually I want to show all the elements from this array.
[{"id":2,"stud_name":"John Dpalma","stud_address1":"277 Eisenhower Pkwy","stud_address2":"","stud_city":"Edison","stud_state":"New Jersey","stud_country":"USA","stud_zipcode":"07039","stud_email":"abc#gmail.com","created_at":1409739580,"updated_at":1410253832},
{"id":3,"stud_name":"Anthony Gonsalvis","stud_address1":"520 Division St","stud_address2":"","stud_city":"Piscataway","stud_state":"NJ","stud_country":"USA","stud_zipcode":"07201","stud_email":"pqr#gmail.com","created_at":1409740530,"updated_at":1410255590},
{"id":4,"stud_name":"James Bond","stud_address1":"6 Harrison Street, 6th Floor","stud_address2":"Ste-2324","stud_city":"New York","stud_state":"NY","stud_country":"USA","stud_zipcode":"10013","stud_email":"xyz#gmail.com","created_at":1409757637,"updated_at":1412263107},
{"id":9,"stud_name":"Mary Jane","stud_address1":"2112 Zeno Place","stud_address2":"CA","stud_city":"Venice","stud_state":"CA","stud_country":"","stud_zipcode":"90291","stud_email":"utp#gmail.com","created_at":1409908569,"updated_at":1410254282}]
In HTML select control I want to set the values in following manner(consider first two records from above array)
<select id="student" name="student" class="form-control">
<option value="">Select Store</option>
<option value="2">John Dpalma, 277 Eisenhower Pkwy, Edison</option>
<option value="3">Anthony Gonsalvis, 520 Division St, Piscataway</option>
</select>
You might have observed from the expected output above that I want to set the value of option as a id from array and the text that I want to display is comprising of stud_name+stud_address1+stud_city
How should I manage this for all the elements from the JSON data in my code?
Also please guide me in showing the loading option into the select control until the response from PHP comes.
Please provide me some help.
success: function(result, success) {
var $select = $('#student');
$.each(result, function (i, option) {
var txt = [option.stud_name, option.stud_address1, option.stud_city];
if (option.stud_address2)
txt.splice(2, 0, option.stud_address2);
$('<option>', {
value: option.id,
text: txt.join(', ')
}).appendTo($select);
});
},
or with $.map (slightly more efficient):
success: function(result, success) {
var options = $.map(result, function (option) {
var txt = [option.stud_name, option.stud_address1, option.stud_city];
if (option.stud_address2)
txt.splice(2, 0, option.stud_address2);
return $('<option>', {
value: option.id,
text: txt.join(', ')
});
});
$('#student').append(options);
},
In PHP file echo the following in a loop:
echo '<option value="">'.$stud_name.', '.$stud_address1.', '.$stud_address2.', '.$stud_city.', '.$stud_state.', '.$stud_country.'</option>';
Then attach this result to the select dropdown with jQuery through the ajax success.
Here is my solution. This checks address 2 and adds it to the options accordingly.
JS code:
for(var i=0;i<result.length;i++){
if(result[i]["stud_address2"]==""){
$('#student').append('<option value="' + result[i]["id"] + '">' + result[i]["stud_name"] + ', ' + result[i]["stud_address1"]+ ', ' +result[i]["stud_city"] +'</option>');}
else{
$('#student').append('<option value="' + result[i]["id"] + '">' + result[i]["stud_name"] + ', ' + result[i]["stud_address1"]+ ', '+ result[i]["stud_address2"]+ ', ' +result[i]["stud_city"] +'</option>');
}
}
Here is a working DEMO
This is exactly what you need!
$(document).ready(function(){
var mod_url = $('#mod_url').val();
$.ajax({
url : mod_url,
cache: false,
dataType: "json",
type: "GET",
async: false,
data: {
'request_type':'ajax',
},
success: function(result, success) {
$.each(result,function(index,item){
$label = item.stud_name +', ' + item.stud_address1 +', ' + item.stud_city;
$('#student').append('<option value="'+ item.id +'">'+ $label +'</option>');
});
},
error: function() {
alert("Error is occured");
}
});
});
It's a matter of iterating over the JSON you receive from the server, creating option tags for each record, then appending them to the select element:
var response = [{"id":2,"stud_name":"John Dpalma" ... }]
$.each(response, function (index, record) {
if (!record.stud_address2){
var stud_address2 = "";
} else {
var stud_address2 = record.stud_address2;
}
$('<option>', {
value: record.id,
text: record.stud_name + ", " + record.stud_address1 + ", " + record.stud_city + ", " + stud_address2
}).appendTo("#student");
});
Demo
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<script>
function __highlight(s, t) {
var matcher = new RegExp("(" + $.ui.autocomplete.escapeRegex(t) + ")", "ig");
return s.replace(matcher, "<strong>$1</strong>");
}
$(document).ready(
function() {
$("#suggest").autocomplete(
{
source : function(request, response)
{
$.ajax({
url : 'URL',
dataType : 'json',
data : { term : request.term },
success : function(data)
{
//alert(data[0].title);
response($.map(data, function(item) {
//alert(item);
return {
label : __highlight(item.title, request.term),
value : item.title
};
}));
}
});
},
minLength : 3,
select : function(event, ui)
{
if(ui.item){
$(event.target).val(ui.item.value);
}
//submit the form
$(event.target.form).submit();
}
}).keydown(function(e) {
if (e.keyCode === 13)
{
$("#search_form").trigger('submit');
}
}).data("autocomplete")._renderItem = function(ul, item)
{
return $("<li></li>").data("item.autocomplete", item).append(
$("<a></a>").html(item.label)).appendTo(ul);
};
});
</script>

JQuery, HTML5 Uploader - get data response after upload

How can I get data response after uploading image and insert that response into a tag as data-id attribute (after successful post I am getting id of inserted image ). Where in the function is happening this? The function:
function img_upload(url) {
{
var fileTemplate = "<div id=\"{{id}}\">";
fileTemplate += "<div class=\"preview\"></div>";
fileTemplate += "<div class=\"filename\">{{filename}}</div>";
fileTemplate += "Obriši Sliku";
fileTemplate += "</div>";
function slugify(text) {
text = text.replace(/[^-a-zA-Z0-9,&\s]+/ig, '');
text = text.replace(/-/gi, "_");
text = text.replace(/\s/gi, "-");
return text;
}
$("#dropbox").html5Uploader({
postUrl: url,
onClientLoadStart: function (e, file, data) {
var upload = $("#upload");
if (upload.is(":hidden")) {
upload.show();
}
upload.append(fileTemplate.replace(/{{id}}/g, slugify(file.name)).replace(/{{filename}}/g, file.name));
console.log(data);
},
onClientLoad: function (e, file) {
$("#" + slugify(file.name))
.find(".preview")
.append("<img class=img_upload title=\"" + file.name + "\" src=\"" + e.target.result + "\" alt=\"\">")
.on('click', function () {
img_name = $(this).find('.img_upload').attr('title'),
url = '<?php echo base_url() ?>admin/galerija_naslovna_slika/' + img_name.replace(/\s/g, "_") + '/' + id;
$.post(url);
});
var img_delete = $('.image_delete');
delete_image(img_delete);
},
onServerLoad: function (e, file) {
}
});
}
}
I know this is old, But what I do is pass the id in the postURL.
So something like: /image_upload/212/
You need to use apache's mod_rewrite though to get to your php file. And then you can simply look at the request path to get the ID.
Or the other way to do it is pass the ID as a POST var.
You could have a hidden "input" with the id as the value.
docid = $('#docid').val();
$.ajax({
url: '/upload.php',
type: "POST",
data: {'docid': docid},
success: function(data, status, jqXHR) {
set_status('info', 'Success!');
},
error: function(jqXHR, status, err) {
set_status('danger', 'Error: ' + err + ' - ' + status);
},
complete: function(jqXHR, status) {
}
});

Categories

Resources