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>
Related
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);
}
}
})
what i'm trying to do is call a funcation like below, further i want to pass current element (item) to function as parameter.
<tr rv-each-item="items:models">
<td>{ item:Name }</td>
</tr>
var selectedItem = function (item)
{
console.log(item);
}
while searching around i found below discussion helpful but could not solve my problem as it does not implement backbone
https://github.com/mikeric/rivets/issues/554
Rivets.js: When button is clicked, call a function with an argument from a data binding
While working around i found different approaches that can help, posting here if someone can get help or improve if there is any thing needs to.
Option 1
<body>
<div rv-each-book="model.books">
<button rv-on-click="model.selectedBook | args book">
Read the book {book}
</button>
</div>
</body>
<script type="text/javascript">
rivets.formatters["args"] = function (fn) {
var args = Array.prototype.slice.call(arguments, 1);
return function () {
return fn.apply(null, args);
};
};
rvBinder = rivets.bind(document.body, {
model: {
selectedBook: function (book) {
alert("Selected book is " + book);
},
books: ["Asp.Net", "Javascript"]
}
});
</script>
Option 2
Create a custom binder
<body>
<div rv-each-book="books">
<a rv-cust-href="book">
Read the book {book}
</a>
</div>
</body>
<script type="text/javascript">
rivets.binders['cust-href'] = function (el, value) {
//el.href = '/Books/Find/' + value;
//OR
el.onclick = function() { alert(value);};
}
rvBinder = rivets.bind(document.body, {
books: ["Asp.Net", "Javascript"]
});
</script>
Option 3
As I was using rivetsjs with backbone, i can also get advantage of events on backbone view
// backbone view
events: {
'click #linkid': 'linkclicked'
},
linkclicked: function (e){
console.log(this.model.get("Name"));
},
<td><a id="linkid" href="#">{ item:Name }</a></td>
I have a codemirror editor in a partial view and a list of files in the main view. I want to refresh the editor once a file name is clicked. I tried many solutions provided on StackOverflow and other websites but nothing worked , and This is my first time using Javascript so I can't figure out What am I doing wrong.
This is my code:
Controller:
public ActionResult Index()
{
StudentsCodes model = new StudentsCodes();
model.Student = (Student)CurrentUser;
var user = UserManager.FindById(((Student)CurrentUser).InstructorID);
model.Instructor =(Instructor) user;
return View(model);
}
public PartialViewResult DevelopmentPartial (StudentsCodes path )
{
return PartialView(path);
}
Main view:
<script type="text/javascript" src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script type="text/javascript" src="~/Scripts/jquery-3.1.1.js"></script>
<ul id="tree">
#foreach (var file in Directory.GetFiles(Server.MapPath("~/Content/" + Model.Student.UserName + "/CompilerProject/" + name)))
{
var filename = Path.GetFileName(file);
<li id="filelist" onclick="#(Model.path = "~/Content/" + Model.Student.UserName + "/CompilerProject/src/" + #filename)">
<span class="glyphicon glyphicon-file"></span>
#filename
/li>
}
<div id="partial">
#{
Html.RenderPartial("DevelopmentPartial",null);
}
</div>
<script>
$(document).ready(function () {
$("#filelist").click(function (e) {
#{Html.RenderAction("DevelopmentPartial", Model);
}
});
});
</script>
partial view:
#using (Html.BeginForm())
{
var fileContents= "";
if (Model==null)
{
fileContents = "";
}
else
{
fileContents = System.IO.File.ReadAllText(Server.MapPath(Model.path));
}
#Html.TextArea("code", fileContents, new { id = "code" })
}
I can't assign ids for list elements since their number is unknown at compile time and it changes when the user adds or deletes a file, that's why most of the solutions provided didn't work . The result here was 3 editors overlapping and display the contents of the last file. And <li> items are non-clickable. What am I doing wrong in my code ?
Edit:
After updating the script as the following:
<script>
$(document).ready(function() {
$(".filelist").on("click",function (e) {
$("#partial").load('DevelopmentPartial');
});
});
</script>
It refreshes the partial view but the editor is always empty, and the Model is always null. Is it wrong to update the Model using "onclick"?
In case someone faced the same problem, I solved it by changing id to class at the list, then by using this script:
<div id="partial">
#{
Html.RenderAction("DevelopmentPartial", new { path1 = Model.path});
}
</div>
<script>
$(document).ready(function () {
$('.filelist').on('click', function (e) {
alert('Im clicked on filePath = ' + $(this).attr('value'));
var filePath = $(this).attr('value'); //value is attribute set in Html
$('#partial').load('DevelopmentPartial', { path1: filePath });
});
});
</script>
And the controller:
public PartialViewResult DevelopmentPartial(string path1)
{
modelSC.path = path1;
return PartialView(modelSC);
}
where modelSC is a global variable in the controller.
I am trying to call a JavaScript function from the onclick event of two different buttons. I have dug around and searched for like problems but have not found a solutions. When I click either button I get the error
Error: 'RemoveCode' is undefined'
What am I doing wrong?
<script type="text/javascript">
$(document).ready(function ()
{
function RemoveCode(codeType)
{
var selectedProjectsField = $("#SelectedProjects");
var selectedProjectCodesField = $("#SelectedProjectCodes");
var selectedTasksField = $("#SelectedTasks");
var selectedTaskCodesField = $("#SelectedTaskCodes");
var selectedOption;
if (codeType = "Project")
{
selectedOption = $("#SelectedProjects :selected").index();
}
else
{
selectedOption = $("#SelectedTasks :selected").index();
}
alert(selectedOption);
}
});
</script>
Code for my buttons:
<li>
<label for="SelectedProjects">Selected Projects:</label>
<select size="1" id="SelectedProjects" name="SelectedProjects" multiple></select> <button class="removeButton" onclick="RemoveCode('Project')" type="button">-</button>
</li>
<li>
<label for="SelectedTasks">Selected Tasks:</label>
<select size="1" multiple id="SelectedTasks" name="SelectedTasks"></select> <button class="removeButton" onclick="RemoveCode('Task')" type="button">-</button>
</li>
I should note that on the same page there are multiple change events for the other elements on the page and they all work fine. It is just this `onclickP that is failing.
Firstly note that in your if condition you need to use == (not =) to compare values.
To solve your issue you have two options. Firstly you could simply move the RemoveCode function out of the scope of the document.ready handler so that it can be accessed from the onclick attribute:
<script type="text/javascript">
function RemoveCode(codeType)
{
// your code...
}
$(document).ready(function ()
{
// your code...
});
</script>
Alternatively, it would be much better practice to add your event handlers using unobtrusive Javascript. As you're using jQuery, here's how you can do that:
$(function() {
$('button').click(function() {
var $selectedProjectsField = $("#SelectedProjects");
var $selectedProjectCodesField = $("#SelectedProjectCodes");
var $selectedTasksField = $("#SelectedTasks");
var $selectedTaskCodesField = $("#SelectedTaskCodes");
var selectedOption;
if ($(this).data('codetype') == "Project") {
selectedOption = $selectedProjectsField.find(':selected').index();
} else {
selectedOption = $selectedTasksField.find(':selected').index();
}
alert(selectedOption);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>
<label for="SelectedProjects">Selected Projects:</label>
<select size="1" id="SelectedProjects" name="SelectedProjects" multiple></select>
<button class="removeButton" data-codetype="Project" type="button">-</button>
</li>
<li>
<label for="SelectedTasks">Selected Tasks:</label>
<select size="1" multiple id="SelectedTasks" name="SelectedTasks"></select>
<button class="removeButton" data-codetype="Task" type="button">-</button>
</li>
</ul>
You are defining your RemoveCode method inside a closure. This function will thus not be available as onclick callbacks of your HTML elements.
You can just update your code to this and it should work:
<script type="text/javascript">
function RemoveCode(codeType)
{
var selectedProjectsField = $("#SelectedProjects");
var selectedProjectCodesField = $("#SelectedProjectCodes");
var selectedTasksField = $("#SelectedTasks");
var selectedTaskCodesField = $("#SelectedTaskCodes");
var selectedOption;
if (codeType = "Project")
{
selectedOption = $("#SelectedProjects :selected").index();
}
else
{
selectedOption = $("#SelectedTasks :selected").index();
}
alert(selectedOption);
}
</script>
put your function out side of document.ready()
<script type="text/javascript">
$(document).ready(function () // No Need of this Function here
{ });
function RemoveCode(codeType) // Automatically load when Your page is getting loaded on Browser.
{
var selectedProjectsField = $("#SelectedProjects");
var selectedProjectCodesField = $("#SelectedProjectCodes");
var selectedTasksField = $("#SelectedTasks");
var selectedTaskCodesField = $("#SelectedTaskCodes");
var selectedOption;
if (codeType = "Project")
{
selectedOption = $("#SelectedProjects :selected").index();
}
else
{
selectedOption = $("#SelectedTasks :selected").index();
}
alert(selectedOption);
}
</script>
You are defining your ready() method inside of a closure.
You then have two approaches you can use. First is you can not use $(document).ready() as the buttons that call ready() can't be clicked until the document is ready anyway.
Second is you could bind the onclick inside of your $(document).ready().
$(document).ready(function() {
$('#firstItem').click(function() { Ready('Project'); });
....
});
My website has tabs and within that tab, info cards and a checkbox on the right hand side that highlights the card in a different colour. How can I makes it so that onclick the highlighting is saved even if the page is refreshed or if the page is sent as a link? Full code here: http://codepen.io/johnsonshara/pen/obGjGN (below code not in code pen version)
What I have tried:
function save () {
var fieldValue = document.getElementById('like').value;
localStorage.setItem('checkbox', 'fieldValue');
}
function load () {
var storedValue = localStorage.getItem('checkbox');
if(storedValue){
document.getElementById('like').value = storedValue;
}
}
And This:
function save() {
if(typeof(Storage) !== "undefined") {
if (localStorage.setItem) {
localStorage.setItem = document.getElementById("like");
} else {
localStorage.getItem = .hasClass.apply;
}
document.getElementById("like").innerHTML = localStorage.toString;
} else {
document.getElementById("like").innerHTML = "Sorry, an error occured.";
}
}
html
<input type="checkbox" class="faChkRnd" onclick="save()" id="like" >
Check out the following link to see how you can use the local storage:
http://www.w3schools.com/html/html5_webstorage.asp
Quick example code of how it would work:
// Put the object into storage
localStorage.setItem('testObject', "testing");
// Retrieve the object from storage
var retrievedObject = localStorage.getItem('testObject');
Example using your example code above:
alert(load());
$(document).on("click", "#clickME", function(){
save();
});
function save ()
{
var fieldValue = "testString";
localStorage.setItem('checkbox', fieldValue);
}
function load ()
{
var storedValue = localStorage.getItem('checkbox');
if(storedValue)
{
console.log("VALUE :" + localStorage.getItem('checkbox'));
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="clickME">Click me</button>
or if the page is sent as a link
You should store your data as a url parameter not in the local storage. So anyone that click on the link will get the data.
See this link to know more about using url parameters with JS:
How to get the value from the GET parameters?