Onclick cannot find function to execute - javascript

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);
}
}
})

Related

How to edit and delete individual items from CRUD app

I'm trying to write a CRUD app. I'm having trouble figuring out how to edit and delete individual items. For each item created, I'm making two <a> tags inside of a <span> tag. One for edit and one for delete. But I can't seem to figure out how to make them do what they need to do. At this point they don't do anything because I can't figure out how to access the values correctly.
Note - I'm just beginning to learn jQuery so, any pro tips on that are appreciated.
Here's the html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
<form class='form'>
<input id="input" type="text" placeholder="Type here..">
</form>
<h3>Notes</h3>
<ul></ul>
<button id='clear'>Clear All</button>
</div>
<script src="app.js"></script>
</body>
</html>
And the javascript:
const app = {};
app.counter = (function(){
var i = -1;
return function(){
i += 1;
return i;
}
})()
app.create = function(element){
return document.createElement(element);
}
app.select = function(element){
return document.querySelector(element);
}
app.makeList = function(text) {
var i = app.counter();
var li = app.create('li');
var div = app.create('span');
var edit = app.create('a');
var del = app.create('a');
li.textContent = text;
edit.textContent = ' Edit';
edit.href = '#'
del.textContent = ' Delete';
del.href = '#'
div.appendChild(edit);
div.appendChild(del);
li.appendChild(div);
ul.insertBefore(li, ul.childNodes[0])
li.id = 'item' + i;
del.id = 'delete' + i;
edit.id = 'edit' + i;
}
// constants & variables
const ul = app.select('ul')
const input = app.select('input')
var notes;
$(document).ready(function(){
if (localStorage.getItem('notes')) {
notes = JSON.parse(localStorage.getItem('notes'));
} else {
notes = [];
}
localStorage.setItem('notes', JSON.stringify(notes));
// build list items and display them on the page
JSON.parse(localStorage.getItem('notes')).forEach(function(item){
app.makeList(item);
});
// when form is submitted
$('.form').submit(function(e){
e.preventDefault();
if (input.value.length > 0){
notes.push(input.value);
localStorage.setItem('notes', JSON.stringify(notes));
app.makeList(input.value);
input.value = "";
}
})
// clear items on page and from local storage
$('#clear').click(function(){
if (window.confirm('This will clear all items.\nAre you sure you want to do this?')){
localStorage.clear();
while (ul.firstChild) {
ul.removeChild(ul.firstChild)
}
}
});
$('ul').on('click', 'li', function(){
console.log(this.textContent) // logs whatever is typed + Edit Delete
})
});
Do something like this.
$("ul").on("click", "li", function(e) {
console.log(this.textContent); // logs whatever is typed + Edit Delete
if(e.target.id === "edit") {
//edit
}
if(e.target.id==="delete") {
//delete
}
});
You are trying to access elements before they are ready that is why you are not able to see anything.
Declare them on global level but assign them value after the document is ready.
var ul;
var input;
var notes;
$(document).ready(function () {
ul = app.select('ul')
input = app.select('input')
...Rest of your code
});
For the Edit and Delete Functionality
As you are appedning IDs in edit and delete button you need to parse that as well
$('ul').on('click', 'li', function (e) {
if (e.target.id.includes('edit')) {
console.log(` item ${e.target.id.split('edit')[1]} needs to be edited.`)
}
if (e.target.id.includes('delete')) {
//delete
}
})

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>

How to clear input field after hitting submit

