create onclick event for multiple ids - javascript

I have written a js function:
$(document).on('click', '#id1', function () {
$.ajax({
type: "POST",
url: "/url",
data: { uInput: 'id1' },
success: function (response) {
some code....
},
error: function (error) {
console.log(error);
}
});
});
Problem is, since I have more clickable objects with various IDs, i wanted to create a single script/function that would accept onclick event from not only #id1, but also #id2, #id3 etc...
I tried following advice found here: https://stackoverflow.com/a/18508894/11271927
and here https://stackoverflow.com/a/18508907/11271927
but whenever I would edit the code to acomodate my code structure, it wouldnt work.
var options = {
id1: 'id1',
id2: 'id2',
id3: 'id3',
id4: 'id4'
};
$('.options').click(function () {
$.ajax({
type: "POST",
url: "/url",
data: options[this.id],
success: function (response) {
some code....
},
error: function (error) {
console.log(error);
}
});
});
Essentially, this code doesnt do anythign on click.
If you know what I have missed or done wrong, please help.

If you want to have one function that will have a click listener on several elements (for example by class) you can try it like this:
<button class="button" id="id1">A</button>
<button class="button" id="id2">B</button>
<button class="button" id="id3">C</button>
<script>
$(document).on('click', '.button', function () {
$.ajax({
type: "POST",
url: "/url",
data: {
uInput: this.getAttribute('id'),
},
success: function (response) {
console.log(response);
},
error: function (error) {
console.log(error);
}
});
});
</script>

You can set a single click event listener on the document and use a conditional inside its function to apply the same statement block to any groups of elements.
For example, you could filter for targets that have id begining with the string "id" like this (core js):
document.addEventListener('click', event => {
if (event.target.id.indexOf('id') == 0) {
// commands to apply to those elements;
} // end if #id* click;
// any number of other groups or individual elements can be added, each with a conditional to filter the required ones.
}); // end event listener
If you require more specificity, refine the conditional, for example (inside the document event listener function):
const id=event.target.id;
if (id == "id1" || id == "id3" || id == "somethingElse") {
// relevant statements;
};
I generally use document event listeners by default, there is no extra computational cost and I find the single event listener easier to maintain.

Related

Can't delete data after 10 entries in AJAX, JQuery and javascript/php

