Bootstrap Confirmation data-on-confirm not executing function - javascript

I'm trying to make a delete confirmation execute a function that deletes the current id data.
I am getting this error:
Uncaught TypeError: Cannot read property 'call' of undefined
in this part of the bootstrap-confirmation.js
return function() {
context[func].call(this);
};
this is my button code
<button class="btn btn-danger" data-toggle="confirmation"
data- btn-ok- class="btn-danger" data-btn-cancel-icon="glyphicon
glyphicon-ban-circle" data-btn-cancel-class="btn-default"
data-popout="true" data-singleton="true" data-on-confirm="goDel(id)">
Eliminar</button>
this is my Javascript
<script type="text/javascript">
function goDel(id)
{
location.href="./delete/" + id;
}
</script>
this is my delete controller
public function delete($id) {
$clientes = new Clientes();
$codcta = new Codcta();
$this -> codcta = $codcta -> find();
$codciu = new Codciu();
$this -> codciu = $codciu -> find();
$clientes = new clientes();
if ($clientes->delete((int)$id)) {
Flash::valid('El registro se ha eliminado correctamente');
}else{
Flash::error('Falló Operación');
}
return Redirect::to();
}

Change this in your button:
data-on-confirm="goDel"
and add this:
data-id="YOUR-ID-HERE"
in your javascript function:
function goDel()
{
var id = $(this)[0].getAttribute('data-id');
location.href="./delete/" + id;
}
Good Luck!

The button code in HTML will be:
<button class="btn btn-danger" data-toggle="confirmation" data-title="Title here" data-content="Content here" data-btn-cancel-icon="glyphicon
glyphicon-ban-circle" data-btn-cancel-class="btn-default"
data-popout="true" data-singleton="true" data-on-confirm="deleteMethodName" data-id="your-deleted-id-here">Eliminar</button>
The javascript function code will be:
function deleteMethodName()
{
var id = $(this)[0].getAttribute('data-id');
//Now you will get ID from above and use it as you like
}

Related

How to fix .addEventListener is not a function [duplicate]

