JS JQuery Method to clear inputs works too well - javascript

I made a method for my UI class that clears inputs in a containing div.
The problem is, once it is called, The checkboxes never get set through AJAX calls until you refresh the page. The example below is for my group/user management. If you click on a group to edit, a jQuery UI dialog pops up with the attributes and permissions of that group. If you cancel, and try to add a new one, the inputs are cleared. If you then goto edit a group after that, the inputs are not updated.
Edit: It seems the checkboxes stop working if the cancel button is clicked regardless if my clearInputs method is called or not.
Here is the method of the UI class:
clearInputs: function(container) {
$(container + " :input").val("");
$(container).find('input[type=checkbox]:checked').prop('checked', false);
}
And an example of the calling code (copied from my project, but I cut some of the fat out...
/* The user clicks the edit group button... */
$(document).delegate('.group_edit', 'click', function() {
var groupId = $(this).attr('id').replace("group_edit_", "");
// This call to the clearInputs method is commented out,
// and behaves as I described above.
// ui.clearInputs("#dialogGroup");
$.ajax({
type: "POST",
url: "ajax.users.php",
data: {
action: "get_privs",
group: groupId
},
success: function (result) {
if (result.success == true) {
// Set the name value
$("#name").val(result.GroupName);
// Update each of the checkboxes
$.each(result.privs, function(priv, grant) {
grant = Boolean(parseInt(grant));
$('#dialogGroup input[value=' + priv + ']').prop('checked', grant);
});
/* Create the dialog */
$("#dialogGroup").dialog({
buttons: {
"OK" : function () {
$(this).dialog("close");
var form_data = new Array();
$.each($("input[#name='cbox[]']:checked"), function() {
form_data.push($(this).val());
});
$.ajax({
/* Saves the form data */
});
},
"Cancel": function() {
ui.clearInputs("#dialogGroup");
$(this).dialog("close");
}
}
});
And finally to add a group:
$(document).delegate('#group_add', 'click', function() {
var dialog = "#dialogGroup";
// ui.clearInputs(dialog);
$(dialog).dialog({
modal: true,
title: "Create Group",
buttons: {
"OK": function() {
$(this).dialog("close");
$("#dialogNotify").html("Saving...");
$("#dialogNotify").dialog('open');
var form_data = new Array();
$.each($("input[#name='cbox[]']:checked"), function() {
form_data.push($(this).val());
});
$.ajax({
/* Save the form data */
});
},
Cancel: function() {
$(this).dialog("close");
}
}
});
});
I hope I included everything... If not I will update.

try this:
$( document ).ready(function()
{
var search_on = $('#formX');
$( search_on )
//CHANGE "input" for "input,select" to search all fields
.find('input')
.each(function( e )
{
if( $(this).attr('type') == 'radio' || $(this).attr('type') == 'checkbox' )
{
$(this).attr('checked',false);
//USE RESET() IF IS A FORM FIELD
$(this).reset();
}
//IF IS A DROPDOWN
/*
else if( $(this).attr('type') == undefined )
{
$(this).find('option').attr('selected',false);
}
*/
else
{
$(this).val('');
//USE RESET() IF IS A FORM FIELD
//$(this).reset();
}
});
});
Or use this function( if is a form ):
jQuery.fn.reset = function () {
$(this).each (function() { this.reset(); });
}
And Call
$('#formX').reset();

I figured it out. The problem was inside of my method, I had:
clearInputs: function(container) {
$(container + " :input").val("");
$(container).find('input[type=checkbox]:checked').prop('checked', false);
}
The first line of the method, I guess is doing something to all inputs.
If you change the first line to
$(container + " :input[type=text]").val("");
It works fine...

Related

Jquery on click event is not working when ajax call is running at loop

I have two ajax functions that one is recursively working at loop and other is working when click event invoked. I tested both of the functions that are able to work properly. But when i start recursive function button event is not invoked.
Function that works on click event GET Content from ActionResult (MVC)
function UpdateRequests(url, state, id, cell)
{
$.ajax({
type: "GET",
url: url + id,
success: function (result) {
if (result == "OK")
{
cell.fadeOut("normal", function () {
$(this).html(state);
}).fadeIn();
}
else if(result == "DELETE" || result == "CANCEL")
{
cell.parent().fadeOut("normal", function () {
$(this).remove();
});
}
else
{
$(".modal-body").html(result);
$("#myModal").modal();
}
},
error: function () {
alert("Something went wrong");
}
});
}
Recursive function GET partial view from ActionResult (MVC)
function RefreshRequests()
{
if (isListPage())
{
var id = PageId();
var url = "/Home/List/" + id;
}
else
{
var url = "/Home/Index";
}
$.ajax({
type: "GET",
url: url,
success: function (data) {
$(".ajaxRefresh").html(data);
EditPageHeader();
},
complete: function () {
setTimeout(RefreshRequests, 2000);
}
});
}
Click event
$(".tblRequests").on("click", button, function (e) {
e.preventDefault();
var id = $(this).data("id");
var currentRow = $(this).closest("tr");
var cell = currentRow.children('td.requestState');
UpdateRequests(url, state, id, cell);
});
Main
$(document).ready(function () {
EditPageHeader();
RefreshRequests();
ButtonEvent(".btnPrepare", "/Home/Prepare/", "PREPARING");
ButtonEvent(".btnApprove", "/Home/Approve/", "APPROVED");
ButtonEvent(".btnCancel", "/Home/Cancel/", "CANCELED");
RefreshRequests();
});
Assumptions:
The Ajax Calls bring you data that end up as HTML elements in the modal body.
These new elements added above need to respond to the click event (the one that doesn't work correctly right now)
If the above 2 are true, than what is happening is you are binding events to existing elements (if any) and new elements (coming from API response) are not bound to the click event.
The statement
$(".tblRequests").on("click", button, function (e) {
...
})
needs to be executed every time new elements are added to the body. A better approach for this would be to define the event handler as an individual method and then bind it to each new element.
var clickHandler = function (e) {
e.preventDefault();
var id = $(this).data("id");
var currentRow = $(this).closest("tr");
var cell = currentRow.children('td.requestState');
UpdateRequests(url, state, id, cell);
}
// Then for each new record that you add
$(".tblRequests").on("click", button, clickHandler);
It would be helpful if you can try to explain what exactly you are trying to achieve.
Problem is that the $(this) will hold all elements of the selector. And will also now with one as it will be triggered one time and then never again. Also as can be seen from here, delegate events should be at the closest static element that will contain the dynamic elements.
function ButtonEvent(button, url, state)
{
$("body").on("click", button, function (e) {
e.preventDefault();
var button = e.target;
var id = $(button).data("id");
var currentRow = $(button).closest("tr");
var cell = currentRow.children('td.requestState');
UpdateRequests(url, state, id, cell);
});
}

$post method using in jQuery

I want to create a "add" button in my jQuery calculator. When I click "add" button, it display "+" in the display and the number that I have entered will be stored. After that I can input another number to finish the equation. I can stuck in the part of the add button not sure how to do it. Do I need to use load()?
Try this out. Made a solution with limited inputs you have given
http://jsfiddle.net/sabkaraja/utc7f2ex/
You can decide what you want to do with the added value in #add.click(....) event. I have used a simple eval to get the result in.
$(function () {
var $display = $('#display');
$display.val(0);
$(document).on('click', 'button.number', function () {
if ($display.val().length >= 8) {
$display.val("Error");
} else if ($display.val() == "Error") {
$display.val("0");
} else {
$display.val( $display.val() + '+' + $(this).val());
}
});
$("#clear").click(function () {
$display.val("0");
});
$("#ce").click(function () {
if ($display.val().length >= 2) {
$display.val($display.val().substring(0, $display.val().length - 1));
} else {
$("#ce").trigger("click");
}
});
$("#add").click(function () {
if ($display.val().length !== 0) {
v = eval($display.val()); //<----- here is where I add the numbers
$display.val( v); //------------> do whatever you like to do after this
$.ajax({
url: 'submit.php',
type: 'POST',
dataType :'html',
data: {sum: v},
success: function(data) {
alert(data);
}
});
}
});
});

Inserting a Confirm/Cancel pop-up into JQuery - CSS Issue

I am still quite new to JQuery and I am trying to make a simple pop-up message to confirm a delete, but I want the table row to turn red during this process.
I found this code that seems sweet, short, and simple.
$(document).ready(function(){
$('.confirm').click(function(){
var answer = confirm("Are you sure you want to delete this item?");
if (answer){
return true;
} else {
return false;
}
});
});
from: http://brettgregson.com/programming/how-to-make-a-are-you-sure-pop-up-with-jquery/138
And I am "attempting" to add it onto my current deleteFunction(), but I am still pretty new to JQuery and I am having some "bugs" with it.
My deleteFunction (no confirmation - but color updating works fine)
function deleteFunction(element) {
var newID = $(element).closest("td").find("span.ID").text();
$(element).closest("tr").css('background-color', 'red');
$.post(
'#Url.Action("customDelete", "Movie")',
{
'id': newID
},
function (data) { },
"json"
);
$(element).closest("tr").hide();
}
My insertion of the confirmation box works, but does not update the tr background color, nor does it revert the color back to the default upon cancellation.
function deleteFunction(element) {
var newID = $(element).closest("td").find("span.ID").text();
$(element).closest("tr").css('background-color', 'red');
$(document).ready(function () {
var answer = confirm("Are you sure you want to delete this item?");
if (answer) {
$.post(
'#Url.Action("customDelete", "Movie")',
{
'id': newID
},
function (data) { },
"json"
);
$(element).closest("tr").remove();
return true;
} else {
$(element).closest("tr").css('background-color', 'default');
return false;
}
});
}
If someone could explain why the CSS color is not being touched until after the confirmation box appears (or why it does not remove the color after Cancel is pressed) it would be very much appreciated.
I've created a jsfiddle for you: working sample. As for clearing the color, you should use css('background-color', 'initial'). As for highlighting - it should highlight, as sample does. If it does not help, then feel free to reveal your html markup, most likely the issue is there
You can call your delete function if user wants to delete, like this way
here is your delete function:
function deleteFunction(element) {
var newID = $(element).closest("td").find("span.ID").text();
$(element).closest("tr").css('background-color', 'red');
$.post(
'#Url.Action("customDelete", "Movie")',
{
'id': newID
},
function (data) { },
"json"
);
$(element).closest("tr").hide();
}
and here is cofirm to delete:
$(document).ready(function(){
var ans=confirm("Are you sure you want to delete this item?");
if(ans)
{
deleteFunction(element);
}
else
{
return false;
}
});

focusin event using on not firing

I am attempting to perform some action on the foucsin of the textbox. However, for some reason the event never fires.
$(".ddlAddListinTo li").click(function () {
var urlstring = "../ActionTypes";
$.post(urlstring, function (data) {
$(window.open(urlstring, 'Contacts', 'width=750, height=400')).load(function (e) {
// Here "this" will be the pop up window.
$(this.document).find('#txtAutocompleteContact').on({
'focusin': function (event) {
alert('You are inside the Contact text box of the Contacts Popup');
}
});
});
});
});
When doing it that way, you generally have to find the body or use contents() to access the contents, as in
$(this.document).contents().find('#txtAutocompleteContact')
but in this case using a little plain javascript seems more appropriate :
$(".ddlAddListinTo li").on('click', function () {
var urlstring = "../ActionTypes";
$.post(urlstring, function (data) {
var wind = window.open(urlstring, 'Contacts', 'width=750, height=400');
wind.onload = function() {
var elem = this.document.getElementById('txtAutocompleteContact');
$(elem).on('focus', function() {
alert('You are inside the Contact text box of the Contacts Popup');
});
}
});
});

javascript not displaying login form again

when I click on the log in button the pop up open correctly. But when I close it and again click on the log in button without refreshing the page, it doesn't appear.
my code is:
<script type="text/javascript">
load_login_page = function() {
$.get(HOST_NAME + "e_commerce/ECommerces/ecommerce_login", {}, function(data) {
$("#temp_login_box").html(data);
$.blockUI({
message:$('#temp_login_box'),
css:{
top:($(window).height() - 300) / 2 + 'px',
left:($(window).width() - 800) / 2 + 'px',
width:'620px',
border:'none',
background:'none',
cursor:'default'
},
overlayCSS:{ backgroundColor:'#333' }
});
load_login_ajax_form();
});
};
load_login_ajax_form = function () {
var options = {
beforeSubmit:show_login_request, // pre-submit callback
success:show_login_response // post-submit callback
};
$('#product_info_form').ajaxForm(options);
};
show_login_request = function (formData, jqForm, options) {
return true;
};
show_login_response = function (responseText, statusText, xhr, $form) {
if (responseText == 'ok') {
// $("#temp_login_box").html(responseText);
window.location.href = HOST_NAME + "e_commerce/ECommerces/user_desboard";
//load_login_ajax_form();
} else {
$("#temp_login_box").html(responseText);
load_login_ajax_form();
}
};
hide_login_info = function() {
$.unblockUI();
};
hide_login_info is form closing function. temp_login_box is id to targeted div. please help me out with this code.
Please trace your function load_login_page to check whether $.get called every time.
because you are creating $.blockUI in success of $.get
To check more i need $.unblockUI Code.
But what i suggest is, in unblockUI function either you do empty the div or hide it.
If you hide it then to show on click you have to write $().show(); in $.blockUI function
if it is not the reason
provide $.unblockUI code then might be i can help you.
Note is jquery selector for the div you hide

Categories