I write this script that user check checkbox info that want to delete and click delete button it delete info with ajax. My problem is that when in first time I delete everything is fine but in second time title of dialog is empty. Why?
I do that with this code after showing dialog because my title is dynamic:
$("#ui-id-1").text(tittle);
<script src="../../Scripts/jquery-1.8.3.js"></script>
<script src="../../Scripts/jquery-ui-1.9.2.custom.js"></script>
<script>
$(function () {
$(":checkbox").change(function () {
var $this = $(this);
if ($this.is(":checked")) {
$this.closest("tr").addClass("SlectedtRow");
} else {
$this.closest("tr").removeClass("SlectedtRow");
}
})
var tittle = '';
var url = '';
$("#dialog").dialog({
autoOpen: false,
width: 400,
modal: true,
resizable: false,
buttons: [
{
text: "بلی",
click: function () {
Delete();
$(this).dialog("close");
}
},
{
text: "خیر",
click: function () {
$(this).dialog("close");
}
}
]
});
var IsActive
// Link to open the dialog
$(".insertBtn").click(function (event) {
var IsSelected = false;
var ModalText = " آیا کاربر ";
$('#userForm input:checked').each(function () {
ModalText += this.value + " - "
IsSelected = true;
});
if (IsSelected) {
document.getElementById('ErrorContent').style.display = "none";
ModalText = ModalText.slice(0, -2);
if (this.id == 'DeleteUser') {
ModalText += " حذف گردد "
tittle = 'حذف کاربر'
url = '#Url.Action("DeleteUser", "UserManagement")';
}
else if (this.id == 'InActiveUser') {
ModalText += " غیر فعال گردد "
tittle = 'تغییر فعالیت کاربر '
url = '#Url.Action("ChangeActiveStatus", "UserManagement")';
IsActive = false;
}
else if (this.id == 'ActiveUser') {
ModalText += " فعال گردد "
tittle = 'تغییر فعالیت کاربر '
url = '#Url.Action("ChangeActiveStatus", "UserManagement")';
IsActive = true;
}
$('#ModalMessgae').text(ModalText);
$("#dialog").dialog("open");
$("#ui-id-1").text(tittle);
event.preventDefault();
} })
function Delete() {
var list = [];
$('#userForm input:checked').each(function () {
list.push(this.id);
});
var parameters = {};
if (url == '#Url.Action("DeleteUser", "UserManagement")') {
parameters = JSON.stringify(list);
}
else {
parameters = JSON.stringify({ "userId": list, "ISActive": IsActive });
}
$.ajax({
url: url,
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: "html",
traditional: true,
data: parameters,
success: function (data, textStatus, jqXHR) {
$('#updateAjax').html(data);
},
error: function (data) {
$('#updateAjax').html(data);
}
}); //end ajax
}
});
</script>
html markup
#using Common.UsersManagement.Entities;
#model IEnumerable<VwUser>
#{
Layout = "~/Views/Shared/Master.cshtml";
}
<form id="userForm">
<div id="updateAjax">
#if (string.IsNullOrWhiteSpace(ViewBag.MessageResult) == false)
{
<div class="#ViewBag.cssClass">
#Html.Label(ViewBag.MessageResult as string)
</div>
<br />
}
<table class="table" cellspacing="0">
#foreach (VwUser Item in Model)
{
<tr class="#(Item.IsActive ? "tRow" : "Disable-tRow")">
<td class="tbody">
<input type="checkbox" id="#Item.Id" name="selected" value="#Item.FullName"/></td>
<td class="tbody">#Item.FullName</td>
<td class="tbody">#Item.Post</td>
<td class="tbody">#Item.Education</td>
</tr>
}
</table>
</div>
<br />
<br />
#if (!Request.IsAjaxRequest())
{
<div class="btnContainer">
delete
<br />
<br />
</div>}
set title like below
Specifies the title of the dialog. If the value is null, the title attribute on the dialog source element will be used.
Code examples:
Initialize the dialog with the title option specified:
$( ".selector" ).dialog({ title: "Dialog Title" });
//Get or set the title option, after initialization:
// getter
var title = $( ".selector" ).dialog( "option", "title" );
// setter
$( ".selector" ).dialog( "option", "title", "Dialog Title" );
see set title in dialog box
Related
Can somebody give me a hint how to pass a list from the controller to Model list in view page after call the Action Result whit ajax in page. (Meaning update current list model with ajax call back result)?
This is my default load view page code:
#model List<ChargeSystem.Models.Message>
#foreach (var item in Model)
{
<div class="container1">
<p>#item.Msg</p>
<span class="time-right">#item.MsgDate</span>
</div>
}
</div>
<div class="divContinMsg">
<input type="text" id="txtMsg" name="txtMsg" />
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#txtMsg").keyup(function (e) {
if (e.keyCode == 13) {
$.ajax(
{
url: '/User/ajaxContactAdmin?msg=' + $("#txtMsg").val(),
type: 'Post',
data: "",
contentType: false,
success: function (result) {
//What can i do????
},
error: function () {
alert("error");
}
})
};
});
});
</script>
This is the Ajax call action result:
public ActionResult ajaxContactAdmin(string msg)
{
var result = new { model = messageRepository.Select().ToList()};
return Json(result, JsonRequestBehavior.AllowGet);
}
So, How can i refresh the model after ajax call back?
So what you would do is append the result to the existing result set.
Firstly I would add a container for easier reference, secondly you would add the item to the container:
#model List<ChargeSystem.Models.Message>
<div id="listContainer">
#foreach (var item in Model)
{
<div class="container1">
<p>#item.Msg</p>
<span class="time-right">#item.MsgDate</span>
</div>
}
</div>
</div>
<div class="divContinMsg">
<input type="text" id="txtMsg" name="txtMsg" />
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#txtMsg").keyup(function (e) {
if (e.keyCode == 13) {
$.ajax(
{
url: '/User/ajaxContactAdmin?msg=' + $("#txtMsg").val(),
type: 'Post',
data: "",
contentType: false,
success: function (result) {
$('#listContainer').append('<div class="container1">'+
'<p>' + result.Msg + '</p>'+
'<span class="time-right">' + result.MsgDate +'</span>'+
'</div>');
},
error: function () {
alert("error");
}
})
};
});
});
</script>
It looks like you want to enter information in your text box and save and update it in the view.
I think you can do this.
Here is an example:
Your Controller:
public IActionResult GetUser ()
{
var messages = context.Messages.ToList();
return View(messages);
}
[HttpPost]
public IActionResult ajaxContactAdmin(string msg)
{
var message = new Message
{
Msg = msg,
MsgDate = DateTime.Now
};
context.Add(message);
context.SaveChanges();
return Json(message);
}
Js in your View:
#section scripts{
<script>
$(document).ready(function () {
$("#txtMsg").keyup(function (e) {
if (e.keyCode == 13) {
var msg = document.getElementById("txtMsg").value
$.ajax(
{
url: '/Home/ajaxContactAdmin?msg=' + $("#txtMsg").val(),
type: 'Post',
data: { "msg": msg},
contentType: false,
success: function (message)
{
console.log(message);
window.location.reload();
},
error: function () {
alert("error");
}
})
};
});
});
</script>
}
Result display:
I am looking to show a modal, I have my Modals as partial classes, so if you select the class .js-verify-songs it loads up the partial _VerifySong . If however there is an error, it should load up the error partial _ErrorMessage. And finally if you select .js-reject-song it should load _RejectSong partial.
Any idea how I would do this, please?
to show errors. Currently I have this in my Controller to handle errors:
public partial class SongsManagementController : BaseController
{
private const string NoDataFound = "No data found.";
private const string InvalidDataPosted = "Invalid data posted";
private const string InvalidRequest = "Invalid request.";
private const string VerificationFailedUnexpectedError = "The following song failed to verify due to an unexpected error, please contact RightsApp support.";
private const string ConcurrencyError = "The following song failed to verify as another user has since changed its details.";
[HttpPost]
[Route("VerifyNewSongs")]
[AuthorizeTenancy(Roles = "super,administrator")]
public async Task<ActionResult> VerifyNewSongs(List<VerifySongViewModel> verifySongViewModels)
{
// Not AJAX method - refuse
if (!Request.IsAjaxRequest())
return RedirectToAction("NewSongs", "SongsManagement");
if (verifySongViewModels.NullOrEmpty())
{
// return error;
return Json(new JsonBaseModel
{
success = false,
message = InvalidRequest,
data = null,
errors = new List<string>
{
InvalidDataPosted
}
});
}
foreach (var verifySong in verifySongViewModels)
{
if (verifySong.WorkId == default(Guid) || verifySong.RowVersion == default(Guid))
{
return Json(new JsonBaseModel
{
success = false,
message = InvalidDataPosted,
data = null,
errors = new List<string>
{
$"Invalid data posted for following song.",
$"Song Title: {verifySong.SongTitle}",
$"Song Id: {verifySong.UniqueCode}"
}
});
}
var work = await _artistAccountService.GetWorkGraphAsync(verifySong.WorkId, includeWriterAmendments: true);
if (work == default(WorkGraphModels.Work))
{
return Json(new JsonBaseModel
{
success = false,
message = NoDataFound,
data = null,
errors = new List<string>
{
$"No data found for following song.",
$"Song Title: {verifySong.SongTitle}",
$"Song Id: {verifySong.UniqueCode}"
}
});
}
if (work.VerifiedState != Domain.Enumerators.VerifiedStateType.NotVerified)
{
return Json(new JsonBaseModel
{
success = false,
message = NoDataFound,
data = null,
errors = new List<string>
{
$"Song already verified.",
$"Song Title: {verifySong.SongTitle}",
$"Song Id: {verifySong.UniqueCode}"
}
});
}
work.RowVersion = verifySong.RowVersion;
var workAndAmendment = new WorkGraphModels.WorkAndAmendment
{
Original = work,
Amendment = null
};
var verifiedState = await _artistAccountService.VerifyWorkGraphAsync(workAndAmendment, GetLoggedUserId());
if (!verifiedState.ValidationErrors.NullOrEmpty())
{
return Json(new JsonBaseModel
{
success = false,
message = NoDataFound,
data = null,
errors = new List<string>
{
VerificationFailedUnexpectedError,
$"Song Title: {verifySong.SongTitle}",
$"Song Id: {verifySong.UniqueCode}"
}
});
}
else if (!verifiedState.DatabaseErrors.NullOrEmpty())
{
if (!verifiedState.FatalException)
{
// concurrency exception
return Json(new JsonBaseModel
{
success = false,
message = NoDataFound,
data = null,
errors = new List<string>
{
ConcurrencyError,
$"Song Title: {verifySong.SongTitle}",
$"Song Id: {verifySong.UniqueCode}"
}
});
}
else
{
// fatal
return Json(new JsonBaseModel
{
success = false,
data = null,
errors = new List<string>
{
VerificationFailedUnexpectedError,
$"Song Title: {verifySong.SongTitle}",
$"Song Id: {verifySong.UniqueCode}"
}
});
}
}
}
return Json(new JsonBaseModel
{
success = true,
message = "All songs verified successfully."
});
}
};
}
This is my Main View:
Layout = Request.IsAjaxRequest() ? null : "~/Views/Shared/_SentricLayout.cshtml";
var actionName = ViewContext.RouteData.Values["Action"].ToString();
#* calc full account code *#
var fullAccountCode = Model.WorkUniqueCode;
ViewBag.Title = "New Songs";
}
#section scripts {
#Scripts.Render("~/bundles/jqueryajaxval")
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/datetimepicker")
<script language="javascript" type="text/javascript">
#* DOM ready? *#
$(function () {
addTableStylingScripts();
var selectFormDiv = $('.catalogSelector');
selectFormDiv.hide();
$(".records-selected").hide();
// clear all filter boxes and reset search.
$("#btnClear").click(function()
{
$("#newSongsSearch").find(':input').each(function ()
{
if (this.type === "text")
{
$(this).val("");
}
});
$("#btnSearch").click();
});
#* edit catalogue button *#
$('#changeCat').click(function () {
$('#errorContainer').hide();
var label = $('#catLabel');
if (label.is(":visible")) {
label.hide();
selectFormDiv.show();
$('#changeCat').addClass("active");
} else {
label.show();
selectFormDiv.hide();
$('#changeCat').removeClass("active");
}
});
#* edit dropdown *#
$("#catalogueSelect").on("change", function () {
#* change display on select change *#
$('#errorContainer').hide();
$('#catLabel').show();
selectFormDiv.hide();
$('#changeCat').removeClass("active");
#* set up ajax post to controller *#
var model = {
AccountCode: '#fullAccountCode',
CurrentAccountId: $('#currentAccountId').val(),
CurrentRowVersion: $('#currentRowVersion').val(),
NewCatalogueId: $('#catalogueSelect option:selected').val(),
Action: '#actionName'
};
$.ajax({
url: '#Url.Action("ChangeCatalogue", "ArtistAccount")',
data: JSON.stringify(model),
type: 'POST',
cache: false,
contentType: 'application/json',
success: function (result) {
#* ajax worked *#
if (result.ChangeStatus === "Success")
{
var newSelected = $('#catalogueSelect option:selected').text();
$('#catLabel').html(newSelected);
#* update dropdown context *#
var newSelectedId = $('#catalogueSelect option:selected').val();
$('#currentCatalogue').val(newSelectedId);
#* update rowversion *#
var newRowVersion = result.OldOrNewRowVersion;
$('#currentRowVersion').val(newRowVersion);
}
else
{
$('#errorContainer').show();
$('#errorMessage').html(result.ErrorMessage);
#* return downdown context *#
var currentCatId = $('#currentCatalogue').val();
$("#catalogueSelect").val(currentCatId);
$('#catalogueSelect').select2({ width: '180px', dropdownAutoWidth: true });
}
},
error: function () {
#* failed *#
$('#errorContainer').show();
$('#errorMessage').html('There was a server error, please contact the support desk on (+44) 0207 099 5991.');
#* return downdown context *#
var currentCatId = $('#currentCatalogue').val();
$("#catalogueSelect").val(currentCatId);
$('#catalogueSelect').select2({ width: '180px', dropdownAutoWidth: true });
}
});
});
function loadPartialPage(url) {
$('.spinnerOverlay').removeClass('hide');
$.ajax({
url: url,
type: 'GET',
cache: false,
success: function (result) {
$('.spinnerOverlay').addClass('hide');
$('#tableContainer').html(result);
addBootstrapTooltips("#tableContainer");
}
});
}
function getSelectedWorks() {
var selectedWorks = $(".individual:checked");
var works = [];
$.each(selectedWorks, function (key, value) {
works.push(getSelectedWork(this));
});
return works;
}
// verify songs in bulk
$(document).on("click", ".js-verify-songs", function (e) {
e.preventDefault();
var works = getSelectedWorks();
verifySongs(works);
});
// reject songs in bulk
$(document).on("click", ".js-reject-songs", function (e) {
e.preventDefault();
var works = getSelectedWorks();
});
function getSelectedWork(element) {
var work = new Object();
work.WorkId = getRowData(element, "id");
work.RowVersion = getRowData(element, "rowversion");
work.UniqueCode = getRowData(element, "uniqueworkid");
work.SongTitle = getRowData(element, "songtitle");
return work;
}
// verify one song
$(document).on("click", ".js-verify-song", function (e) {
e.preventDefault();
var works = [];
works.push(getSelectedWork(this));
verifySongs(works);
});
// reject one song
$(document).on("click", ".js-reject-song", function (e) {
e.preventDefault();
var works = [];
works.push(getSelectedWork(this));
});
function verifySongs(songs) {
$('.spinnerOverlay').removeClass('hide');
$.ajax({
url: '#Url.Action("VerifyNewSongs", "SongsManagement")',
data: JSON.stringify(songs),
type: 'POST',
cache: false,
contentType: 'application/json',
success: function (result) {
$('.spinnerOverlay').addClass('hide');
if (result.success) {
loadPartialPage($(".paginate_button.active a").attr("href"));
}
},
error: function(error) {
$('.spinnerOverlay').addClass('hide');
}
});
}
#* Pagination Async Partial Handling *#
$(document).on("click",
"#indexPager a",
function() {
if ($(this).parent().hasClass('disabled') || $(this).parent().hasClass('active'))
return false;
loadPartialPage($(this).attr("href"));
return false;
});
$(document).on("change",
"#pageSizeSelector",
function() {
var selectedValue = $(this).val();
loadPartialPage(selectedValue);
return false;
});
#* Sorting Async Partial Handling *#
$(document).on("click",
"#tableHeader a",
function()
{
loadPartialPage($(this).attr("href"));
return false;
});
});
// Ensure that after paging and sorting ajax calls we re-bind
// the change event and hide the record count label.
$(document).ajaxComplete(function() {
$(".records-selected").hide();
$(".individual").on("change", determineActionButtonAvailability);
$(".selectall").click(function () {
$(".individual").prop("checked", $(this).prop("checked"));
determineActionButtonAvailability();
});
});
// Search functions
$('.searchDivider').click(function (e) {
$('#searchFields').slideToggle();
var isSearchShown = $(this).find('.caret').hasClass("caret-up");
if (isSearchShown) {
$(this).children('span').replaceWith('<span class="bg-white">Search <b class="caret"></b></span>');
} else {
$(this).children('span')
.replaceWith('<span class="bg-white">Search <b class="caret caret-up"></b></span>');
}
});
$(".searchArea input:text").keypress(function (e) {
if (e.which === 13) {
e.preventDefault();
$("#btnSearch").click();
}
});
$(window).resize(function () {
if ($(window).width() >= 1024) {
$('#searchFields').show();
}
});
$(".searchArea input:text").keypress(function (e) {
if (e.which === 13) {
e.preventDefault();
$("#btnSearch").click();
}
});
// Checks individual checkboxes and displays the count
$(".individual").on("change", determineActionButtonAvailability);
$(".selectall").click(function () {
$(".individual").prop("checked", $(this).prop("checked"));
determineActionButtonAvailability();
});
//Disable Top Verify Button if two or more checkboxes are selected.
$('.verify-btn').prop('disabled', true);
//Disable Action Button in the columns when more than one checkbox is selected
$('.table-btn').prop('disabled', false);
$(".individual").on("click", function () {
if ($(".individual:checked").length > 1) {
$('.table-btn').prop('disabled', true);
$('.verify-btn').prop('disabled', false);
}
else {
$('.table-btn').prop('disabled', false);
$('.verify-btn').prop('disabled', true);
}
});
// When one or more works are selected, will enable the top action menu.
// Will disable when none selected.
function determineActionButtonAvailability() {
if ($(".individual:checked").length > 1) {
$(".records-selected").show();
$("#selected").text($(".individual:checked").length);
$("#total").text($(".individual").length);
$(".verify-btn").prop('disabled', false);
if ($(".individual:checked").length > 1) {
}
}
else {
$(".records-selected").hide();
$('.table-btn').prop('disabled', false);
$(".verify-btn").prop('disabled', true);
}
}
// Enforce only numeric input in the Unique Id search textbox.
$(document).on("keydown", ".uniqueCodefield", function (e) {
var key = window.event ? e.keyCode : e.which;
var currentVal = $('.uniqueCodefield').val();
if (key === 8 || key === 9 || key === 13 || key === 37 || key === 39 || key === 35 || key === 36 || key === 46) {
return true;
} else if (key === 13) {
$('#newSongsSearch').validate();
if ($('#newSongsSearch').valid()) {
return true;
}
return false;
}
else if ((key < 48 || key > 57) && (key < 93 || key > 105)) {
return false;
} else if (currentVal.length >= 10) {
return false;
} else {
return true;
}
});
#* Wire up the Search button click to perform an AJAXified search *#
$(document).on("click", "#btnSearch", function (e) {
e.preventDefault();
// Only perform the search if the search criteria is valid.
if (!$('#newSongsSearch').valid()) {
return false;
}
$('.spinnerOverlay').removeClass('hide');
var model = {
SearchModel: {
WorkUniqueCode: $('#SongCode').val(),
SongTitle: $('#SongTitle').val(),
CatalogueUniqueCode: $('#CatalogueCode').val(),
CatalogueName: $('#CatalogueName').val(),
AccountUniqueCode: $('#AccountCode').val(),
AccountName: $('#AccountName').val()
}
};
$.ajax({
url: '#Url.Action("SearchNewSongs", "SongsManagement")',
data: JSON.stringify(model),
type: 'POST',
cache: false,
contentType: 'application/json',
success: function (result) {
$('#tableContainer').html(result);
addBootstrapTooltips("#tableContainer");
}
});
return false;
});
#* Wire up the Search button click to perform an AJAXified search *#
$(document).on("click", "#btnSearch", function (e) {
e.preventDefault();
$('.spinnerOverlay').removeClass('hide');
var model = {
SearchModel : {
Name: $('#ContractNameSearch').val(),
ContractType: $('#ContractTypeSearch').val(),
CreatedBy: $('#CreatedBySearch').val(),
DateFrom : $('#DateFromSearch').val(),
DateTo : $('#DateToSearch').val()
}
};
$.ajax({
url: '#Url.Action("SearchContracts", "ClientSetup")',
data: JSON.stringify(model),
type: 'POST',
cache: false,
contentType: 'application/json',
success: function (result) {
$('#tableContainer').html(result);
addBootstrapTooltips("#tableContainer");
}
});
return false;
});
</script>
#Scripts.Render("~/bundles/searchusers-autosuggest")
}
#section additionalStyles {
#Styles.Render("~/plugins/datatables/media/css/cssDatatables")
}
<article class="row">
<h1 class="pageTitle artistHeader fw200 mb20 mt10">#ViewBag.Title</h1>
<div class="col-md-12">
<div class="panel panel-visible">
#Html.Partial("_NewSongsSearch", Model)
</div>
</div>
<div class="col-md-12">
<div class="panel panel-visible" id="tableContainer">
#Html.Partial("_NewSongsList", Model)
</div>
</div>
</article>
I am unsure though how I would show a list of error in my error partial view. Also how do you load a partial view with Ajax?
Currently you click verify and it loads the spinner, but I would like to load a partial view which is a modal. I’ve used partials because it’s what was decided. I’m just unsure how to get them to load using Ajax.
I am trying to do this, when a user checks at least one box, the icon must show if not, it hides.
With my code, when i select the #mastercheckbox, the icon does show but when i select the other checkbox displaying on each row, it doesn't show.
Why is this happening?
HTML:
<table id="users-table" class="table table-hover table-condensed" style="width:100%">
<thead>
<tr>
<th><input type="checkbox" id="master"></th>
<th>Category</th>
<th>Description</th>
<th>Number of Items</th>
<th>Action</th>
</tr>
</thead>
</table>
<script type="text/javascript">
$(document).ready(function() {
oTable = $('#users-table').DataTable({
"processing": true,
"serverSide": true,
"bProcessing":false,
"bSort":false,
"ajax": "{{ route('datatable.getcategories') }}",
"columns": [
{data: 'checkbox', name: 'checkbox', orderable: false, searchable: false},
{data: 'name', name: 'name'},
{data: 'action', name: 'action', orderable: false, searchable: false}
],
});
});
</script>
Controller:
$stduents= Student::all();
return Datatables::of($student)->addColumn('checkbox', function ($std) {
return '<input type="checkbox" class="sub_chk" data-id="'.$std->id.'">';
})->make(true);
Where i select my checkbox:
<script type="text/javascript">
$(document).ready(function () {
$("i[type='icon']").css('display','none'); //set style explicitly
$('#master').on('click', function(e) {
if($(this).is(':checked',true))
{
$(".sub_chk").prop('checked', true);
} else {
$(".sub_chk").prop('checked',false);
}
});
$('.delete_all').on('click', function(e) {
var allVals = [];
$(".sub_chk:checked").each(function() {
allVals.push($(this).attr('data-id'));
});
if(allVals.length <=0)
{
alert("Please select row.");
}
else {
var check = confirm("Are you sure you want to delete this row?");
if(check == true){
var join_selected_values = allVals.join(",");
$.ajax({
url: $(this).data('url'),
type: 'GET',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: 'ids='+join_selected_values,
success: function (data) {
if (data['success'])
{
$("#" + data['tr']).slideUp("slow");
location.reload();
alert(data['success']);
}
else if (data['error'])
{
alert(data['error']);
}
else
{
//alert('Whoops Something went wrong!!');
}
},
error: function (data) {
alert(data.responseText);
}
});
$.each(allVals, function( index, value )
{
$('table tr').filter("[data-row-id='" + value + "']").remove();
});
}
}
});
$('[data-toggle=confirmation]').confirmation({
rootSelector: '[data-toggle=confirmation]',
onConfirm: function (event, element) {
element.trigger('confirm');
}
});
$(document).on('confirm', function (e) {
var ele = e.target;
e.preventDefault();
$.ajax({
url: ele.href,
type: 'GET',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
success: function (data) {
if (data['success'])
{
$("#" + data['tr']).slideUp("slow");
location.reload();
alert(data['success']);
}
else if (data['error']) {
alert(data['error']);
}
else
{
alert('Whoops Something went wrong!!');
}
},
error: function (data) {
alert(data.responseText);
}
});
return false;
});
});
</script>
Display icon when at least one checkbox is selected:
<script>
$("input[type='checkbox']").click(function() {
var atLeastOneChecked = false;
$("input[type='checkbox']").each(function(index) {
if ($(this).prop('checked'))
atLeastOneChecked = true;
});
if (atLeastOneChecked) {
$("i[type='icon']").show(); //built-in jquery function
//...or...
$("i[type='icon']").css('display','inline-block'); //or set style explicitly
} else {
$("i[type='icon']").hide(); //built-in jquery function
//...or...
$("i[type='icon']").css('display','none'); //set style explicitly
}
});
</script>
Since your checkboxes are added after the page load $("input[type='checkbox']").click(...) will not add the event handler to them. i.e.
//will handle clicked events on checkbox existing when this js runs
$('input[type="checkbox"]').click(function() {
alert('clicked')
});
//will handle clicked events on dynamically added checkboxes
$(document).on('click', 'input[type="checkbox"]', function() {
alert('clicked2');
});
//add new checkbox to page
$('button').click(function() { $('#master').after($('<input type="checkbox" >')) });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" id="master">
<button type='button'>Add Checkbox</button>
What you want to do instead is $(document).on('click', 'input[type="checkbox"]', function() { ... }
A simple example works for me - whatever is going wrong for you, you'll have to either provide more code or narrow in on the problem with some debugging of your own.
Hope this helps: master and grouped checkboxes all react to click
HTML:
<div id="icon">SEE ME?</div>
<div id="info">Information</div>
<div><input type="checkbox" id="master"></div>
<div><input type="checkbox" name="subset01[]" value="00"></div>
<div><input type="checkbox" name="subset01[]" value="01"></div>
<div><input type="checkbox" name="subset01[]" value="02"></div>
<div><input type="checkbox" name="subset01[]" value="03"></div>
<div><input type="checkbox" name="subset01[]" value="04"></div>
<div><input type="checkbox" name="subset01[]" value="05"></div>
<div><input type="checkbox" name="subset01[]" value="06"></div>
<div><input type="checkbox" name="subset01[]" value="07"></div>
<div><input type="checkbox" name="subset01[]" value="08"></div>
<div><input type="checkbox" name="subset01[]" value="09"></div>
CSS:
#icon{ display: none; }
JS:
$( function(){
$('#info').text("please click a checkbox");
$( "input[type='checkbox']" ).click( function(){
$('#info').html( "you clicked # "+ new Date().getTime() +" currently "+ $(':checked').length +" checked" );
if( $(':checked').length ){
$("#icon").show();
}else{
$("#icon").hide();
}
} );
} );
I want to select a value from combobox jqueryUI but it doesn't work how can I do That???I want To check if txtId HiddenField have value:change
selected value of combobox.I write this way:
if($("#txtId").val())
{
//change selected combobox value with textId value
}
This is my script and html(I remove style for not confusing)
<script>
(function ($) {
$.widget("custom.combobox_with_optgroup", {
_create: function () {
$.extend($.ui.menu.prototype.options, {
items: "> :not(.aureltime-autocomplete-category)"
});
this.wrapper = $("<span>")
.addClass("aureltime-combobox")
.insertAfter(this.element);
this.element.hide();
this._createAutocomplete();
this._createShowAllButton();
},
_createAutocomplete: function () {
var selected = this.element.find(":selected"),
value = selected.val() ? selected.text() : "";
this.input = $("<input>")
.appendTo(this.wrapper)
.val(value)
.attr("title", "")
.addClass("aureltime-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left")
.autocomplete({
delay: 300,
autoFocus: true,
minLength: 0,
source: $.proxy(this, "_source")
})
.tooltip({
tooltipClass: "ui-state-highlight"
});
this._on(this.input, {
autocompleteselect: function (event, ui) {
//event . preventDefault() ;
ui.item.value = ui.item.labelOriginal;
//alert( ui.item.option.value + " " + ui.item.option.labelOriginal );
ui.item.option.selected = true;
this._trigger("select", event, {
item: ui.item.option
});
},
autocompletefocus: function (event, ui) {
ui.item.value = ui.item.labelOriginal;
},
autocompletechange: "_removeIfInvalid"
});
this.input.data("ui-autocomplete")._renderMenu = function (ul, items) {
var self = this,
currentCategory = "";
$.each(items, function (index, item) {
if (item.category != currentCategory) {
if (item.category) {
ul.append("<li class='aureltime-autocomplete-category'>" + item.category + "</li>");
}
currentCategory = item.category;
}
self._renderItemData(ul, item);
});
};
this.input.data("ui-autocomplete")._renderItem = function (ul, item) {
var attr = { class: item.class };
if (item.title) attr.title = item.title;
return $("<li>", attr).html(item.label).appendTo(ul);
};
},
_createShowAllButton: function () {
var input = this.input,
wasOpen = false;
$("<a>", { tabIndex: -1, title: "انتخاب نمایید" })
.tooltip()
.appendTo(this.wrapper)
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass("ui-corner-all")
.addClass("aureltime-combobox-toggle ui-corner-right")
.mousedown(function () {
wasOpen = input.autocomplete("widget").is(":visible");
})
.click(function () {
input.focus();
if (wasOpen) {
return;
}
input.autocomplete("search", "");
});
},
_source: function (request, response) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
response(this.element.find("option").map(function () {
var $this = $(this),
text = $this.text(),
category = $this.closest("optgroup").attr("label") || "",
regexTerm = $.ui.autocomplete.escapeRegex(request.term);
if (this.value && (!request.term || matcher.test(text) || matcher.test(category))) {
var retour =
{
labelOriginal: text,
label: !request.term ? text : text.replace(
new RegExp(
"(?![^&;]+;)(?!<[^<>]*)(" +
regexTerm +
")(?![^<>]*>)(?![^&;]+;)", "gi"
), "<strong>$1</strong>"),
value: this.value,
class: $this.attr("class"),
option: this,
category: category.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + regexTerm + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>")
};
var title = $this.attr("title");
if (title) retour.title = title;
return retour;
}
}));
},
_removeIfInvalid: function (event, ui) {
if (ui.item) {
//alert( ui.item.labelOriginal + " found" );
return;
}
//alert("ear");
var value = this.input.val(),
valueLowerCase = value.toLowerCase(),
//matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex( value ) + "$", "i"),
valid = false;
this.element.find("option").each(function () {
//if ($(this).text().match(matcher)) {
if ($(this).text().toLowerCase() === valueLowerCase) {
this.selected = valid = true;
return false;
}
});
if (valid) {
return;
}
this.input
.val("")
.attr("title", value + " non trouvé")
.tooltip("open");
this.element.val("");
this._delay(function () {
this.input.tooltip("close").attr("title", "");
}, 12500);
this.input.data("ui-autocomplete").term = "";
},
_destroy: function () {
this.wrapper.remove();
this.element.show();
}
});
})(jQuery);
$(function () {
$("#combobox").combobox_with_optgroup();
});
</script>
<script>
$(document).ready(function () {
$.ajax({
type: "POST",
url: "Tkh_Breath.aspx/GetGenders",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#combobox").get(0).options.length = 0;
$("#combobox").get(0).options[$("#combobox").get(0).options.length] = new Option("انتخاب نمایید", "");
$.each(msg.d, function (index, item) {
$("#combobox").get(0).options[$("#combobox").get(0).options.length] = new Option(item.Display, item.Value);
});
},
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
});
</script>
'//////////////////////////////////////HTml
<select id="combobox" name="combobox" plaholder=" " data-type="cape">
</select>
<asp:HiddenField ID="txtId" runat="server" />
just add an onChange listner to the hidden field and update the combobox value on that event.
something like this:
html:
<select id="combobox" name="combobox" plaholder=" " data-type="cape"></select>
<asp:HiddenField ID="txtId" runat="server" />
script:
$(document).ready(function(){
$("#txtId").change(function(){
//update select box value here
})
})
My view I want to check file if it bigger than 500 kb give for example alert()
<img src="#Model.Value" width="95" height="80" id="down-load" data-id="#Model.Key" data upload="#Url.Action("AddPreview", "Images")" />
(function ($) {
$("[data-id]").each(function () {
var $this = $(this);
$($this).upload({
name: 'attachments',
action: $this.data("upload"),
enctype: 'multipart/form-data',
params: {},
autoSubmit: true,
onSubmit: function () { },
onSelect: function () {
var size = $('#down-load')[0].files[0].size;//do not work
},
onComplete: function (e) {
if (e.charAt(0) != '[') {
$.fn.showUserActionNotification(e, true);
return;
}
var data = JSON.parse(e);
if (data[0].Error) {
$.fn.showUserActionNotification(data[0].Error, true);
}
else if (data[0].Preview) {
$this.attr("src", data[0].Preview);
}
}
});
$this.parent().find("input").css("cursor", "pointer");
});
})(jQuery);
I want to get size on function onSelect to check it on big
Is any body can help me?
I have done function
var imageSize = function (e) {
return $.map(e.files, function (file) {
var name = file.name;
var size = file.size;
if (size > 512000) {
var alert = $(".valid-size-goods").text(name + ": " + (size / 1024).toFixed(2) + " kb");
alert.dialog({
title: alert.attr("dlgTitle"),
modal: true,
resizable: false,
buttons: [{ text: alert.attr("btn"), click: function () { $(this).dialog("close"); } }]
}); return false;
}
return true;
});
};
and put it to onSelect:imageSize(e)