I have 10 rows with data inserted and I'm able to delete any of those, but after I insert from 11th row onwards I can't delete any of the rows after the 10th.
EDIT (I CAN'T DELETE ANYTHING WHEN THE RESPONSIVE FORM IS SHOWING)
$(document).ready(function(){
$('#list').dataTable({
responsive: true
});
$('.delete_piece').click(function(){
_conf("Are you sure to delete this piece?","delete_piece",[$(this).attr('data-id')])
})
})
function delete_piece($id){
start_load()
$.ajax({
url:'ajax.php?action=delete_piece',
method:'POST',
data:{id:$id},
success:function(resp){
if(resp==1){
alert_toast("Data successfully deleted",'success')
setTimeout(function(){
location.reload()
},1500)
}
}
})
}
DELETE FUNCTION AJAX
if($action == "delete_piece"){
$delsete = $crud->delete_piece();
if($delsete)
echo $delsete;
}
DELETE FUNCTION FOR THE ADMIN (ME)
function delete_piece(){
extract($_POST);
$delete = $this->db->query("DELETE FROM mro_inventory where id = ".$id);
if($delete){
return 1;
}
}
Consider the following.
$(function() {
function delete_piece($id) {
start_load()
$.ajax({
url: 'ajax.php?action=delete_piece',
method: 'POST',
data: {
id: $id
},
success: function(resp) {
if (resp == 1) {
alert_toast("Data successfully deleted", 'success')
setTimeout(function() {
location.reload()
}, 1500);
}
}
});
}
$('#list').dataTable({
responsive: true
});
$('tbody').on("click", ".delete_piece", function(e) {
_conf("Are you sure to delete this piece?", "delete_piece", [$(this).attr('data-id')])
});
});
This uses the .on() method to delegate the click event to a class.
Delegated event handlers have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated event handlers to avoid the need to frequently attach and remove event handlers.
See more: https://api.jquery.com/on/
It was not clear from your post what the HTML structure looks like; yet, you are using DataTables, so I know there should be a Table Body element that should be present.
this is how I solved the problem!!
$(document).ready(function() {
$('#list').dataTable({
responsive: true
});
$('tbody').on("click", ".delete_piece", function() {
_conf("Are you sure to delete this piece?","delete_piece",[$(this).attr('data-id')])
})
})
function delete_piece($id){
start_load()
$.ajax({
url: 'ajax.php?action=delete_piece',
method: 'POST',
data: {
id:$id
},
success: function(resp) {
if (resp == 1) {
alert_toast("Data successfully deleted",'success')
setTimeout(function() {
location.reload()
}, 1500)
}
}
})
}

AJAX/jQuery generated inputs not recognized by other jQuery scripts

I have what I assume is a relatively simple issue. For testing purposes I have made it so simple so as to locate the issue.
I have a jQuery script that works alongside AJAX to return some results next to checkboxes, here it is below:
$.ajax({
type:'GET',
url: '/customers/details/emails',
dataType:'json',
data: {
'customerID': $('select[name=payer_id]').val(),
'_token': $('input[name=_token]').val(),
},
success: function(data) {
$('.errorTitle').addClass('hidden');
$('.errorContent').addClass('hidden');
if ((data.errors)) {
setTimeout(function () {
$('#createOrigin').modal('show');
toastr.error('Check your inputs!', 'Error Alert', {timeOut: 5000});
}, 500);
if (data.errors.title) {
$('.errorTitle').removeClass('hidden');
$('.errorTitle').text(data.errors.title);
}
if (data.errors.content) {
$('.errorContent').removeClass('hidden');
$('.errorContent').text(data.errors.content);
}
} else {
$.each(data, function(i,val) {
$('<tr>').append(
$('<td>').html('<input type="checkbox" id="emailCheckboxSelect">'),
$('<td>').text(val)).appendTo('#customerEmails');
});
}
}
});
As you can see near the end, for each result a table row is appended, with a checkbox with an id of "emailCheckboxSelect".
Now to my problem, these are obviously dynamically created elements so I believe this is the issue with this script (a simple dummy just to locate the issue). Here is that script that should work:
$(function(){
$('#emailCheckboxSelect').click(function(){
alert('clicked');
});
});
This doesn't work with the dynamically created elements. However, I did add <input type="checkbox" id="emailCheckboxSelect">Checkbox directly to my page, and this does set off the alert.
So what am I doing wrong and what do I need to do so that jQuery can recognize dynamically created elements?
Try to bind the click event after the $.each(data, function() {}) inside the sucess: function() {}
You are using multiple elements with same id in the DOM : Element IDs should be unique within the entire document.
use classes instead
your code will look like:
$.ajax({
type: 'GET',
url: '/customers/details/emails',
dataType: 'json',
data: {
'customerID': $('select[name=payer_id]').val(),
'_token': $('input[name=_token]').val(),
},
success: function(data) {
$('.errorTitle').addClass('hidden');
$('.errorContent').addClass('hidden');
if ((data.errors)) {
setTimeout(function() {
$('#createOrigin').modal('show');
toastr.error('Check your inputs!', 'Error Alert', {
timeOut: 5000
});
}, 500);
if (data.errors.title) {
$('.errorTitle').removeClass('hidden');
$('.errorTitle').text(data.errors.title);
}
if (data.errors.content) {
$('.errorContent').removeClass('hidden');
$('.errorContent').text(data.errors.content);
}
} else {
$.each(data, function(i, val) {
$('<tr>').append(
$('<td>').html('<input type="checkbox" class="emailCheckboxSelect" />'),
$('<td>').text(val)).appendTo('#customerEmails');
});
$('.emailCheckboxSelect').click(function(e) {
alert('clicked');
});
}
}
});
Try changing your click event to something like
$('td').on('click', '.emailCheckboxSelect', function () {
alert('clicked');
});
This would work on dynamically created elements. Also, use class instead of id for dynamically created elements.

.focusout() fires twice on second event jQuery

When I am using the .focusout() function in jQuery it seems to fire twice when I trigger the event for the second time, here is an example of my code:
$(document).ready(function() {
var baseUrl = "http://annuityadvicecentre.dev/";
if($('html').hasClass('ver--prize-soft')) {
$('#home_telephone').focusout(function () {
var softResponse = {};
var inputVal = $(this).val();
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
$.ajax({
type: 'POST',
url: baseUrl + "lookup",
data: {
number: inputVal,
phone_type: "mobile",
},
error: function() {
console.log('POST Error: Mobile');
},
}).done(function(data) {
// you may safely use results here
softResponse.isMobile = data;
});
$.ajax({
type: 'POST',
url: baseUrl + "lookup",
data: {
number: inputVal,
phone_type: "landline",
},
error: function() {
console.log('POST Error: Landline');
},
}).done(function(data) {
// you may safely use results here
softResponse.isLandline = data;
});
$(document).ajaxStop(function () {
console.log('All AJAX Requests Have Stopped');
});
});
}
});
Sorry for the messy example as I have just been bootstrapping this up however you can see I am wrapping this focusout function:
$('#home_telephone').focusout(function () {...
Around my AJAX calls, now for some reason when I test this out on the page and un-focus on the #home_telephone element the .ajaxStop() function only runs once which is the functionality I want however if I then click on the element and un-focus again the .ajaxStop() function runs twice. Any idea why this might be happening? Thanks
Try to add e.stoppropogation() within function like:
$('#home_telephone').focusout(function (e) {
e.stopPropagation()();
//your code
});
You're adding a new ajaxStop listener every time the element is unfocused. Just move the:
$(document).ajaxStop(function () {
console.log('All AJAX Requests Have Stopped');
});
call outside of the focusout callback function.

unbind and off doesn't work before call ajax-Jquery

I have an element with class.btn-confirm and handel click event like this in MasterLayout (ASP.NET MVC)
$(document).on('click', '.btn-confirm', function () {
$.ajax({
url: $('#url').data('deleteurl'),
type: "POST",
data: { code: $('.btn-confirm').data('code') },
success: function (data) {
ShowMessage(data.message, 'success');
},
error: function (responce) {
ShowMessage('error', 'error');
}
});
});
and I want override this event in Other Page like this :
$('.btn-confirm').unbind('click');
$('.btn-confirm').off('click');
$(document).on('click', '.btn-confirm', function ()
{
...}
but when I clicked on button , run two functions , I want disable first event handle.
I used unbind and off but it does not work.
If you bind the event on document you must then also unbind it on document
$(document).off('click', '.btn-confirm');
$(document).on ('click', '.btn-confirm', ...new function...

How to pass data from a html page to another?

I have two pages:
choose.html
create.html
In the choose.html I can choose an entry from a listview. I can click on such entries in the listview and I want to pass the ID of that entry so that I can use the ID on the html page create.html.
ID is a number.
I have done:
When I clicked on an entry, I get the ID:
function postID(id) {
alert(id);
}
This functions so far.
Then I tried this code with a GET on the create.html:
POST:
function postID(id) {
$.ajax({
url: "create.html",
type: "POST",
dataType: "text",
data: id,
success: function () {
document.location.href = "create.html";
},
error: function (jqXhr) {
alert("Error");
}
});
}
GET:
try {
$.get("chooseAddress.html", function (id) {
alert(id);
});
}
catch (e) {
alert();
}
But nothing happens. Can you help me?
Thanks
So many work for so simple problem. Use a hidden field or use a Session variable.
Use create a hidden field and give value as your Id.
<form action='create.html'>
<input type='hidden' value='id'>
</form>

Categories

Resources