I have a form being sent over ajax with event.preventdefault on it so it doesn't send automatically but this then stops the check boxes from functioning...
How do I get around this...
JSfiddle
$('[name="id"]').each(function (index, el) {
var getval = $(this).val();
console.log(getval);
$('#form_pub_priv_' + getval).on('click', function (event) {
event.preventDefault();
var arr_unchecked_values = $('input[type=checkbox]:not(:checked)').map(function () {
return this.value;
}).get();
var formvalues = $('#form_pub_priv_' + getval + ' [name="id"]').serialize();
var dataJoin = '&mod=' + arr_unchecked_values + '&' + formvalues;
console.log(dataJoin);
$.ajax({
url: 'unpublish-Lyst.html',
type: 'POST',
data: dataJoin
})
.done(function (data) {
console.log(data);
})
.fail(function () {
console.log("error");
})
.always(function () {
console.log("complete");
});
});
});
You're stopping the click event indirectly in your checkboxes, that's why your checkboxes don't work.
$('#form_pub_priv_' + getval).on('click', function (event) {
event.preventDefault(); //Remove this!
var arr_unchecked_values = ...
To prevent the form from being submited, you should do it in tye submit form event.
$('#form_pub_priv_' + getval).submit(function(event){
...
event.preventDefault(); //Here it's ok
});
Cheers
Related
I have written a code in Javascript in which I have attached an input type submit to a form. On form submit the listener gets called.
The problem is that on when I click the button once, one ajax call occurs. When I click it again two calls occur while only one call should occur on each click. Similarly on clicking 3 times 3 calls occur and so on...(the calls get increasing). If I refresh the page then the number gets reset. I have tried everything but I had no luck. If anyone found out what is wrong here it would be awesome. Thanks in advance.
javascript code:
$('input.create-discounts-quotations').click(function () {
var discount_quotation_type = $('input.quotation-discount-type').val();
if (discount_quotation_type == "value") {
var total = $('input.discount-input-quotation').val();
var discounted_price = product_price - total;
$('#final_discounted_amount').val(discounted_price);
$("table.product-response-table tr").each(function () {
var row = $(this).index() + 1;
var td = $(this).find('td.quotation-response-discounts');
$(td).each(function () {
$(this).html(total);
});
});
$("table.product-response-table tr").each(function () {
var row = $(this).index() + 1;
var td = $(this).find('td.product_final_price_discounted');
$(td).each(function () {
$(this).html(discounted_price);
});
});
var form1 = $('form#quotation_discount_update_form');
form1.on("submit", function (e) {
var form_data1 = form1.serialize();
$.ajax({
type: 'POST',
url: form1.attr('action'),
data: form_data1,
dataType: "json",
success: function (data) {
$('.quotation-discount-status-update').empty();
$('.quotation-discount-status-update').append('<div class="alert alert-success">Discount Added</div>');
}
});
e.preventDefault();
});
}
if (discount_quotation_type == "percentage") {
var total = $('input.discount-input-quotation').val();
var temp_first = product_price;
var temp1 = total / 100;
var temp2 = temp1 * product_price;
var discounted_price = product_price - temp2;
$('#final_discounted_amount').val(discounted_price);
$("table.product-response-table tr").each(function () {
var row = $(this).index() + 1;
var td = $(this).find('td.quotation-response-discounts');
$(td).each(function () {
$(this).html(total);
});
});
$("table.product-response-table tr").each(function () {
var row = $(this).index() + 1;
var td = $(this).find('td.product_final_price_discounted');
$(td).each(function () {
$(this).html(discounted_price);
});
});
var form1 = $('form#quotation_discount_update_form');
form1.on("submit", function (e) {
var form_data1 = form1.serialize();
$.ajax({
type: 'POST',
url: form1.attr('action'),
data: form_data1,
dataType: "json",
success: function (data) {
$('.quotation-discount-status-update').empty();
$('.quotation-discount-status-update').append('<div class="alert alert-success">Discount Added</div>');
}
});
e.preventDefault();
});
}
if (discount_quotation_type == "not_selected") {
$('.quotation-discount-status-update').empty();
$('.quotation-discount-status-update').append('<div class="alert alert-danger">Discount Method Not Selected</div>');
return false;
}
// return false;
});
That happen because every time you click your code will reattach the submit event so it will be duplicated in every click.
You should never attach the events inside other events, please put the submit event outside of the click event and the code should work, example :
var form1 = $('form#quotation_discount_update_form');
form1.on("submit", function (e) {
var form_data1 = form1.serialize();
$.ajax({
type: 'POST',
url: form1.attr('action'),
data: form_data1,
dataType: "json",
success: function (data) {
$('.quotation-discount-status-update').empty();
$('.quotation-discount-status-update').append('<div class="alert alert-success">Discount Added</div>');
}
});
e.preventDefault();
});
Else you have to remove the event handler every time using .off(), like :
form1.off("submit").on("submit", function (e) {
Ajax1:
<script type="text/javascript">
$(document).ready(function () {
$('.CategoryName').click(function() {
var categoryName = $(this).attr("data-id");
var url="{{url('getSubCategoryName/').'/'}}" + categoryName;
$.ajax({
url : url,
type: 'GET',
dataType:'json',
success:function(data){
$.each(data, function( index, value ) {
var output = '';
output = ' ' + value.subCategoryName + '';
**$(".subcategory").append('<ul><li data-
id="'+value.subCategoryName+'" class="getDeviceCategoryName">'+value.subCategoryName+'</li></ul>')**
});
}
});
});
});
</script>
The code which is marked in bold has the value for data-id attribute..And I need to pass that value when class named getDeviceCategoryName is clicked.
AJAX2:
<script type="text/javascript">
$(document).ready(function () {
$('.getDeviceCategoryName').click(function() {
var subCategoryName = $(this).attr("data-id");
alert(subCategoryName);
});
});
</script>
This is one I tried for that..But its not working.It doesnot alerts or shows any error.
You should consider jquery event delegation:
Change your jquery selector line like this:
<script type="text/javascript">
$(document).ready(function () {
$(document).on('click','.getDeviceCategoryName',function() {
var subCategoryName = $(this).attr("data-id");
alert(subCategoryName);
});
});
</script>
Here you go with a solution
$(document).ready(function () {
$(document).on('click', 'li.getDeviceCategoryName', function() {
console.log($(this).data("id"));
});
});
Since the elements are generated dynamically, so you need to delegate events.
For receiving the data-attribute you can do $(this).data("attribute-name"); in your scenario it will be $(this).data('id');
Hope this will help you.
Personally I think code is more efficient if the click event is applied to the element right after it's created.
$(function () {
$('.CategoryName').click(function () {
var categoryName = $(this).attr('data-id');
var url = '{{url(\'getSubCategoryName/\').\'/\'}}' + categoryName;
$.ajax({
url: url,
type: 'GET',
dataType: 'json',
success: function (data) {
$.each(data, function (index, value) {
var output = '';
output = ' ' + value.subCategoryName + '';
$('.subcategory').append($('<ul/>').append('<li data-id="' + value.subCategoryName + '" class="getDeviceCategoryName">' + value.subCategoryName + '</li>')
.find('li')
.click(function () {
var subCategoryName = $(this).attr('data-id');
alert(subCategoryName);
});
);
});
}
});
});
});
$(document).ready(function () {
$(document).on('click', '.getDeviceCategoryName', function(){
var subCategoryName = $(this).attr("data-id");
alert(subCategoryName);
});
});
i made a function that sends data (ajax) to the database and depending on the response from the server i need to alert a message but it seems like whenvever i change the select option i get the alert message for each change(if i change the select four times when i click i get the alert four times ) , but if i remove my ajax function and replace it simply by an alert i get it once not repeating itself here is my JS
$('.select_ids').change(function () {
var id = $(this).val();
var form = $('#form_widget_ids_' + id);
var container = form.parent('.ewb_forms');
var box = container.parent('.edit_widget_box');
container.children('.selected').fadeOut(300, function () {
$(this).removeClass('selected');
form.fadeIn(300, function () {
$(this).addClass('selected');
});
});
Widget.updateSSOUrl(box);
$.ajax({
type: "POST",
url: window.location + "",
data: {'id': id}
}).done(function (msg) {
$(".red").on('click', function (evt) {
if ('done' == msg) {
evt.preventDefault();
alert('NOP');
}
})
});
});
the event that you are binding i think is wrong. For newly append items is better in your case to use
$(document).on('click', ".red", function (evt) {
})
And it must be moved outside the ajax success because now you are triggering it every time
----- Edited ---
If you want just to alert the output of the ajax you dont need the onClick event
$('.select_ids').change(function () {
var id = $(this).val();
var form = $('#form_widget_ids_' + id);
var container = form.parent('.ewb_forms');
var box = container.parent('.edit_widget_box');
container.children('.selected').fadeOut(300, function () {
$(this).removeClass('selected');
form.fadeIn(300, function () {
$(this).addClass('selected');
});
});
Widget.updateSSOUrl(box);
$.ajax({
type: "POST",
url: window.location + "",
data: {'id': id}
}).done(function (msg) {
if (msg === 'done') {
evt.preventDefault();
alert('NOP');
}
});
});
If you want to show the latest result on a button click you can store the msg on a global variable and on click of a div show that like
var globalMsg = "";
$('.select_ids').change(function () {
var id = $(this).val();
var form = $('#form_widget_ids_' + id);
var container = form.parent('.ewb_forms');
var box = container.parent('.edit_widget_box');
container.children('.selected').fadeOut(300, function () {
$(this).removeClass('selected');
form.fadeIn(300, function () {
$(this).addClass('selected');
});
});
Widget.updateSSOUrl(box);
$.ajax({
type: "POST",
url: window.location + "",
data: {'id': id}
}).done(function (msg) {
globalMsg = msg
});
});
$(".div").click(function() { alert(globalMSG); });
I have an ajax function, which submits the data and refreshes the div after the data has been updated. The problem is that the jQuery elements within the div breaks after the form has been submitted, and the div has been refreshed.
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null
}
tournamentid = getURLParameter('id');
$(document).ready(function () {
$(document).on('click', "button#submit" ,function(){
$.ajax({
type: "POST",
url: "test.php?page=tourneys&id=" + tournamentid + "&action=teams&submit=true", //process to mail
data: $('#swapteams').serialize(),
success: function(msg){
createNoty('The teams has been updated!', 'success');
// Refresh the div after submission
$("#refresh").load("test.php?page=tourneys&id=" + tournamentid + "&action=teams #refresh");
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
return false;
});
});
// the plugins and jQuery variables within the refresh div
$(document).ready(function() {
$('a[id^="teamname"]').editable({
ajaxOptions : {
type : 'post'
}
});
});
$(document).ready(function() {
$('select[id="swap"]').change(function(){
$( "#saveprogress" ).show("fade");
});
});
You need to use event delegation to support dynamically added elements also you need to initialize the plugin again once the div is refreshed
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [, ""])[1].replace(/\+/g, '%20')) || null
}
tournamentid = getURLParameter('id');
$(document).ready(function () {
$(document).on('click', "button#submit", function () {
$.ajax({
type: "POST",
url: "test.php?page=tourneys&id=" + tournamentid + "&action=teams&submit=true", //process to mail
data: $('#swapteams').serialize(),
success: function (msg) {
createNoty('The teams has been updated!', 'success');
// Refresh the div after submission and pass a callback which will initialize the plugins
$("#refresh").load("test.php?page=tourneys&id=" + tournamentid + "&action=teams #refresh", createEditable);
},
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
return false;
});
});
// the plugins and jQuery variables within the refresh div
$(document).ready(createEditable);
function createEditable() {
$('a[id^="teamname"]').editable({
ajaxOptions: {
type: 'post'
}
});
}
$(document).ready(function () {
//use event delegation
$(document).on('change', 'select[id="swap"]', function () {
$("#saveprogress").show("fade");
});
});
I hired a developer to help with some work, he was mostly PHP focused and attempted this javascript. The following AJAX script breaks the page whenever it reloads the HTML into the DOM. It called a function via Codenigniter to reload the view within the page. Once this happens, all of the javascript no longer works.
I can't seem to find a solution that helps solve this issue. Please help.
Note: Ideally I would of rather the code only loaded the data and not refresh the HTML, but for now this will need to do as I am up against a timeline.
The code:
$(document).ready(function () {
// Ajax Form Submit
$('body').on('click', '.submitForm', function () {
var formid = $(this).parents('form').attr('id');
var validationResult = $('#' + formid).validationEngine('validate');
if (!validationResult) {
return false;
}
var url = $('#' + formid).attr('action');
var formdata = $('#' + formid).serialize();
if ($('#' + formid).find('.submitForm').hasClass('loading')) {
$(this).hide();
$('#' + formid).find('.loader').show();
}
$.ajax({
type: "POST",
cache: false,
url: url,
data: formdata,
dataType: 'json',
success: function (data) {
if ($('#' + formid).find('.submitForm').hasClass('loading')) {
$('#' + formid).find('.submitForm').css('display', 'inline');
$('#' + formid).find('.loader').hide();
}
if (data.type == 'add') {
if (data.html) {
var newhtml = "<tr>" + data.html + "</tr>";
$('.tab-pane.active table').append(newhtml);
}
$('#' + formid).find('.message').html(data.msg).show();
$('#' + formid).trigger('reset');
setInterval(function () {
$('#' + formid).find('.message').hide();
}, 5000);
} else {
if (data.error) {
$('#' + formid + ' .message').show().html(data.error);
} else {
$('#' + formid + ' .message').show().html(data.msg);
if (data.reload_loc) {
window.setTimeout(function () {
window.location.href = data.reload_loc;
}, 4 * 1000);
}
}
}
}
});
});
// Generic Save Form Data
$('body').on('click', '#saveFormdata', function () {
var formid = $(this).parents('form').attr('id');
var validationResult = $('#' + formid).validationEngine('validate');
if (!validationResult) {
return false;
}
$('#' + formid).submit();
});
});
You just do something like this:
function bindEvent()
{
$('body').on('click', '.submitForm', function () { //Your code });
$('body').on('click', '#saveFormdata', function () { //Your code});
}
function unblindEvent()
{
$('body').off('click', '.submitForm'); //Something like this, please read Jquery.off
$('body').off('click', '#saveFormdata');
}
Before you replace these element, call unblindEvent(). And after you replace these elements call bindEvent().