Get value of the clicked button - javascript

I have multiple buttons containing different values.
My buttons :-
<button id="1" name="1" value="1">Button1</button>
<button id="2" name="2" value="2">Button2</button>
Now, if I click on Button1, I should get it's value. That is 1, and if I click Button2, I should get value 2.
I have written this code :-
<script type="text/javascript">
$("button").click(function() {
var fired_button = $("button").val();
alert(fired_button);
});
</script>
But it always alerts 1. What must I do to fix my code?

UPDATED
Use this instead of button in :
var fired_button = $("button").val();
You have to use this to target the current button clicked instead of button that will select all buttons in the DOM, .val() makes it to get the value of the first button.
$("button").click(function() {
var fired_button = $(this).val();
alert(fired_button);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="1" name="1" value="1">Button1</button>
<button id="2" name="2" value="2">Button2</button>

You need to use this variable in order to access the clicked button's value.
<script type="text/javascript">
$("button").click(function() {
var fired_button = $(this).val();
alert(fired_button);
});
</script>
This would return the value of the button.

You could try something as simple as:
$(this).val();
$(function(){
$("button").click(function() {
var fired_button = $(this).val();
alert(fired_button);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="1" name="1" value="1">Button1</button>
<button id="2" name="2" value="2">Button2</button>
Note: you should add your event listeners after the document is ready. This is why, I have enclosed the event handler in the
$(function{})
This is a shorthand of
$(document).ready(function(){})
For more information about this, please have a look here.

Use this inside the click handler
<script type="text/javascript">
$("button").click(function() {
var fired_button = $(this).val();
alert(fired_button);
});
</script>

this will give you the element that was clicked, $(this) to get a jquery version.
Update your code to:
$("button").click(function() {
var fired_button = $(this).val();
alert(fired_button);
});

Try with $(this).val();. It will return clicked button value.

If you're using jQuery, you're looking for the .attr() function.
$(this).attr("value")
That code will give you the value attribute of the html element designed by $(this) (or you precise the ID of the element).

Try $(this).val().
'this' always refers to the current object.

this will give you the element that was clicked, $(this) to get a jquery version.
Update your code to:
$("button").click(function() {
var fired_button = $(this).val();
alert(fired_button);
});

Plain JavaScript solution with ES6 syntax:
document.querySelectorAll('button').forEach(button => {
button.addEventListener('click', () => {
const fired_button = button.value;
alert(fired_button);
});
});

Related

Same AJAX call for multiple button on clicks on the same page [duplicate]

I have multiple buttons containing different values.
My buttons :-
<button id="1" name="1" value="1">Button1</button>
<button id="2" name="2" value="2">Button2</button>
Now, if I click on Button1, I should get it's value. That is 1, and if I click Button2, I should get value 2.
I have written this code :-
<script type="text/javascript">
$("button").click(function() {
var fired_button = $("button").val();
alert(fired_button);
});
</script>
But it always alerts 1. What must I do to fix my code?
UPDATED
Use this instead of button in :
var fired_button = $("button").val();
You have to use this to target the current button clicked instead of button that will select all buttons in the DOM, .val() makes it to get the value of the first button.
$("button").click(function() {
var fired_button = $(this).val();
alert(fired_button);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="1" name="1" value="1">Button1</button>
<button id="2" name="2" value="2">Button2</button>
You need to use this variable in order to access the clicked button's value.
<script type="text/javascript">
$("button").click(function() {
var fired_button = $(this).val();
alert(fired_button);
});
</script>
This would return the value of the button.
You could try something as simple as:
$(this).val();
$(function(){
$("button").click(function() {
var fired_button = $(this).val();
alert(fired_button);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="1" name="1" value="1">Button1</button>
<button id="2" name="2" value="2">Button2</button>
Note: you should add your event listeners after the document is ready. This is why, I have enclosed the event handler in the
$(function{})
This is a shorthand of
$(document).ready(function(){})
For more information about this, please have a look here.
Use this inside the click handler
<script type="text/javascript">
$("button").click(function() {
var fired_button = $(this).val();
alert(fired_button);
});
</script>
this will give you the element that was clicked, $(this) to get a jquery version.
Update your code to:
$("button").click(function() {
var fired_button = $(this).val();
alert(fired_button);
});
Try with $(this).val();. It will return clicked button value.
If you're using jQuery, you're looking for the .attr() function.
$(this).attr("value")
That code will give you the value attribute of the html element designed by $(this) (or you precise the ID of the element).
Try $(this).val().
'this' always refers to the current object.
this will give you the element that was clicked, $(this) to get a jquery version.
Update your code to:
$("button").click(function() {
var fired_button = $(this).val();
alert(fired_button);
});
Plain JavaScript solution with ES6 syntax:
document.querySelectorAll('button').forEach(button => {
button.addEventListener('click', () => {
const fired_button = button.value;
alert(fired_button);
});
});

change the background of an id that is clicked

When one of the element(id) of a form is clicked, i would like to listen to that event, and change the background of that element.
$(document).ready(function(){
$('form').on('click', function(e){
var x = e.target.id;
$(x).css('background-color',color);
return false;
});
}
<form>
<div id="a">Item1</div>
<div id="b">Item2</div>
<div id="c">Item3</div>
</form>
Your code will end up looking for tag names because the selector is
$("b")
If you want to do it the way you have it, you would need to add the missing #.
$("#" + x).css('background-color',color);
But there is no need to look up the element when you already have a reference to is. Use event delegation and this
$('form').on('click', 'div', function(e){
$(this).css('background-color',color);
});
Why bother using e.target? Just update your code to use $(this):
$(function() {
$('form > div').on('click', function(e) {
e.preventDefault();
$(this).css('backgroundColor', color);
});
});
This will work out. Take care of your tags.
$(document).ready(function(){
$('form').on('click', function(e){
var x = e.target.id;
$("#"+x).css('background-color',"red");
return false;
});
});
The thing happening to you is that event.target.id returns a string representing the id of the element, not a selector. So where you use $(x).... you have to use $('#'+x), your actual code does not work because the selector for the background change is not looking for an element with the X value on the Id but for an element called like the value of X (eg. x="a", then it's looking for elements)
Here's my "lowly" try:
<!DOCTYPE html>
<html lang = 'es'>
<head>
<title> My Test </title>
</head>
<body>
<form>
<div id="a"> Item1 </div>
<div id="b"> Item2 </div>
<div id="c"> Item3 </div>
</form>
<script>
function addBackgroundColor(e){
var index = parseInt(Math.random() * 4); // the number of the multiplier has to be equal to the length of the array colorsList.
e.target.style.backgroundColor = colorsList[index];
}
var colorsList = ['blue','red','green','yellow','orange']; //add others colors here if you want.
var divsList = document.getElementsByTagName('div');
for (var i in divsList){
divsList[i].addEventListener('click', addBackgroundColor);
}
</script>
</body>
</html>
No need to go fancy. Just do
$(document).ready(function(){
$('form div').on('click', function(e){
$(this).css('background-color',color);
return false;
});
}

Copy value from input 1 to input 2 onclick

Looking for a script that copies input value 1 to input 2 on button click and add +1 to sets text box.
b = document.getElementById('tussenstand').value;
var theTotal1 = b;
$(document).on("click", "#button1", function(){
theTotal1 = Number(theTotal2)
$('#eindstand').val(theTotal2);
});
$('#eindstand').val(theTotal2);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="tussenstand"></input>
<input id="eindstand"></input>
<input id="sets"></input>
<button id="button1">click</button>
Thanks in advance.
I think this will do it.
$(document).on("click", "#button1", function(){
var total = document.getElementById('tussenstand').value;
$('#eindstand').val(total);
var sets = parseInt($('#sets').val());
$('#sets').val( (sets || 0) + 1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="tussenstand"></input>
<input id="eindstand"></input>
<input id="sets"></input>
<button id="button1" onclick="">click</button>
$('#button1').click(function(){
$('#eindstand').val($('#tussenstand').val());
$('#sets').val(Number($('#sets').val())+1);
});
check here : jsfiddle
Edited as you commented
The code below should work. There are several issues that will help you in the future. In the HTML the function that is triggered via the onclick will interfere with the jQuery onclick. You may want to remove it.
onclick="bereken();
The way that you have your code the b variable is not declared.
b=document.getElementById('tussenstand').value;
The way that the jQuery onclick is written should have a narrower scope (not the document). The way that it is now every time you click any were in the document it fires. I changed this:
$(document).on("click", "#button1", function(){
to this:
$("#button1").on("click", function() {
The full edited code is here.
var count = 0;
$("#button1").on("click", function(){
if ( typeof b === 'number') {
count++;
$("#eindstand").val(b);
$("#sets").val(count);
}
});
Look at the JQuery API Documentation for the .on() method. The function doesn't take the target as a parameter, but as the caller object! EDIT: well, it would actually still work the other way around, but that makes event delegation. Only do that if you know what you're doing. I prefer changing this:
$(document).on("click", "#button1", function(){ ... });
into this:
$("#button1").on("click", function() { ... });
Which in vanilla JS would be:
document.getElementById("button1").addEventListener("click", function() { ... });
Next, you shouldn't need to define variables outside of your function, and naming variables with numbers in them is a bad practice. Try to make the names as clear as possible.
Now that this is clear, here's how I'd write it:
$("#button1").on("click", function() {
$("#eindstand").val($("#tussenstand").val());
$("#sets").val(parseInt($("#sets").val())+1);
});
To achieve that use:
$(function() { //on DOM ready
$('#button1').click(function(){ //Attach event
//Get value safe - can use parseFloat() too:
val1 = parseInt($('#tussenstand').val());
val2 = parseInt($('#eindstand').val());
sets = parseInt($('#sets').val());
//Make sure we are using integers:
if (isNaN(val1) || isNaN(val2) || isNaN(sets)) return;
//Add
$('#eindstand').val(val1 + val2);
//Increment:
$('#sets').val(sets+1);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="tussenstand" type='number' />
<input id="eindstand" value='0' type='number' />
<input id="sets" value='0' type='number' />
<button id="button1">click</button>

How to replace a button on click using jquery

I have a button currently available with an id :
<input type="button" id="show_button" value="Show" />
What I want is that..onclicking the button , the value of the button will be changed to "Hide" and it's id will be changed to "hide_button".. And on clicking the hide button it's value will be changed to "Show" and it's id will change to "show_button"..How can I achieve that?
i don't know why you want to change the id since we can get what you want without changing the ids..
try this
$('#show_button').click(function(){
var $this=$(this);
$this.val(($this.val()=="Show")?"Hide":"Show");
});
this is better since you don't have to use two click event handler for both the ids..
and if incase you need to change the ids.. then use on event delegation ..
$(document).on('click','#show_button',function(){
var $this=$(this);
$this.prop('id','hide_button');
$this.val("Hide"); //OR $this.val("Hide") //if you are using input type="button"
});
$(document).on('click','#hide_button',function(){
var $this=$(this);
$this.prop('id','show_button');
$this.val("Show"); //OR $this.val("Hide") //if you are using input type="button"
});
fiddle here
You can change value using
$('#show_button').val('hide');
You can change id using
$('#show_button').attr('id','hide_button');
$('body').on('click', '#show_button, #hide_button', function() {
var $this = $(this),
isShow = $this.attr('id') == 'show_button';
if (isShow) {
$this.attr('id', 'hide_button').val('Hide');
}
else {
$this.attr('id', 'show_button').val('Show');
}
});
jsFiddle: http://jsfiddle.net/sW49u/
Working example: http://jsfiddle.net/TjaBR/
$('body').on('click', '#process', function() {
$(this).toggleClass('hidden');
$(this).val($(this).hasClass('hidden') ? 'Hide' : 'Show');
});
Using Jquery Javascript library:
$('body').on('click', '#show_button', function() {
$(this).attr('id', 'hide_button').val('Hide');
});
$('body').on('click', '#hide_button', function() {
$(this).attr('id', 'show_button').val('Show');
});
One solution for your question is have 2 inputs, that you toggle between. I don't like changing/renaming id's principle.
Check this demo.
html
<input type="button" id="show_button" value="Show" />
<input type="button" id="hide_button" value="Hide" style="display:none;" />
jQuery
$('input').click(
function(){
$('input').toggle();
});

Javascript button ID selecting

I'm new to Javascript, seems I'm missing something simple here. I just want to return the ID of the button I am clicking but instead I'm getting "undefined."
HTML
<div class="btn-group" id="{{user.get('name')}}">
<button class="btn" id="voteup">^^</button>
<h4>{{user.get('vote')}}</h4>
<button class="btn" id="votedown">vv</button>
</div>
JAVASCRIPT
$(document).ready(".btn").click(function() {
var id = this.id;
alert(id);
)};
Try this
$(document).ready(function() {
$(".btn").click(function() {
alert($(this).attr("id"));
});
});
You mixed up the things. $(document).ready() accepts the handler function which is executed when the DOM tree is fully loaded. The correct solution is:
$(document).ready(function() {
$(".btn").click(function() {
var id = this.id;
alert(id);
});
});
Correct way to bind click listener is
$(function(){
$(document).on("click",".btn",function(e){
alert($(this).prop("id"));
});
});
I think you should try this way:
jQuery(document).ready(function(){
jQuery('.btn').live('click', function(){
var id = jQuery(this).attr('id');
alert(id);
});
});
Try it and tell us if worked or not (:
Ofcourse you have error in your javascript:
$(document).ready(".btn").click(function() { //<----here in doc ready handler
var id = this.id;
alert(id);
)}; //<---------------closing of the handler
this should be changed to this:
$(document).ready(function(){
$(".btn").click(function() {
var id = this.id;
alert(id);
});
});
If you are using jQuery, you can read the id attribute like this:
$(this).attr('id');

Categories

Resources