This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed 1 year ago.
I'm getting an error that addeventlistener is not a function. I try to put it into a function but it didn't work. I also did this with btn.onclick event but I was getting the error:
"Uncaught TypeError: Cannot set property 'onclick'".
Any idea how to fix this, and why am I getting this error?
Here is the code:
<!-- try run this -->
<div class="input_wrpr">
<input class="enter_1" type="number" />
<input class="enter_2" type="number" />
<button data-combine="plus" class="combine_ plus" type="submit"> + </button>
<button data-combine="minus" class="combine_ minus" type="submit"> - </button>
<button data-combine="multi" class="combine_ multi" type="submit"> * </button>
<button data-combine="divi" class="combine_ divi" type="submit"> / </button>
<p class="result_"></p>
</div>
<script>
(function () {
"use strict";
var slc = (elemnt) => {
return document.querySelectorAll(elemnt);
};
var view = slc(".result_"),
btn = slc(".combine_"),
input1 = slc(".enter_1"),
input2 = slc(".enter_2");
btn.addEventListener("click", (e) => {
view.innerHTML = parseInt(input1.value) + parseInt(input2.value);
});
})(); // i know this code is not complete but i'm having an issue with eventlistener// i try this using loop but it's not working i mean i'm not getting any errors but result is not printing/
// i didn't try this using getAttribute because i don't know how to do with that especially with data- attribute.
// * this below code is working fine but i wanted to shorteren this code
// * i gusse you alredy have seen it that here i have to give eventlistener to each button and i'm using querySelector but above i'm using querySelectorAll.
// (function () {
// "use strict";
// var slc = (elemnt) => {
// return document.querySelector(elemnt);
// };
// var view = slc(".result_"),
// plus = slc(".plus"),
// minus = slc(".minus"),
// multi = slc(".multi"),
// divi = slc(".divi"),
// input1 = slc(".enter_1"),
// input2 = slc(".enter_2");
// plus.addEventListener("click", (e) => {
// view.innerHTML = parseInt(input1.value) + parseInt(input2.value);
// input1.value = "";
// input2.value = "";
// });
// minus.addEventListener("click", (e) => {
// view.innerHTML = parseInt(input1.value) - parseInt(input2.value);
// input1.value = "";
// input2.value = "";
// });
// multi.addEventListener("click", (e) => {
// view.innerHTML = parseInt(input1.value) * parseInt(input2.value);
// input1.value = "";
// input2.value = "";
// });
// divi.addEventListener("click", (e) => {
// view.innerHTML = parseInt(input1.value) / parseInt(input2.value);
// input1.value = "";
// input2.value = "";
// });
// })();
</script>
querySelectorAll returns a collection of node elements. If you have multiple elements that match you selector you have to iterate over this collection and set the listener for each element. If you are sure there is only one element that matches the selector you can use querySelector to get the first element that matches. Then you can set the listener directly to the element.
As previously noted querySelectorAll will return a nodelist rather than a specific node and thus assigning an event listener as you do will not work. Instead the nodelist should be iterated through and the event listener applied to each node. The idea of using a shortcut to document.querySelectorAll is one I do frequently but they are a little different as shown below. The remains of the code can be simplified a little ...
(function () {
"use strict";
var q=(e,n=document)=>n.querySelector(e);
var qa=(e,n=document)=>n.querySelectorAll(e);
var view = q(".result_");
var btns = qa(".combine_");
let clickhandler=(e)=>{
e.preventDefault();
let a=Number( q(".enter_1").value );
let b=Number( q(".enter_2").value );
let c;
switch(e.target.dataset.combine){
case 'plus':c=a+b;break;
case 'minus':c=a-b;break;
case 'multi':c=a*b;break;
case 'divi':c=a/b;break;
}
view.textContent=c.toString();
};
btns.forEach( btn=>btn.addEventListener("click", clickhandler ) );
})();
<!-- try run this -->
<div class="input_wrpr">
<input name='a' class="enter_1" type="number" />
<input name='b' class="enter_2" type="number" />
<button data-combine="plus" class="combine_ plus" type="submit"> + </button>
<button data-combine="minus" class="combine_ minus" type="submit"> - </button>
<button data-combine="multi" class="combine_ multi" type="submit"> * </button>
<button data-combine="divi" class="combine_ divi" type="submit"> / </button>
<p class="result_"></p>
</div>
Your btn is an array of node (your buttons), you can't do and addEventListener on a array? You need first to make a true array like that:
var btn = [...slc('.combine_')]
And then loop the array and create the events listener, like that :
for(let i=0; i<btn.length; i++){
btn[i].addEventListener("click", ()=>{})
}

Onclick cannot find function to execute

