Uncaught ReferenceError: addToCart is not defined javascript - javascript

i am using javascript onclick function to make a function but it returns an error
Uncaught ReferenceError: addToCart is not defined i don't know why
here is my code
my javascript code
function addToCart(){
var productname = $('pname').text();
var productid = $('productid').text();
var color = $('#color option:selected').text();
var color = $('#size option:selected').text();
var quantity = $('#qty').val();
$.ajax({
type: "POST",
dataType: 'json',
data:{
color:color,
size:size,
quantity:quantity,
productname:productname,
},
url: "cart/data/store"+productid,
success:function(data)
console.log(data);
})
and my onclick input
<input type="submit" class="btn btn-primary" onclick="addToCart()" value="add to cart">

You did onclick="addToCart()" which immediately executed the function you should onclick="addToCart".

This is probably happening because the browser isn't properly loading your function. I would try adding a console.log above and outside of your function definition to make sure it's being loaded.
More generally, if you're using jQuery, you probably want to attach that addToCart onclick handler in Javascript rather than in HTML. See this question for more details: Add onclick event to button after document is ready with JS/JQuery selecting by class

In the case of everything is okay then what you can do is insted of onclick in html
<input type="submit" class="btn btn-primary" id="cart-btn" value="add to cart">
Script:
$(document).ready(function(){
function addToCart(){
//function definition
}
$("#cart-btn").click(addToCart);
});

I think your addToCart function is either not loading or not defined in the global scope!
Example 1 (Function defined in global scope)
function hi() {
alert("hi");
}
<button onclick="hi()">Click Me</button>
Example 2 (onClick function not defined in global scope)
(() => {
function hi() {
alert("hi");
}
})()
<button onclick="hi()">Click Me</button>

Related

Send an object by parameter to another function when I call it from a button

I'm new in Javascript and I have some problems with the order of execution.
I have a search button that when I press it, I run the Search() function. In this function I process some data, which I save in the variable 'data'. However, I want to send those data as a parameter to the other() function, but when I run the HTML, first 'other' to 'search' is executed:
<div class="btn" onclick="selected()">Select</div>
...
<script>
function selected(){
data = some stuff...
}
other(data)
<script>
How can I make the function other to run only when I type select button?
I tried to do it this way but it doesn't work as it should:
<div class="btn" onclick="selected()">Select</div>
...
<script>
function selected(){
data = some stuff...
other(data)
}
<script>
Try This
function selected(){
var data = document.getElementById("in").value;
console.log(data);
other(data);
}
function other(data1){
console.log(data1);
}
<input type="text" style="padding:10px;width:100%" value="default" id="in">
<div class="btn" style="padding:10px; background:green;color:white;" onclick="selected()">Select</div>

knockout.js click binding not calling viewmodel function

I want a function declared on my viewmodel to trigger when clicking a button. However the functions are not called when the button is clicked.
I have tried renaming the methods, callling them with parameters, but nothing triggers them. I know that knockout.js i loaded on the page since the showSmsPanel observable is working as expected.
MyJavascript.js
function AdminTilmeldingerViewModel() {
var self = this;
self.showSmsPanel = ko.observable(false); // hidden initially
self.cancelSend = function () {
console.log('cancelSend');
this.showSmsPanel(false);
}
self.sendSms = function () {
console.log('sendSms');
};
}
var vm = new AdminTilmeldingerViewModel();
ko.applyBindings(vm);
MyHtml.aspx
<div id="smsPanel" data-bind = "visible: showSmsPanel" class="row">
<input type=button class="btn btn-primary" data-bind="click: sendSms" id="btnSendSms" value="Send sms">
<input type=button class="btn btn-default" data-bind="click: cancelSend" value="Annuller">
</div>
I would expect the function to be called on clicking the buttons, but I dont see output logged to the console.

onClick not called for button (html)

My html fragmentRow is as below, which has a <a> and a
<a href="onLoadShowRoutesView?routeIdnpk=${param.routeIdnpk}">
<div class="col-md-4 pull-right">
<input type="button" class="btn btn-small btn-default btn-flat pull-right" value="${param.publishOrUnPublishValue}"
name="${param.publishOrUnPublishName}"
id="${param.publishOrUnPublishName}"
onclick="${param.publishOrUnPublishOnClick}"
data-val="${param.routeIdnpk}" style="margin-top: 6px;">
</div>
</a>
I am including fragmentRow.jsp like this
<jsp:include page="fragmentListRouteItem.jsp">
<jsp:param name="routeIdnpk"
value="${childRouteViewPojo.routeIdnpk}" />
<jsp:param name="publishOrUnPublishValue" value="Publish" />
<jsp:param name="publishOrUnPublishName" value="Publish" />
<jsp:param name="publishOrUnPublishOnClick" value="onPublish" />
</jsp:include>
And I have a ajax that is called onclick of the button
$('#unPublish').click(
function() {
var routeIdnpk = $(this).prev().val();
$.ajax({
type : "Get",
url : "unpublishRoute",
data : {
routeIdnpk : routeIdnpk
},
success : function(response) {
response = successAction(response);
},
error : function(e) {
ajaxGlobalErrorResponseWithTitleAndMessage("Unable to Unpublish",
"The unpublish operation failed, please try again");
}
});
});
When I click on the button, onLoadShowRoutesView gets called instead of $('#unPublish').click(
I have tried $('#unPublish').click( and onClick="unPublish", function unPublish() too. Still the href of <a> gets called. Is there a way to override the main div <a href> and instead call the caller of the button on click ?
I have read thru this, and other links too. But unable to find a fix for the issue.
Now I know I am missing something very basic here.
Edit 1 : I have tried
<div onclick="location.href='onLoadShowRoutesView?routeIdnpk=${param.routeIdnpk}';">
Still the onLoadShowRoutesView gets called even when I click the button
Edit 2 #zakaria-acharki : I also added
function onUnPublish () {
var routeIdnpk = $(this).prev().val();
$.ajax({
}) ;
}
function publish () {
var routeIdnpk = $(this).prev().val();
$.ajax({
}) ;
}
Yet same result
With help from #zakaria-acharki, What worked for me was the below. Some typos and 'ondblclick' with the parent div
1
$('#unPublish').click(
function() {
var routeIdnpk = $(this).val();
$.ajax({
});
$('#Publish').click(
function() {
var routeIdnpk = $(this).val();
$.ajax({
});
2
<button type="button"
class="btn btn-small btn-default btn-flat pull-right"
value="${param.routeIdnpk}"
name="${param.publishOrUnPublishName}"
id="${param.publishOrUnPublishName}" style="margin-top: 6px;">${param.publishOrUnPublishValue}</button>
3
<div
ondblclick="location.href='onLoadShowRoutesView?routeIdnpk=${param.routeIdnpk}';">
EDIT
$('#unPublish').click(
works only for the first button
$('button[name="unPublish"]').click(function(){
this worked for all the buttons
Today : I learnt the value of button[name="something"]
try edit your code a little bit like this
you can add your onclick function on your element or adding the function dynamically

Getting the value of attribute data-* in an inline function

I have a data attribute data-niq which i am using to store some data. I want to pass the data in *-niq to a function as a second parameter to a function.
This is the code
<button onClick="editevent(this.id,this.id.getAttribute('data-niq'));" id="mid" data-niq="niq" class="mr edit btn btn-success pull-right"> Edit</button>
<script>
function editevent(clicked_id,attri_bute){
console.log('clicked id',clicked_id);
console.log('data-niq',attri_bute);
}
</script>
and the link https://jsfiddle.net/codebreaker87/zob8dm4z/8/
When i run the code i get TypeError: this.id.getAttribute is not a function
How can i pass the data-niq value in the inline function that i am calling?.
Few things here
Never mix your mark up with javascript
Try to bind events in javascript end.
check the following snippet.
window.onload = function() {
var mid = document.getElementById("mid");
mid.addEventListener('click', function() {
editevent(this);
})
}
function editevent(thisObj) {
var id = thisObj.getAttribute('id');
var dataniq = thisObj.getAttribute('data-niq');
alert(id);
alert(dataniq);
}
<button id="mid" data-niq="niq" class="mr edit btn btn-success pull-right">Edit</button>
Hope it helps
you have added this.id.getAttribute('data-niq');
remove id
this.getAttribute('data-niq')

onClick and action html

I am using purecss as a base for a simple project. What I am currently having trouble with is I have a submit button where I will pull some info from the fields, and when clicked I want to run some javascript, as well as take the user to another page. This is what I am trying with no luck:
<div class="pure-controls">
<button type="submit" class="pure-button pure-button-primary" onClick="saveInfo(this.form)" action="confirm.html">Submit</button>
<button type="submit" class="pure-button pure-button-primary">Search</button>
</div>
Give your buttons IDs for simplicity, and take out that nasty inline JS.
<div class="pure-controls">
<button type="submit" class="pure-button pure-button-primary" id="button1">Submit</button>
<button type="submit" class="pure-button pure-button-primary" id="button2">Search</button>
</div>
And then with your script:
var el = document.getElementById("button1"); //cache the save button
el.addEventListener("click", function() {
document.forms[0].submit(); //submit the form or save it etc
window.location.href = "confirm.html";
}, false); //event handler
Send your form data into the function, and then use a simple redirect since only form elements have action properties. Then just add the click event, save your form however you want (submission, ajax call, doesn't matter), then either in a callback or how it is, redirect the client with window.location.href
You could have a Javascript event handler for a button press which might look something like:
document.getElementById('buttonID').onclick=function(){
//Do whatever processing you need
document.getElementById('formID').submit();
};
Alternatively, you could have an event handler in jQuery which would look something like:
$('#buttonID').on('click',function(){
// Do whatever processing you need
$('#formID').submit();
});
You can make the code inside saveInfo() redirect the user to confirm.html after you're done saving the info.
window.location = "confirm.html"
<div class="pure-controls">
<button type="submit" class="pure-button pure-button-primary" id="button1">Submit</button>
<button type="submit" class="pure-button pure-button-primary" id="button2">Search</button>
</div>
<script>
$(document).ready(function() {
$('#button1').click(function(){
var form = $(this).parents('form');
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: form.serialize(),
dataType: 'json',
success: function(response) {
window.location.href = "http://www.page-2.com";
}
});
return false;
});
});
</script>
Your form could as well do without a type submit..
Type can be a mere button.. On click, you could now do all your javascript stuff with onclick="javascript:somefunction()",
somefunction = function (){
Process javascript here
document.formname.submit();
location.href = "new.html"
}

Categories

Resources