How can refactor this below jQuery code.
All the functions does the same job but on different key-presses on the table search box. Which is filtering the table data.
I want re factor this code and write it in single function. Please help me.
jQuery(function($) {
// when the #name field changes
$("body").on("keypup", "#name", function() {
var form = $("#users_form"); // grab the form wrapping the name bar.
var url = form.attr("action");
var formData = form.serialize();
$.get(url, formData, function(data) {
$("#reseller_admin_list").html(data); // replace the "results" div with the result of action taken
});
$("body").on("keypup", "#login", function() {
var form = $("#users_form"); // grab the form wrapping the name bar.
var url = form.attr("action");
var formData = form.serialize();
$.get(url, formData, function(data) {
$("#reseller_admin_list").html(data); // replace the "results" div with the result of action taken
});
$("body").on("keypup", "#account_manager", function() {
var form = $("#users_form"); // grab the form wrapping the name bar.
var url = form.attr("action");
var formData = form.serialize();
$.get(url, formData, function(data) {
$("#reseller_admin_list").html(data); // replace the "results" div with the result of action taken
});
$("body").on("keypup", "#email", function() {
var form = $("#users_form"); // grab the form wrapping the name bar.
var url = form.attr("action");
var formData = form.serialize();
$.get(url, formData, function(data) {
$("#reseller_admin_list").html(data); // replace the "results" div with the result of action taken
});
});
});
function update() {
var form = $("#users_form"); // grab the form wrapping the name bar.
var url = form.attr("action");
var formData = form.serialize();
$.get(url, formData, function(data) {
$("#reseller_admin_list").html(data); // replace the "results" div with the result of action taken
});
}
$("body").on("keyup", "#account_manager, #login, #email", update);
The explanation:
1.) We extract the duplicate code in a single function called update. We follow the DRY principle here
2.) JQuery allows us to use multiple selectors, so we can bind the update function to all elements at once:
$("body").on("keyup", "#account_manager, #login, #email", update);
instead of calling:
$("body").on("keyup", "#account_manager", update);
$("body").on("keyup", "#login", update);
$("body").on("keyup", "#email", update);
how about just having one code block:
$("body").on("keypup", "#name, #login, #account_manager, #email", function() {
var form = $("#users_form");
var url = form.attr("action");
var formData = form.serialize();
$.get(url, formData, function(data) {
$("#reseller_admin_list").html(data);
});
});
Much better though, would be to give you elements a class, and bind to the class rather then each id, i.e.
$("body").on("keypup", ".someClass", function() { //etc
write a new function.
$("body").on("keypup", "#login", function() {
functionName();
});
and in function
function functionName(){
var form = $("#users_form"); // grab the form wrapping the name bar.
var url = form.attr("action");
var formData = form.serialize();
$.get(url, formData, function(data) {
$("#reseller_admin_list").html(data); // replace the "results" div with the result of action taken
});`
}
Related
Sorry I am a beginner with jQuery and Javascript. I want to be able to get the results into my modal from any form on the page that has class ajax. My code is below but not working correctly. Currently it opens the post result in a new page and not in the modal. Can anyone shed any light on my code?
Many thanks
$(document).ready(function() {
$('.ajax').click(function() {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('name').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
console.log(value);
// AJAX request
$.ajax({
url: url,
type: type,
data: data,
success: function(response){
// Add response in Modal body
$('.modal-body').html(response);
// Display Modal
$('#aaModal').modal('show');
}
});
});
});
This probably happens because your browser submits the form by default. It doesnt know youre doing AJAX stuff. To prevent this, use preventDefault().
In addition to that, jQuery has a built in function for serializing (1 and 2) form data.
$(document).ready(function() {
$('form.ajax').click(function(event) {
event.preventDefault(); // prevents opening the form action url
var $form = $(this),
url = $form.attr('action'),
type = $form.attr('method'),
data = $form.serialize();
// console.log(value); // value doesnt exist outside of your loop btw
// AJAX request
$.ajax({
url: url,
type: type,
data: data,
success: function(response){
// Add response in Modal body
$('.modal-body').html(response);
// Display Modal
$('#aaModal').modal('show');
}
});
});
});
Also, its not quite clear if you bind the click event handler to a form or a button, I guess the first one. You should change the handler to the following:
$(document).ready(function() {
$('form.ajax').on('submit', function(event) {
I have this div
<div class='additional_comments'>
<input type="text" id='additional_comments_box', maxlength="200"/>
</div>
Which will only sometimes appear on the page if jinja renders it with an if statement.
This is the javascript i have to send an ajax request:
$(document).ready(function() {
var button = $("#send");
$(button).click(function() {
var vals = [];
$("#answers :input").each(function(index) {
vals.push($(this).val());
});
vals = JSON.stringify(vals);
console.log(vals);
var comment = $('#additional_comments_box').val();
var url = window.location.pathname;
$.ajax({
method: "POST",
url: url,
data: {
'vals': vals,
'comment': comment,
},
dataType: 'json',
success: function (data) {
location.href = data.url;//<--Redirect on success
}
});
});
});
As you can see i get the comments div, and I want to add it to data in my ajax request, however if it doesnt exist, how do I stop it being added.
Thanks
You can use .length property to check elements exists based on it populate the object.
//Define object
var data = {};
//Populate vals
data.vals = $("#answers :input").each(function (index) {
return $(this).val();
});
//Check element exists
var cbox = $('#additional_comments_box');
if (cbox.length){
//Define comment
data.comment = cbox.val();
}
$.ajax({
data: JSON.stringify(data)
});
I've set up a page with a bunch of contenteditbale divs, along with some js/ajax functionality so that a user can inline edit.
<div class="inlineEdit" contenteditable="true"></div>
JS is a s such:
$(document).ready(function(){
$('div.inline-edit').blur(function()
{
var pathArray = window.location.pathname.split( '/' );
var segment_3 = pathArray[3];
var editableObj = $(this);
var token_input = $('input.token');
var save_data ={};
var token_name = token_input.attr('name');
save_data['field'] = editableObj.attr('id');
save_data['id'] = editableObj.closest('.inline-id').attr('id');
save_data['editedValue'] = editableObj.text();
$.ajax({
url: segment_3+'/update',
type: 'POST',
data:save_data,
success: function(){
//on success functionality
}
});
});
});
This part all works perfectly grand, all the right fields get updated with the right info. All i need is some way to validate that information before it get to the ajax
I know of JQuery Validation however I'm pretty sure it doesn't work with divs.
Is there a solution or am I stuck/have to change up the divs?
You can create a temporary input box and pass the value through it to check validity. I wrote a function to use HTML5 validation to check for validity.
function validityChecker(value, type) {
type = type?type:'text'
$('body').append('<input id="checkValidity" type="'+type+'" style="display:none;">');
$('#checkValidity').val(value)
validity = $('#checkValidity').val()?$('#checkValidity').val().length>0:false && $('#checkValidity')[0].checkValidity()
$('#checkValidity').remove();
return validity;
}
In your case use like this:
if(validityChecker(save_data['editedValue'], 'number')){ // if you want to check for number
$.ajax({
url: segment_3+'/update',
type: 'POST',
data:save_data,
success: function(){
//on success functionality
}
})
}
Demo:
function validityChecker(value, type) {
type = type?type:'text'
$('body').append('<input id="checkValidity" type="'+type+'" style="display:none;">');
$('#checkValidity').val(value)
validity = $('#checkValidity').val()?$('#checkValidity').val().length>0:false && $('#checkValidity')[0].checkValidity()
$('#checkValidity').remove();
return validity;
}
save_data = 'This is not a number';
alert(validityChecker(save_data, 'number')) // false
alert(validityChecker(save_data, 'text')) // true
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I want to fetch data from div tag which set contenteditable=true
I have used autosuggestion in that..Data is successfully fetched but when I write item which is written in autosuggestion field then it wont be fetched because it add HTML tag and it wont save into database
My code
if data is changed:
var timeoutID;
$('[contenteditable]').bind('DOMCharacterDataModified', function () {
clearTimeout(timeoutID);
$that = $(this);
timeoutID = setTimeout(function () {
$that.trigger('change')
}, 50)
});
$('[contentEditable]').bind('change', function () {
getTextChangeContent();
});
UPDATE
function getTextChangeContent() {
var ma = document.getElementById('myAudio');
var remove = ma.src.slice(0, -4);
var path = remove.substring(remove.lastIndexOf("/") + 1);
var newPath = path.concat('.wav');
var text_id = document.getElementById('textbox');
var textdata = text_id.innerHTML;
$.ajax(
{
type: "POST",
url: '#Url.Action("getChangeContent")',
dataType: "json",
mtype: "post",
data: { arg: varid, content: textdata, path: newPath },
async: true,
success: function (data) {
alert(data + " DATA");
}
});
}
when I changed data and use autosuggestion then it will show data as
The door is blacl <span class="atwho-inserted">[[Ceilings]]</span>
How to ignore html tag and take only values of that?
Plz suggest me
Retrieve innerText rather than innerHTML in order to ignore the HTML content. If you want only the content inside the html tag with class .atwho-inserted, then retrieve only that content.
var textdata = text_id.innerText;
This is very consistent, but firebug is showing that my saveForm function is not being defined form my 'button.save' event handler, but it works for my 'button.deleteForm' event handler:
function saveForm(form)
{
var $form = form;
var url = $form.attr('action');
$.ajax({
type: "POST",
enctype: 'mutipart/form-data',
url: url,
data: $form.serialize(), // serializes the form's elements.
success: function(data)
{
// data is the server response.
// change this function to tell the
// user whether their submission
// is correct or what fields have
// bad data.
var response = JSON.parse(data);
return true;
}
});
return false; // avoid to execute the actual submit of the form.
}
// Do not use event handlers like .click(). This is the
// only viable solution for handling events on dynamically
// generated HTML elements. This handles the saving of data
// to the server.
$(document).on('click', 'button.save', function(e){
var $form = $(this).closest('form');
saveForm(form);
});
// This event handler is responsible for deleting data.
// For Joey's job: Please make sure that this calls save
// after the user hits delete. This will save the data in
// the database.
$(document).on('click', 'button.deleteForm', function(e){
// Get the form to update before deleting our embedded form
var $form = $(this).closest('form');
var str = $(this).attr('id');
// Get the table id in review to delete
var deleteForm = str + '_review';
$('table#' + deleteForm).remove();
// Get the collection form id to delete
var idArray = str.split('_');
idArray.pop();
divId = '#' + idArray.join('_');
$(divId).remove();
saveForm($form);
});
you missed $ in saveform
$(document).on('click', 'button.save', function(e){
var $form = $(this).closest('form');
saveForm($form);
//------^----here
});