How to pass parameters to a javascript function on onclick? - javascript

I have a script where i want to call another function on onclick by passing parameters.I want to call remove_product function .How can i achieve this?
function load_cart(){
$('.mini-cart-products').html('');
var url = $('.ajax-url').attr('href');
var t = 0;
// console.log(url);
$.ajax({
url : url,
dataType:'json',
success:function(result){
if(result.length > 0)
{
var image = $('.mini-cart-image a img');
var prod_name = $('.mini-cart-name a');
var attribute = $('.mini-cart-attributes');
var pricing = $('.mini-cart-pricing');
$.each(result, function(key, val){
var remove_url = val.remove;
var barcode = val.barcode;
var cart_id = val.cart_id;
console.log("remove_url :"+remove_url+" barcode : "+barcode+" cart_id : "+cart_id);
var productDiv = $( "<div class='mini-cart-product clearfix'></div>" );
var nameDiv = '<div class="mini-cart-name font">'+val.name+'</div>';
var attributes = $( "<div class='mini-cart-attributes'></div>" );
var colorAttr = '<div class="attribute"><span class="label">Colour: </span><span class="value">'+val.color+'</span></div>';
var sizeAttr = '<div class="attribute"><span class="label">Size&nbsp&nbsp&nbsp: </span><span class="value">'+val.size+'</span></div>';
var remove = '<div class="mini-cart-remove"><a onclick="remove_product(remove_url,barcode,cart_id)">Remove</a></div>';

The line of remove var should be something like that.
var remove = '<div class="mini-cart-remove"><a onclick="remove_product(\''+remove_url+'\',\''+barcode+'\',\''+cart_id+'\')">Remove</a></div>';
This will solve your problem
Sample fiddle

You can do with html onclick:
<button onclick="myFunction(param1, param2)">Click me</button>
or via jQuery
$(button).on('click', function() {
myFunction(param1, param2);
});

Here's the same thing as other answers but without jquery: https://jsfiddle.net/7L5ypo2r/
var testButton = document.getElementById('test-button')
testButton.onclick = function(){
//your code would go here
alert("test");
};

You should declare on the top of your javascript code a member variable.
<script>
var remove_product = null;
function yourFunction () {
remove_product = 'your_value';
}
$("#yourButton").on('click', function (event) {
alert(remove_product);
}
</script>

Related

Function unable to get called in click event of jQuery

Unable to access function named print1() in click event of jQuery and it is defined also. I have made a Calculator using jQuery and print1() function prints the value in paragraph tag
$(document).ready(function () {
var temp = 0;
var his1 = "";
var k = false;
//flag=false;
var input = "";
var prev = 0;
var count = 0;
var displayFlag = false;
var divide = true;
var firstNumber = "";
var secondNumber = "";
$(".number").click(function (e) {
var num = $(this).text();
//window.alert(num);
print1(num);
});
function print1(num) {
// code to print here
});
});
https://jsfiddle.net/w2h7zLtn/
Try this script. You need to move the print1 to outside of document ready function
Working link
$(document).ready(function(){
var temp=0;
var his1="";
var k=false;
//flag=false;
var input="";
var prev=0;
var count=0;
var displayFlag=false;
var divide = true;
var firstNumber="";
var secondNumber="";
$(".number").click(function(e){
var num= $(this).text();
//window.alert(num);
print1(num);
});
});
function print1(num)
{
alert(num);
}
I was typing onclick() command code on html page though I had click event in jQuery. Thank you for help !

Access Instagram data outside the scope in JavaScript

I just need to access my instgram data outside my the scope please help me with this. Everything is working fine for me
$(document).ready(function ()
{
var apiurl = "https://api.instagram.com/v1/users/4322593457/media/recent/?access_token=4322593457.15d3a7f.13779606843446ab834b0e8512412d4a&count=5&callback=?";
$.getJSON(apiurl, function (data) {
suatroot = data.data;
$.each(suatroot, function (key, val) {
var itemobj = val.images.low_resolution.url;
var hrefobj = val.link;
var captobj = val.caption.text;
data = captobj; //Can I access this???????
var suatpaket = "<a target='_blank' href='"+hrefobj+"'><img src='" + itemobj + "'/><br>"+captobj+"<br></a>";
$(".instagram").append(suatpaket);
});
});
});
Console.log(suatroot); //undefined here I want object
Create a function that will accept suatroot as parameter Like wise:
function suatrootCallback(suatroot){
// code to handle suatroot/data.data
}
$(document).ready(function (){
var apiurl = "https://api.instagram.com/v1/users/4322593457/media/recent/?access_token=4322593457.15d3a7f.13779606843446ab834b0e8512412d4a&count=5&callback=?";
$.getJSON(apiurl, function (data) {
var suatroot = data.data; // do not create global variable
suatrootCallback(suatroot); // call the callback
$.each(suatroot, function (key, val) {
var itemobj = val.images.low_resolution.url;
var hrefobj = val.link;
var captobj = val.caption.text;
data = captobj; //Can I access this???????
var suatpaket = "<a target='_blank' href='"+hrefobj+"'><img src='" + itemobj + "'/><br>"+captobj+"<br></a>";
$(".instagram").append(suatpaket);
});
});
});
You can access the instagram data only after being initalized, so better you can call a function after the response.
$(document).ready(function () {
var apiurl = "https://api.instagram.com/v1/users/4322593457/media/recent/?access_token=4322593457.15d3a7f.13779606843446ab834b0e8512412d4a&count=5&callback=?";
$.getJSON(apiurl, function (data) {
suatroot = data.data;
$.each(suatroot, function (key, val) {
var itemobj = val.images.low_resolution.url;
var hrefobj = val.link;
var captobj = val.caption.text;
data = captobj;
callbackInstagram(data); //accessed here
//window.data = data also if you want to access if globally after initailized
var suatpaket = "<a target='_blank' href='"+hrefobj+"'><img src='" + itemobj + "'/><br>"+captobj+"<br></a>";
$(".instagram").append(suatpaket);
});
});
});
function callbackInstagram (data) {
console.log(data);
}
Hope that helps! Thanks

Replace var with some new var jquery

I have code to find something from database and output it back if it exists.
Now when I output it back I need to make on click one of those outputs replace that output as var in some other var.
$(document).ready(function() {
$('#display').hide();
$("#leavepost").keypress(function(event) {
var key = (event.keyCode ? event.keyCode : event.which);
if (key == 35) {
$('#display').show();
$('#leavepost').on('keyup', function() {
var matches = $(this).val().match(/(^|\s)(#[a-z\d-]+)/ig)[0];
var name = matches;
$.ajax({
type: "POST",
url: "d/sul.php",
data: {
su: name
},
success: function(sss) {
$('#display').html(sss);
$(".adduser").click(function() {
var username = $(this).text();
var a = username;
var username2 = $(this).attr('id');
var E = "<a class='red' contenteditable='false' href='#' >" + a + "</a>";
var content = name.replace(name, E);
$("#leavepost").html(content);
$("#display").hide();
$("#leavepost").focus();
});
}
});
}).keyup();
}
});
});
When I click on class div hides but before that nothings happend... I need to replace #word from var name witdh var E.
Thanks
Your problem is most likely because you used .html() in on a <textarea> as stated in the discussion.
https://jsfiddle.net/q9gwdLj5/
$(function(){
$("#choices li").click(function(){
var name = $(this).text();
$("#ta").val($("#ta").val().replace("#thisperson", name));
})
})
Changing the .html() bit with .val() will fix the problem.

Javascript AJAX scope inside of $.each Scope

So I am trying to loop through some elements and change some text based on the result of an ajax call. the problem is I cannot get the data out of the ajax callback and I am not sure how exactly to chain the events to do so. I am getting a stock quote value it would be nice if I could just return that object up into the previous scope, the loop of matches, and then do all the manipulation there.
$(function(){
var tweets = $('.tweet');
var symbol_pat = /(^|\s\$)([a-z]+\b)/gi;
$.each(tweets, function(){
var tweet_html = $(this).html();
tweet_html = tweet_html.replace(symbol_pat,function(){
var symbol = arguments[2];
var YAHOO_API_URL = 'http://query.yahooapis.com/v1/public/yql'
var format = 'json'
var query = 'select * from yahoo.finance.quotes where symbol in ("'+symbol+'")';
var env = "store://datatables.org/alltableswithkeys";
$.ajax({
'url':YAHOO_API_URL,
'async':false,
'method':'GET',
'data': {
'format':format,
'q':query,
'env':env
},
success: function(data){
var quote = data.query.results.quote;
var change = quote.Change;
var change_pct = quote.ChangeinPercent;
var quote_price = quote.LastTradePriceOnly;
var html_str = "";
if( change.indexOf("+") != -1 ){
html_str = '<span class="symWrap up">'+arguments[0]+'</span>';
}else{
html_str = '<span class="symWrap down">'+arguments[0]+'</span>';
}
tweet_html = arguments[0].replace(html_str);
$(this).html(tweet_html);
}
});
});
});
});
$.ajax() runs asynchronously, so you can't really "wait" for the success in the previous scope. You can use jQuery promise and Deferred to do this though. Check out http://www.erichynds.com/jquery/using-deferreds-in-jquery/ and http://joseoncode.com/2011/09/26/a-walkthrough-jquery-deferred-and-promise/
EDIT:
showing an alternate solution that doesn't require promise or deferred:
$(function(){
var tweets = $('.tweet');
var symbol_pat = /(^|\s\$)([a-z]+\b)/gi;
$.each(tweets, function(){
var that = this;
var symbol = arguments[2];
var YAHOO_API_URL = 'http://query.yahooapis.com/v1/public/yql'
var format = 'json'
var query = 'select * from yahoo.finance.quotes where symbol in ("'+symbol+'")';
var env = "store://datatables.org/alltableswithkeys";
$.ajax({
'url':YAHOO_API_URL,
'async':false,
'method':'GET',
'data': {
'format':format,
'q':query,
'env':env
},
success: function(data){
var quote = data.query.results.quote;
var change = quote.Change;
var change_pct = quote.ChangeinPercent;
var quote_price = quote.LastTradePriceOnly;
var html_str = "";
if( change.indexOf("+") != -1 ){
html_str = '<span class="symWrap up">'+arguments[0]+'</span>';
}else{
html_str = '<span class="symWrap down">'+arguments[0]+'</span>';
}
var tweet_html = $(that).html();
var tweet_html = arguments[0].replace(html_str);
tweet_html = tweet_html.replace(symbol_pat,html_str);
$(that).html(tweet_html);
}
});
});
});
});
so long as your replace code is correct, I believe the following rework of your code should work (or at least get you darn close, as this is untested and depends on the rest of your code):
$(function(){
var YAHOO_API_URL = 'http://query.yahooapis.com/v1/public/yql'
var tweets = $('.tweet');
var symbol_pat = /(^|\s\$)([a-z]+\b)/gi;
$.each(tweets, function(){
var tweet_html = $(this).html();
tweet_html = tweet_html.replace(symbol_pat, function(){
var symbol = arguments[2];
var format = 'json'
var query = 'select * from yahoo.finance.quotes where symbol in ("'+symbol+'")';
var env = "store://datatables.org/alltableswithkeys";
var quoteHtml = getQuote(format, query, env, function(quote) {
var change = quote.Change;
var change_pct = quote.ChangeinPercent;
var quote_price = quote.LastTradePriceOnly;
var html_str = "";
if( change.indexOf("+") != -1 ){
html_str = '<span class="symWrap up">'+arguments[0]+'</span>';
}
else{
html_str = '<span class="symWrap down">'+arguments[0]+'</span>';
}
return arguments[0].replace(html_str);
});
return quoteHtml;
});
$(this).html(tweet_html);
});
var getQuote = function(format, query, env, successCallback) {
$.ajax({
'url':YAHOO_API_URL,
'async':false,
'method':'GET',
'data': {
'format': format,
'q': query,
'env': env
},
success: function(data){
var quote = data.query.results.quote;
if(successCallback !== undefined && typeof successCallback == 'function') {
successCallback(quote);
}
}
});
};
});

JQuery with several Elements issue

i got an anchor in the DOM and the following code replaces it with a fancy button. This works well but if i want more buttons it crashes. Can I do it without a for-loop?
$(document).ready(buttonize);
function buttonize(){
//alert(buttonAmount);
//Lookup for the classes
var button = $('a.makeabutton');
var buttonContent = button.text();
var buttonStyle = button.attr('class');
var link = button.attr('href');
var linkTarget = button.attr('target');
var toSearchFor = 'makeabutton';
var toReplaceWith = 'buttonize';
var searchButtonStyle = buttonStyle.search(toSearchFor);
if (searchButtonStyle != -1) {
//When class 'makeabutton' is found in string, build the new classname
newButtonStyle = buttonStyle.replace(toSearchFor, toReplaceWith);
button.replaceWith('<span class="'+newButtonStyle
+'"><span class="left"></span><span class="body">'
+buttonContent+'</span><span class="right"></span></span>');
$('.buttonize').click(function(e){
if (linkTarget == '_blank') {
window.open(link);
}
else window.location = link;
});
}
}
Use the each method because you are fetching a collection of elements (even if its just one)
var button = $('a.makeabutton');
button.each(function () {
var btn = $(this);
var buttonContent = btn.text();
var buttonStyle = btn.attr('class');
var link = btn.attr('href');
var linkTarget = btn.attr('target');
var toSearchFor = 'makeabutton';
var toReplaceWith = 'buttonize';
var searchButtonStyle = buttonStyle.search(toSearchFor);
...
};
the each method loops through all the elements that were retrieved, and you can use the this keyword to refer to the current element in the loop
var button = $('a.makeabutton');
This code returns a jQuery object which contains all the matching anchors. You need to loop through them using .each:
$(document).ready(buttonize);
function buttonize() {
//alert(buttonAmount);
//Lookup for the classes
var $buttons = $('a.makeabutton');
$buttons.each(function() {
var button = $(this);
var buttonContent = button.text();
var buttonStyle = button.attr('class');
var link = button.attr('href');
var linkTarget = button.attr('target');
var toSearchFor = 'makeabutton';
var toReplaceWith = 'buttonize';
var searchButtonStyle = buttonStyle.search(toSearchFor);
if (searchButtonStyle != -1) {
newButtonStyle = buttonStyle.replace(toSearchFor, toReplaceWith);
button.replaceWith('<span class="'
+ newButtonStyle
+ '"><span class="left"></span><span class="body">'
+ buttonContent
+ '</span><span class="right"></span></span>');
$('.buttonize').click(function(e) {
if (linkTarget == '_blank') {
window.open(link);
} else window.location = link;
}); // end click
} // end if
}); // end each
}

Categories