Javascript jquery Help w/ for loop buttons - javascript

I have problem with my code.I'm building a spotify app for school using the spotify WEB Api. My problem is that I have a function that will use a for loop to output data in a table and also create buttons with individual ids like=
<button value="5BJeN4SVEKe204y2SiszOe" id="btn_0">Lorem</button>
<button value="0xmaV6EtJ4M3ebZUPRnhyb" id="btn_1">Lorem</button>
<button value="0rSLgV8p5FzfnqlEk4GzxE" id="btn_2">Lorem</button>
<button value="0esxMkxlIDKbkWL8Vuj35V" id="btn_3">Lorem</button>
and so on. Every button also has a value which represents an albums id. I then transformed these buttons to an array using .toArray so i could get the value i need for every single button. Is it possible to make a function in a way that when i press btn_0 it will get the value of btn_0 and then output it to the console?And then the function would do it for every button. I tried doing one but it just outputs the data from every value like here:
$(document).on('click', '.Abuttons', function(e) {
var array = $("button").toArray();
for (var i=0; i < array.length; i++) {
$.ajax({url: "https://api.spotify.com/v1/albums/"+ array[i].value +"/tracks", success: function(result) {
console.log(result);
}});
}
});
I know i have the class .Abuttons there but i tried to make a for loop before it so it would call every single button, but it didnt work. Hope you understand, and thx for all the help.
P.s My first time here so i couldnt get the formatting to work on my jquery code.

ajax success is callback method but when you are using for loop after one loop it won't wait for the first ajax callback to fire ! it goes for second loop and so on
one solution for this is to declare a variable i for counting above all then create a function for ajax call , in success callback you count requests if variable i is smaller than number of for loop you call that function again while reach to loop !

