I am developing MVC application. I am using bootstrp for CSS.
I want to use alert/dialog for confirmation on the delete the record.
It should ask for OK/Cancel and according to the button click next process will be carried out...
I have get the below code form some forum, it works fine but didn't get any event if I clicked on OK or cancel button
How to read these click events from below code ?
$('#Deactivate').click(function () {
var href = $(this).attr('href');
if (!$('#dataConfirmModal').length) {
$('body').append('<div id="dataConfirmModal" class="modal" role="dialog" aria-labelledby="dataConfirmLabel" aria-hidden="true"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button><h6 id="dataConfirmLabel">Deactivation Confirmation</h6></div><div class="modal-body"><h3>Are you sure to deactive #Model.Name ?</h3> </div><div class="modal-footer"><button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button><a class="btn btn-primary" id="dataConfirmOK">OK</a></div></div>');
}
$('#dataConfirmModal').find('.modal-body').text($(this).attr('data-confirm'));
$('#dataConfirmOK').attr('href', href);
$('#dataConfirmModal').modal({show:true});
$('#dataConfirmOK').on('click', function(e)
{
alert('#Model.Id');
var url2 = "#Html.Raw(Url.Action("DeactivateParty", "Party", new { #id = "PoNo"}))";
alert(url2);
url2 = url2.replace("PoNo", '#Model.Id');
$.post(url2, function (data) {
if(data == true)
{
var url = $("#RedirectTo").val();
location.href = url ;
}
});
return false;
});
You have to specify an event handler for your Ok button:
$('#dataConfirmOK').on('click', function(e) {
// Call your delete action here
});
It looks like you have a syntax error closing off the post method:
$.post(url2, function (data) {
if(data == true)
{
var url = $("#RedirectTo").val();
location.href = url;
}
Should be...
$.post(url2, function (data) {
if(data == true)
{
var url = $("#RedirectTo").val();
location.href = url ;
}
})
n.b If you dump your posted code into the console window of your favorite browser, you'll see the error.
Related
I have a working UI Auto complete with jQuery. I wanted to change the way it worked. Instead of a new browser tab opening with the user selects a value from the list I wanted the user to first pick a value then click a search button to trigger the event.
It works but if you perform a search and then a second search it will trigger the previous URL and new URL at the same time. Also if you perform a search then click the search button without typing anything into the search input it triggers the previous search. Weird right? I'll add my code but I think a codepen example will help clarify what I mean.
The other issue I was having is I am trying to set up a custom alert if the value typed is not in the array but I get the invalid error message no matter what I type. I added that as well in the code. It is one of the if statements.
JS
var mySource = [
{
value: "Google",
url: "http://www.google.com"
},
{
value: "Yahoo",
url: "https://www.yahoo.com"
},
{
value: "Hotmail",
url: "https://hotmail.com"
},
{
value: "Reddit",
url: "https://www.reddit.com"
}
];
//Logic for ui-autocomplete
$(document).ready(function() {
$("input.autocomplete").autocomplete({
minLength: 2,
source: function(req, resp) {
var q = req.term;
var myResponse = [];
$.each(mySource, function(key, item) {
if (item.value.toLowerCase().indexOf(q) === 0) {
myResponse.push(item);
}
if (item.value.toUpperCase().indexOf(q) === 0) {
myResponse.push(item);
}
//Add if statement here to determine if what the user inputs is in the
// array
//and if not in the array give an error to #textAlert.
//Example
if (item.value.indexOf(q) != myResponse) {
$('#alertText').text("Invalid Search");
} else {
return false;
}
});
resp(myResponse);
},
select: function(event, ui) {
$('#appSearchBtn').one("click", function() {
window.open(ui.item.url);
$('#appsearch').val('');
return false;
});
}
});
});
//Input and ui text clears when clicked into
$(document).ready(function() {
var input = document.querySelector('#appsearch');
var ui = document.querySelector(".ui-helper-hidden-accessible");
input.onclick = function() {
input.value = '';
ui.textContent = '';
};
});
HTML
<p id="alertText"></p>
<div class="input-group">
<input type="text" id="appsearch" class="form-control autocomplete" placeholder="Application Search" />
<span class="input-group-btn">
<button class="btn btn-primary inputBtn" id="appSearchBtn" type="button">Search</button>
</span>
</div>
Here is a Code pen https://codepen.io/FrontN_Dev/pen/MEmMRz so you can see how it works. I also added how it should work and what the bugs are.
9/29/17 #0732
I resolved the issue with the event firing the same URL over and over but I still need help with the custom invalid search message that appears for every search even if the value is in the array.
I list my status message with knockoutjs Template Binding. My status mesages have like count. I want when ı click my like button refresh my like count where ı clicked it. How can do it. my knockout model code
var viewModel = {
messages: ko.observableArray()
};
ko.options.useOnlyNativeEvents = true;
ko.applyBindings(viewModel);
$.getJSON('#Url.Action("statusMessages", "Home")', function (data) {
viewModel.messages(data);
});
and my like button clik code
var LikeButtonClick = function (id) {
$.getJSON('#Url.Action("Like", "Home")/' + id).done(function (d) {
if (d.State)
toastr.info("Beğendiniz.");
else
toastr.error("Beğenmekten Vazgeçtiniz");
var message = ko.utils.arrayFirst(viewModel.messages(), function (currentMessage) {
return currentMessage.MessageId == d.Id;
});
if (message) {
console.log(message.MessageId)
// refresh
}
})
};
and my button html code
div class="panel-footer-btn-group pull-right" style="margin-left:5px; display:block;">
<button data-bind="click: LikeButtonClick.bind($root,MessageId)" class="btn btn-default like">
<span data-bind="text:LikeCount"></span> <i class="fa fa-thumbs-o-up"></i>
</button>
It seems like you have an observable property called LikeCount somewhere but you haven't included it in the question.
Somewhere you need to do:
var viewModel = {
messages: ko.observableArray(),
LikeCount: ko.observable();
};
and in your json you need to update that observable:
viewModel.LikeCount(data.LikeCount); //or similar
Hi how can ı get my value with knockoutjs click event my button code
<button data-bind="click : LikeButtonClick , value : MessageId" class="btn btn-default like"><span data-bind="text:LikeCount"></span> <i class="fa fa-thumbs-o-up"></i></button>
and my knockoutjs click code
var LikeButtonClick = function () {
alert("");
}
And how can I refresh my likes after like button click event. I use template binding. My template binding code is
var viewModel = {
messages: ko.observableArray()
};
ko.options.useOnlyNativeEvents = true;
ko.applyBindings(viewModel);
$.getJSON('#Url.Action("statusMessages", "Home")', function (data) {
viewModel.messages(data);
});
and my like button code
var LikeButtonClick = function (id) {
$.ajax({
url: '/Home/Like/' + id,
type: 'POST',
success: function (data) {
// refresh
});
}
});
}
Another method is to build the click function into your data model. Here I've added the function to the item directly. Each click will only affect it's own object information.
function Post() {
var self = this;
self.Text = ko.observable("Lorem Ipsum");
self.Liked = ko.observable(false);
self.LikeCount = ko.computed(function() {
return self.Liked() ? 1 : 0;
});
self.MessageId = ko.observable(1);
self.LikeButtonClick = function() {
self.Liked(!self.Liked());
}
}
function viewModel() {
var self = this;
self.Posts = ko.observableArray();
self.Load = function() {
self.Posts.push(new Post());
self.Posts.push(new Post());
self.Posts.push(new Post());
}
self.Load();
}
ko.applyBindings(new viewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<div data-bind="foreach: Posts">
<div data-bind="text:Text"></div>
<button data-bind="click: LikeButtonClick, value: MessageId" class="btn btn-default like">
<span data-bind="text:LikeCount"></span>
<i class="fa fa-thumbs-o-up"></i></button>
</div>
this context passed to the method will be your viewmodel, or whatever you have bound to the element. Inside LikeButtonClick you should be able to get the value of MessageId by referencing the property this.MessageId().
If you want to pass a value to the click handler, you'll want to declare an inline function where you data-bind, or alternatively, bind the function with a context. Here the context is the main viewmodel:
data-bind="click: LikeButtonClick.bind($root,'green')"
var LikeButtonClick = function (src) {
alert(src); // src='green' in this example
}
I have a two submit buttons set up for form submission.
I'd like to know which submit button was clicked without applying a .click() event to each one.
One more thing I am using ASP.NET MVC 3 and want to get the clicked button name in Controller.
Here's the setup:
<a class="anchorbutton">
<input type="submit" value="Save" id="Save" class="hrbutton"/>
</a>
<input type="submit" value="Save & Next" id="SaveNext" class="hrbutton anchorbutton"/>
$('#form').live('submit', function (e)
{
e.preventDefault();
var form = $('#form');
$.ajax({
cache: false,
async: true,
type: "POST",
url: form.attr('action'),
data: form.serialize(),
success: function (data) {
$.ajax({
url: 'url',
dataType: "html",
success: function (data) {
$("#div").html(data);
}
});
}
});
return false;
});
[HttpPost]
public JsonResult Post(FormCollection form, string submitButton)
{
}
well try binding the click event handler to the Save and SaveAndNext buttons like
$(document).delegate("#Save,#SaveAndNext","click",function(e){
console.log($(this).attr("id"));//here you will know which button was pressed
//next you can check if the form is valid or not
if($(this).closest('form').valid()){
//form is valid submit it ajax(ily)
}else{
//form is not valid
}
});
you can also cache the selector
var $this = $(this);
Give your buttons names:
<a class="anchorbutton">
<button type="submit" name="save" id="Save" class="hrbutton">Save</button>
</a>
<button type="submit" name="savenext" id="SaveNext" class="hrbutton anchorbutton">Save & Next</button>
and then your controller action could take those parameters with the same name and check if it has a value:
[HttpPost]
public ActionResult Post(string save, string saveNext, FormCollection form)
{
if (!string.IsNullOrEmpty(save))
{
// The Save button was clicked
}
else if (!string.IsNullOrEmpty(saveNext))
{
// The Save & Next button was clicked
}
else
{
// None of the submit buttons were used or clicked to submit the form.
// The user simply pressed the Enter key while the focus was inside
// some of the input fields of the form
}
...
}
Oh and by the way, the .live jQuery function is deprecated. Use .on instead.
Try
ButtonClick Event " OnClick="MyButton_Click" "
I want to develop an ajax pipeline such that whenever there is any ajax request made through ajax.beginform or ajax.actionLink it should start with my ajax.start function in which i can be able to read the targetupdateid so that i can shoew blockui and any developer should not bother about this ajax.start.I was trying to use this piece of code but itis not working
$(document).ajaxStart(function (xhr, setting) {
console.log(this.activeElement);
if (this.activeElement.type == 'submit') {
activeElement = this.activeElement.form.attributes["data-ajax-update"].value;
} else {
/ activeElement = this.activeElement.attributes["data-ajax-update"].value;
}
if (activeElement != null) {
$(activeElement).blockUI();
}
});
Any help would highly be appreciated.
try this
<div id="mainbody">
</div>
<div id="SomeId" style="display:none">
// put you style to block the UI here
// or put loader image
<img src="#Url.Content("~/Content/themes/base/images/ajax_loader_big.gif")" alt="" />
</div>
#Ajax.BeginForm("Index", "Search", new AjaxOptions { UpdateTargetId = "mainbody", HttpMethod = "Post", LoadingElementId = "SomeId" })
you can use Ajax-Loader or some css style with loader image which will block the UI. you need to paas that div Id in LoadingElementId which block the UI until ajax functionality is not completed.
Thanks for the solution but i want to block the UpdateTargetId which i resolve by adding a listener to the click .
var activeElement,
targetElement,
callbackfunc = function (event) {
activeElement = event.target || event.srcElement;
};
window.addEventListener('click', callbackfunc, true);
$(document).ajaxStart(function () {if (activeElement !== null && activeElement !== undefined) {
if (activeElement.type == 'submit') {
targetElement = activeElement.form.attributes["data-ajax-update"].value;
}
if (activeElement.tagName == 'A') {
targetElement = activeElement.attributes["data-ajax-update"].value;
}
}
if (targetElement !== undefined || targetElement !== null) {
$(targetElement).block({
showOverlay: false,
css: { border: '0px', width: '40px', height: '40px' },
message: '<div class="progress"><div>'
});
}
});