I have a form, and I would like to clear the input field every time I enter the submit (plus) button.
I have tried using this, it does not work. I may be implementing it in the wrong spot.
document.getElementById('add-item').value='';
My Javascript code is below.
window.addEventListener('load', function(){
// Add event listeners
document.getElementById('add-item').addEventListener('click', addItem, false);
document.querySelector('.todo-list').addEventListener('click', toggleCompleted, false);
document.querySelector('.todo-list').addEventListener('click', removeItem, false);
function toggleCompleted(event) {
console.log('=' + event.target.className);
if(event.target.className.indexOf('todo-item') < 0) {
return;
}
console.log(event.target.className.indexOf('completed'));
if(event.target.className.indexOf('completed') > -1) {
console.log(' ' + event.target.className);
event.target.className = event.target.className.replace(' completed', '');
document.getElementById('add-item').value='';
} else {
console.log('-' + event.target.className);
event.target.className += ' completed';
}
}
function addItem() {
var list = document.querySelector('ul.todo-list');
var newItem = document.getElementById('new-item-text').value;
var newListItem = document.createElement('li');
newListItem.className = 'todo-item';
newListItem.innerHTML = newItem + '<span class="remove"></span>';
list.insertBefore(newListItem, document.querySelector('.todo-new'));
}
function removeItem(event) {
if(event.target.className.indexOf('remove') < 0) {
return;
}
var el = event.target.parentNode;
el.parentNode.removeChild(el);
}
});
This is what you need:
document.getElementById('new-item-text').value = "";
regarding your need, you will need to put it at the end of your addItem()
you can refer this simple code:
<html>
<body>
<input type="text" id="test">
<button onclick="func()">remove</button>
<br/>
Value = <span id="val"></span>
<script>
function func(){
alert("clicked");
document.getElementById('val').innerHTML = document.getElementById('test').value;
document.getElementById('test').value = '';
}
</script>
</body>
</html>
Use form reset method to clear inputs in one go.
document.getElementById("myForm").reset();
You can set your textbox value = '' in submit button.
and you can create a ClearFunction and then you can call it everytime you need it.
function cleartextbox() {
$('#name').val("").focus();
$('#selectgender').val("");
$('#telephone').val("");
}

How to execute javascript methods generated in html onlclick events

The updateValue() method isn't firing and I'm not sure how to even debug this using the browser.
function generateHtmlTableRow() {
var tr = $("<tr></tr>");
$("#results").append(tr);
var someTextData = "test";
tr.append("<td><input type=\"button\" value=\"TestButton\" onclick=\"updateValue(someTextData);\" /></td>");
}
function updateValue(newText) {
alert(newText);
}
The generated html is the problem. It cannot reference a variable in the scope of the generateHtmlTableRow function. So it will work:
function generateHtmlTableRow() {
var tr = $("<tr></tr>");
$("#results").append(tr);
var someTextData = "test";
tr.append("<td><input type=\"button\" value=\"TestButton\" onclick=\"updateValue('" + someTextData + "');\" /></td>");
}
function updateValue(newText) {
alert(newText);
}
$(document).ready(function(){
console.log('log');
generateHtmlTableRow();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="results"></div>
An elegant way to do this is to
Store the someData values in HTML5 data- attributes when you create the <tr>. jQuery has the .data() function for this purpose.
Use a delegated event handler that catches all button clicks inside the <table>. The event handler can then retrieve the data again easily.
function generateTableRow(someData) {
$("<tr><td><button class='test'>TestButton</button></td></tr>")
.data("value", someData)
.appendTo("#results");
}
$(function(){
$("#results").on("click", "button.test", function () {
var value = $(this).closest("tr").data("value");
alert(value);
});
generateTableRow("test 1");
generateTableRow("test 2");
generateTableRow("test 3");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="results"></table>

How can I address the element that called a function from within the function?

I am trying this HTML code:
<button name="darkBlue" onclick="setThemeColor(this.name)">Blue</button>
<button name="black" onclick="setThemeColor(this.name)">Black</button>
and script:
function setThemeColor(buttonName) {
localStorage.themeColor = buttonName;
document.getElementsByTagName('html')[0].className = buttonName
var themeButtons = document.querySelectorAll(".theme");
for (var button in themeButtons) {
themeButtons[button].disabled = false;
}
// this.disabled = false;
// element.setAttribute("disabled", "disabled");
}
I am having a problem here setting the disabled state of the button that called the function. Can someone tell me how i can do this. I have tried two things but neither seem to work.
Pass in a reference to your button instead of just the name:
HTML
<button name="darkBlue" onclick="setThemeColor(this)">Blue</button>
<button name="black" onclick="setThemeColor(this)">Black</button>
JS
function setThemeColor(button) {
localStorage.themeColor = button.name;
document.getElementsByTagName('html')[0].className = button.name;
var themeButtons = document.querySelectorAll(".theme");
for (var button in themeButtons) {
themeButtons[button].setAttribute("disabled", "disabled");
}
button.setAttribute("disabled", "disabled");
}
document.getElementById("buttonid1").disabled=false;

Categories

Resources