If I understand what you're asking, you don't need to build an array at all. Instead you can read the value of the clicked button within its own event handler. You can then include that value in the URL you call via AJAX to get the information, something like this:
$(document).on('click', 'button', function(e) {
$.ajax({
url: "https://api.spotify.com/v1/albums/" + this.value + "/tracks",
success: function(result) {
console.log(result);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button value="5BJeN4SVEKe204y2SiszOe" id="btn_0">Lorem</button>
<button value="0xmaV6EtJ4M3ebZUPRnhyb" id="btn_1">Lorem</button>
<button value="0rSLgV8p5FzfnqlEk4GzxE" id="btn_2">Lorem</button>
<button value="0esxMkxlIDKbkWL8Vuj35V" id="btn_3">Lorem</button>

Your buttons are probably wrapped in an element. Something like,
<div class="my-buttoms">
<button value="..."></button>
</div>
Thus, you can bind a click event in this div and get a click target.
$('.my-buttons').on('click', (e) => console.log(e.target.value))
$('.w').on('click', function(e) {
if (e.target.tagName === 'BUTTON') {
alert(e.target.value);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="w">
<button value="1">1</button>
<button value="2">2</button>
</div>

You can use jQuery $(this) to get the event target value of the value attribute:
$('[id^=btn_]').on('click', function(e) {
$.ajax({
url: "https://api.spotify.com/v1/albums/" + $(this).attr("value") + "/tracks",
success: function(result) {
console.log(result);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button value="5BJeN4SVEKe204y2SiszOe" id="btn_0">Lorem</button>
<button value="0xmaV6EtJ4M3ebZUPRnhyb" id="btn_1">Lorem</button>
<button value="0rSLgV8p5FzfnqlEk4GzxE" id="btn_2">Lorem</button>
<button value="0esxMkxlIDKbkWL8Vuj35V" id="btn_3">Lorem</button>

So, I feel like you may be overcomplicating it:
https://jsfiddle.net/bashaen/vewae2t7/3/
$('button'); in JQuery already returns back an array of all elements it's targeted.
var arr = $("button");
// Actually Contains - [button, button, button, button]
$.each will filter through the buttons much like the for loop, but there are different benefits.
$.each(arr, function(i, e) { // i = index, e = element
console.log( $(e).val() );
// or if you're more comfortable with it.
console.log( $(this).val() );
});
Also, do both a .success() and a .fail(), to see if your ajax is actually going through.

Related

Click Function using AJAX Jquery Javascript

I am making a movie review web site as a project for school, and I want to put a click function on the image movie cover which will load the details and reviews of that movie. The code I'm using works but does not seem practical. The parameter in my loadReviews function is the movie ID for the database.
$(document).ready(function () {
$("#cover1").click(function () { loadReviews(1); });
$("#cover2").click(function () { loadReviews(2); });
$("#cover3").click(function () { loadReviews(3); });
$("#cover4").click(function () { loadReviews(4); });
$("#cover5").click(function () { loadReviews(5); });
$("#cover6").click(function () { loadReviews(6); });
$("#cover7").click(function () { loadReviews(7); });
$("#cover8").click(function () { loadReviews(8); });
$("#cover9").click(function () { loadReviews(9); });
$("#cover10").click(function () { loadReviews(10); });
$("#cover11").click(function () { loadReviews(11); });
$("#cover12").click(function () { loadReviews(12); });
});
As you can see I am writing each one manually. I tried using a for loop like this but does not work the way I thought.
for (i = 1; i < 12; i++) {
$("#cover" + i).click(function () { loadReviews(i); });
}
Using the loop it makes each image load the details of the same (#12) movie. Each image is assigned the class 'cover1', 'cover2' etc. I want some sort of 'loop' to automatically bind each click event to the correct image cover. I'm using a generic handler in Visual Studio 15. We must use ajax and jquery to update the page without a postback, this is how I am getting the movies and reviews.
If I need to show more code let me know. Thanks!
You could get away with having just one click handler and store the identifier as a data attribute. So your repeated HTML element might be something like this:
<div class="cover" data-movieid="1">
...
</div>
<div class="cover" data-movieid="2">
...
</div>
etc.
Then assign a single click handler and within that handler get the identifier from the element which was clicked. Something like this:
$(document).ready(function () {
$('.cover').click(function () {
var movieID = $(this).data('movieid');
loadReviews(movieID);
});
});
Depending on what loadReviews() does, you can probably make the whole thing simpler. Instead of giving everything ids and only using those in your selectors, from any given clicked element you can use jQuery to query the DOM and find the relative element you need without using an id.
If the HTML can't be changed
$("[id^=cover]").click(function () {
var rev = parseInt(this.id.replace(/\D+/g, ''));
loadReviews(rev);
});
Instead of using IDs for each cover I would recommend using a "cover" class and a data parameter with the id.
<div class"cover" data-movieid="1"></div>
and the js code would look like:
$(document).ready(function () {
$(".cover").click(function () { loadReviews($(this).data('movieid')); });
});
Using the loop it makes each image load the details of the same (#12) movie.
This happens because when the loop ends the value of the variable is always the last while the event will happen in future.
Two ways to solve it (Immediately-invoked function expression):
function loadReviews(i) {
console.log(i);
}
for (i = 1; i < 5; i++) {
(function(i) {
$("#cover" + i).on('click', function (e) {
loadReviews(i);
});
}(i));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="cover1">Cover 1</button>
<button id="cover2">Cover 2</button>
<button id="cover3">Cover 3</button>
<button id="cover4">Cover 4</button>
<button id="cover5">Cover 5</button>
The second way is based on the id (i.e: get the last part id: remove the cover string):
function loadReviews(i) {
console.log(i);
}
for (i = 1; i < 5; i++) {
$("#cover" + i).click(function () {
loadReviews(this.id.replace('cover', ''));
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="cover1">Cover 1</button>
<button id="cover2">Cover 2</button>
<button id="cover3">Cover 3</button>
<button id="cover4">Cover 4</button>
<button id="cover5">Cover 5</button>
You are facing the typical "callback inside look" context problem.
Let's check the code.
Having this:
$("#cover1").click(function () {
loadReviews(1);
});
Means that the code inside the function will be run only when the click event occurs, and not when the event is attached, so the runtime will go this way:
// First, attaches the event
$("#cover1").click(function () {
// This will be run when user clicks, so will be called last
loadReviews(1);
});
// The runtime will continue right BEFORE the click callback is run
So in your loop the runtime will go this way:
for (i = 1; i < 12; i++) {
// var i value starts from 0. And attaches the click event
$("#cover" + i).click(function () {
// Runs after all the loop is done (when the i value is 12)
loadReviews(i);
});
// loop continue BEFORE the content of the click callback is run
}
One fast way to fix your loop is to call a function with the variable declared inside the function, so it will be never changed by external actions.
function attachClick(id) {
// This will be run on each loop, creating a id variable
// that will be unique for this context
$("#cover" + id).click(function () { loadReviews(id); });
}
for (i = 1; i < 12; i++) {
// Call the function passing the i variable as parameter
attachClick(i);
}
And the way that you will se a lot around there is by creating anonymous functions (does exactly the same as above but without creating a named function elsewhere):
for (i = 1; i < 12; i++) {
(function(id) {
$("#cover" + id).click(function () {
loadReviews(id);
});
})(i);
}
Those are the fastest ways of modifying your code to have a working one, but when working with events that way, the best is to attach only one event to the parent, capture the element clicked and get the id from there. The less events attached, the faster is everything.
function loadReviews(i) {
console.log(i);
}
for (i = 1; i < 5; i++) {
(function(i) {
$("#cover" + i).on('click', function (e) {
loadReviews(i);
});
}(i));
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn btn-primary" id="cover1">Cover Primary</button>
<button class="btn btn-success" id="cover2">Cover Success</button>
<button class="btn btn-danger" id="cover3">Cover Danger</button>
<button class="btn btn-warning" id="cover4">Cover Warning</button>
<button class="btn btn-info" id="cover5">Cover Info</button>

Find value of multiple buttons with javascript

I need to have multiple buttons on page (created through a PHP loop) - there's not fixed number of buttons as there'll be one for each record displayed. I'd like to get the value of that button with javascript when it is clicked.
So far the html looks like:
<button id="update[0]" value="test">Update</button>
<button id="update[1]" value="test">Update</button>
<button id="update[2]" value="test">Update</button>
etc....
and my script is:
$(document).ready("#update").click(function() {
var updateId = $("#update").val
alert(updateId);
});
So far the script detects when any #update[] button is clicked but how do I know the index of the particular button in order to get the value (i.e. if #update[38] is clicked how do I know it's #update[38] so I can find the value of that particular button?
Thanks.
You do not want to chain off the document ready like you are as its returning the document.
$(document).ready("#update").click(function() {
So you are capturing the document.click not not button.click so when you reference $(this).val() you will get document.value which does not exist.
Should be:
$(document).ready(function () {
$("button").click(function () {
//no reason to create a jQuery object just use this.value
var updateId = this.value;
alert(updateId);
});
});
http://jsfiddle.net/SeanWessell/2Lf6c3fx/
Use the "this" key word.
$(document).ready("#update").click(function() {
var updateId = $(this).val();
alert(updateId);
});
The this keyword in javascript allows you to reference the particular instance of the object you are interacting with.
Also, add "()" to the end of val.
I believe you meant to use
var updateId = $("#update").val()
With jQuery you can use $(this).val()
You could also get the text of the button using .text()
With pure Javascript you could use .value if the button has a value attribute
See this: Javascript Get Element Value
I would suggest the following
<button id="0" class="updatebutton" value="test">Update</button>
<button id="1" class="updatebutton" value="test">Update</button>
<button id="2" class="updatebutton" value="test">Update</button>
Use a class to apply your click function.
$(document).ready(function () {
$("updatebutton").click(function () {
var updateId = this.id;
alert(updateId);
});
});
And use the id to specify the index of the button.
The trick is to give all your buttons the same class and then use $(this) to find out which button was clicked.
Once you know the button, then you can check for any of its attributes like id, value or name.
$(function() {
$(".xx").on("click", function(evt) {
var clicked_button = $(this);
alert(clicked_button.attr("value"));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="update_1" class="xx" value="test1">Button 1</button>
<button id="update_2" class="xx" value="test2">Button 2</button>
<button id="update_3" class="xx" value="test3">Button 3</button>
Hi there a few things wrong with your javascript there.
You are attaching onClick to the document! The function ready returns the document.
Wrong:
$(document).ready("#update").click(function() {
Right:
$(document).ready(function () { $(valid_selector).click...
You are attempting to refetch the button with $('#update'), which 1 doesn't fetch anything, and two if it did would return all of the buttons. So use $(this) in the scope of the click function instead to refer to the button clicked.
Here is your javascript corrected:
https://jsfiddle.net/ffkekpmh/
//When the document is ready call this function
$(document).ready(function () {
//Select all buttons whoes id starts with update
//https://api.jquery.com/category/selectors/attribute-selectors/
$('button[id^="update"]').click(function() {
//Store the id attribute from the clicked button
var updateId = $(this).attr("id");
//Store the value attribute from the clicked button
var value = $(this).attr("value");
alert("You clicked button:"+updateId+" with value: "+value);
});
});

Bypass onclick event and after excuting some code resume onclick

I have the below html button which have onclick event
<button onclick="alert('button');" type="button">Button</button>
and the following js:
$('button').on('click', function(){
alert('jquery');
});
After executing some js code by jQuery/Javascript, i want to continue with the button onclick handler e.g: jquery alert first and than button alert.
i tried so many things like "remove attr and append it after executing my code and trigger click (it stuck in loop, we know why :) )" and "off" click. but no luck.
is it possible via jQuery/javascript?
any suggestion much appreciated
Thanks
A little bit tricky. http://jsfiddle.net/tarabyte/t4eAL/
$(function() {
var button = $('#button'),
onclick = button.attr('onclick'); //get onclick value;
onclick = new Function(onclick); //manually convert it to a function (unsafe)
button.attr('onclick', null); //clear onclick
button.click(function() { //bind your own handler
alert('jquery');
onclick.call(this); //call original function
})
});
Though there is a better way to pass params. You can use data attributes.
<button data-param="<%= paramValue %>"...
You can do it this way:
http://jsfiddle.net/8a2FE/
<button type="button" data-jspval="anything">Button</button>
$('button').on('click', function () {
var $this = $(this), //store this so we only need to get it once
dataVal = $this.data('jspval'); //get the value from the data attribute
//this bit will fire from the second click and each additional click
if ($this.hasClass('fired')) {
alert('jquery'+ dataVal);
}
//this will fire on the first click only
else {
alert('button');
$this.addClass('fired'); //this is what will add the class to stop this bit running again
}
});
Create a separate javascript function that contains what you want to do when the button is clicked (i.e. removing the onclick attribute and adding replacement code in its own function).
Then call that function at the end of
$('button').on('click', function(){
alert('jquery');
});
So you'll be left with something like this
function buttonFunction()
{
//Do stuff here
}
$('button').on('click', function()
{
alert('jquery');
buttonFunction();
});
<button type="button">Button</button>

Changing what function to call depending on which button is pressed

Okay So I what to have 3 buttons
<div id="button1" onclick="choose1()">Button1</div>
<div id="button2" onclick="choose2()">Button2</div>
<div id="button3" onclick="choose3()">Button3</div>
And a start button
<div id="startButton" onclick="noFunction()">Start</div>
I want to make it so that pressing on of the 3 option buttons it changes what function will be called from the start button and the background image of the start button should change.
Is there a way to do this with just javascript or do I need jquery?
It also doesn't seem possible to use onclick on div tags, jquery to do that aswell?
jsFiddle
You can use onclick on <div> tags. But you shouldn't use onclick on any tags. Don't confuse your HTML layout and display with your JavaScript functionality. Bind your click handlers directly in the JS code (note that this solution is using jQuery):
HTML:
<div id="button1">Button1</div>
<div id="button2">Button2</div>
<div id="button3">Button3</div>
<div id="startButton">Start</div>
JS:
function choose1() {
// ...
}
function choose2() {
// ...
}
function choose3() {
// ...
}
$(function() {
$("#button1").click(choose1);
$("#button2").click(choose2);
$("#button3").click(choose3);
});
You can do it in javascript (anything possible with jQuery is possible with plain javascript, since jQuery is written in javascript).
Changing the click handler for the startButton from javascript is very straightforward:
document.getElementById("startButton").onclick = newFunction;
Changing the background image is also pretty simple:
document.getElementById("startButton").style.backgroundImage = "image.png";
Obviously, you should replace newFunction and "image.png" with the function and image you actually want to use respectively.
You can say
function choose1() {
document.getElementById('startButton').onclick = function() {
alert("Button one was originally press");
}
}
jQuery IS javascript. It is just a library of functions/methods that you can call.
To solve your problem, you should write a function that changes the onclick property of your start button, and add the function you write to the onclick of the other buttons.
Like so:
function chooseOne(){
document.getElementById('startButton').onclick="/\*whatever\*/";
}
A technology like what #nbrooks said in the comments that would do this very well is AngularJS
If you give each selector button a class, you can use javascript to interate them and bind a click event. Then you can store in a data property a key which you can lookup in a json object start stores the related action handler and image. Finally in your click handler you can pull these properties and apply them to the start button by setting the onClick handler and background image of the start button.
<div class="startSelector" data-startdataid="1">Button1</div>
<div class="startSelector" data-startdataid="2">Button2</div>
<div class="startSelector" data-startdataid="3">Button3</div>
<div id="startButton">Start</div>
<script>
var startData = {
"1": {
action: function() {
alert("Button 1 was selected");
},
image: "/images/button1.jpg"
},"2": {
action: function() {
alert("Button 2 was selected");
},
image: "/images/button2.jpg"
},"3": {
action: function() {
alert("Button 3 was selected");
},
image: "/images/button3.jpg"
}
}
var changeStartButton = function(e) {
var startDataIndex = e.target.dataset.startdataid
var data = startData[startDataIndex]
document.getElementById("startButton").onclick = data.action
document.getElementById("startButton").style.backgroundImage = data.image
}
items = document.getElementsByClassName("startSelector")
for (var i = 0; i < items.length; i++) {
items[i].addEventListener("click", changeStartButton);
}
</script>
Example
http://jsfiddle.net/Xk8rv/3/

How to capture clicked button in js functions?

I have to buttons like this:
<input type='submit' id='submit' class='processAnimation'>
<input type='reset' id='reset' class='processAnimation'>
Now I have two js function. First function is called when ajax request is started and seconf function is called when ajax request is completed.
this.showLoading = function () {
backupsource = $('.processAnimation').attr('class');
$('.processAnimation').removeAttr('class').addClass('disabled-btn processAnimation');
$('.processAnimation').attr( 'backupsource', backupsource );
}
this.hideLoading = function () {
backupsource = $('.processAnimation').attr('backupsource');
if( backupsource != undefined ) {
$('.processAnimation').removeAttr('class').addClass( backupsource );
$('.processAnimation').removeAttr('backupsource');
}
}
EDIT: Above two functions are working and moving flower replaced clicked button. When request is complete then button is back. Problem is that when I click one button it replace all buttons(class=procesAnimation) with moving flower.
Thanks
Since you haven't posted your click event binding I am going to take a quick guess and say that your selector is not set right or conflicts with another element. try something like this:
$('input').click(function(){
switch( $(this).attr('id') ){
case 'submit' :
ShowLoading();
break;
case 'reset' :
HideLoading();
break;
}
});
and change the syntax of how you initialize the two functions to the following:
function ShowLoading(){
//do your show loading procedure here
};
function HideLoading(){
//do your hide loading procedure here
};
This is using the code u have currently
$('.processAnimation').click(function (){
if($(this).attr('type')=='submit'){
//submit has been clicked
}else{
//reset has been clicked
}
});
but it looks like you should really be using ID's rather than class's
if you have jQuery it is simple
$('#submit').click(showLoading)
$('#reset').click(hideLoading)
Just two different binding of events.
or did I miss something? :)

Categories

Resources