I am using an onclick() function to add an item to cart.
<button class='btn pull-right' id = 'cartBtn' onclick = 'addToCart(<?php echo $id;?>)'><span class='glyphicon glyphicon-shopping-cart'></span></button>
This is the js:
$(document).ready(function(){
var cart = [];
var id = $("#itemId").text();
var stockAvailable = $("itemStock").text();
var inCart = false;
function addToCart(item){
id = item;
if (inCart == true){
console.log("item already in cart");
}
else{
cart.push(id);
}
}
However, I get the following error in the console upon clicking the button:
ReferenceError: addToCart is not defined
I have written the js code on a separate file and inluded it in the head section.
What could be the problem here
You cannot use addToCart without defining it.
You can define it in the place where you want to use this function.
$(document).ready(function() {
function addToCart(item) {
console.log('added');
}
});
addToCart('item');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Right way
function addToCart(item) {
console.log('added');
}
$(document).ready(function() {
});
addToCart('item');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
from the official jquery docs. https://learn.jquery.com/using-jquery-core/document-ready/
TLDR: document.ready runs only once so define your function outside of it.
Here i am showing you very basic example code based on your question
var id, cart = [], stockAvailable, inCart = false;
$(document).ready(function(){
id = $("#itemId").text();
stockAvailable = $("itemStock").text();
});
function addToCart(item){
id = item;
if (inCart == true){
console.log("item already in cart");
}
else{
cart.push(id);
inCart = true;
console.log("item added in cart");
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class='btn pull-right' id = 'cartBtn' onclick = 'addToCart(1)'><span class='glyphicon glyphicon-shopping-cart'></span> Add to Cart</button>
Anyways you are using Jquery, so can you please check with jquery event handler.
Please find the answer using jquery click event.
$("#cartBtn").on("click", function(item){
id = item;
if (inCart == true){
console.log("item already in cart");
}
else{
cart.push(id);
}
}
})

Javascript plugin needs to call back to client's Javascript

I am working on a plugin that allows to add an item to the shopping cart. The plugin is mine, and the shopping cart belongs to the customer. The idea is to add my plugin with a few lines of code to configure.
Once an item is bought, I need to call a function on the customer page so it can be added to the cart, but I didn't manage.
I have this code:
<script type="text/javascript">
$(document).ready(function () {
//plugin1.CallBackTest;
});
var plugin1 = new function() {
this.CallBackTest = function (str) {
console.log("callback in class");
FunctionIWantToCall(str);
}
}
function FunctionIWantToCall(str) {
console.log("callback on client " + str);
}
</script>
<div class="htmlcreatedbyplugin">
<button onclick="CallBackTest('something')">send back</button>
</div>
if I change this line to
send back
it will work, but this html is generated through the plugin class, and I don't know how to retrieve the name of the variable.
The customer should be able to tell the plugin which function to call, e.g
plugin1.AddToCartFunction = FunctionIWantToCall;
Any ideas?
Thank you Stavros Angelis, it works:
<script type="text/javascript">
$(document).ready(function () {
plugin1.CallBackFunction = "FunctionIWantToCall";
});
var plugin1 = new function () {
var myplugin = this;
this.CallBackFunction = "";
this.CallBackTest = function () {
console.log("callback in class");
var item = JSON.parse($(this).attr("vals"));
if (myplugin.CallBackFunction != "") {
window[myplugin.CallBackFunction](item);
}
}
function BindCartButtons() {
console.log("binding buttons")
$(document).on("click", ".htmlcreatedbyplugin > button", myplugin.CallBackTest);
}
BindCartButtons();
}
function FunctionIWantToCall(item) {
console.log("callback on client " + item.id);
}
</script>
<div class="htmlcreatedbyplugin">
<button type="button" vals="{"id":12345, "color":"blue"}">Buy Me</button>
</div>

JQuery Button Data Returning As Null?

I have a button and when I click it, I want the html object (aka button) to be passed as a parameter to another javascript function. I want the javascript function to print the data-hi from the element in the button.
HTML BUTTON
<button type = "button" onclick = "whoIsRdns(this)" class="dns-information btn btn-xs btn-info pull-right" data-toggle="modal" data-target = "#whois_rdns_modal" data-path="{{ path( '_who_is_rdns', { 'peer': peer.number, 'ip': peer.mac } ) }}" data-hi = "hi2">
<i class="icon-search"></i>
</button>
JS FUNCTION(W/ JQUERY)
function whoIsRdns(thisButton){
//Enable jQuery properties from the param of the HTML object
var btn = $(thisButton);
var test = btn.data('hi');
console.log('Value is ' + test);
}
Why would test return as null?
Shouldn't var btn = $("thisButton"); be var btn = $(thisButton); (without quotes)
Just a typo
$("thisButton") !== $(thisButton);
drop the quotes so you are not looking for an element with a tag name thisButton
var btn = $("thisButton");
needs to be
var btn = $(thisButton);

function is not defined when I click on a button

I generate modal forms using function function makeModalEnroll(name, description, i, id)
And in one of my lines there is a string
modal += '<button type="button" id="enroll' + i + '" class="btn btn-success" data-dismiss="modal" onclick="send(this.id);"> Enroll <span class="glyphicon glyphicon-arrow-right"></span> </button>';
I've got function send and for now I submit form with id = 0
function send(id) {
alert(id);
var c = id.charAt(id.length - 1);
alert(c);
$('#enrollForm0').ajaxSubmit({url: 'enroll.html', type: 'post'});
};
But browser says that ReferenceError: send is not defined.
I tried to put function send before and after function makeModalEnroll but this error is always occurs.
How to solve this problem?
May be you don't expose your function to the global scope, try this:
window.send = function(id) {
alert(id);
var c = id.charAt(id.length - 1);
alert(c);
$('#enrollForm0').ajaxSubmit({url: 'enroll.html', type: 'post'});
};

Categories

Resources