Find value of multiple buttons with javascript - 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);
});
});

Related

jQuery dynamically update data keys & values

I'm trying to make a function that gets all data-attributes dynamically from an element. For e.g.:
<button id="button" data-key1="title" data-key2="content">Button 1</button>
<button id="changeButtonData">Change data for button 1</button>
$(document).on('click', '#button', function(e){
e.preventDefault();
$buttonData = $(this).data();
console.log($buttonData);
}
$(document).on('click', '#changeButtonData', function(e){
e.preventDefault();
//edit existing data-keys value
$('#button').data('data-key1', 'newtitle');
//store new data-key on element
$('#button').data('data-key3', 'new');
}
The problem is, if i click the first button and check the console log, it will show data-key1="title" and data-key2="content"
And if i click the 2nd button afterwards, and click the first button again to fire the console logging again, it won't display the new replaced data-attributes or the new data-tags.
Anyone got an idea how to solve this?
The issue is because when you set the data attribute you should omit the data- prefix, eg: $('#button').data('key3', 'new');. Try this:
$(document).on('click', '#changeButtonData', function (e) {
e.preventDefault();
$('#button').data({
'key1': 'newtitle',
'key3': 'new'
});
});
Example fiddle

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>

Find Id of clicked button

I wanted to get the id of clicked button since i have 4-5 buttons on my form.
<button type="submit" style="height: 30px" id="btnHelp" name="btnHelp" onclick="ShowHelp(2);return false;">Help</button>
<button type="button" style="height: 30px" id="btnClose" name="btnClose" onclick="Close();return false;">Close</button>
<button type="button" style="height: 30px" id="btnSave" name="btnSave" onclick="Save();return false;">Close</button>
...............................
Whichever may be the button click, I just want to get id of that button.
$(function () {
var id = $(this).attr('id');
alert(id);
})
Also with
$("input").click(function (event) {
var urlid = $(this).attr('id')
alert(urlid);
})
but i am getting the alert as undefined.
How can i get id of button clicked?
Please help me.
Try
:button Selector
Selects all button elements and elements of type button.
$(":button").click(function (event) {
var urlid = this.id;
alert(urlid);
});
Fiddle Demo
Problem
$("input") --> selects elements with tag input eg. <input type="text"/> but not <button> tag .
I'd try to replace this with the event triggerer.
var urlid = $(event.target).attr("id");
Also, probably your onclick function is preventing your script to be executed, because it's handling the click event, not letting your function do it.
I ditched the onclick attributes of buttons you have, and hooked click events to button rather than input, and it worked. So check whether you are connecting to the right element.
See example here.
<script>
jQuery(":button").click(function (event) {
var urlid = $(this).attr('id')
alert(urlid);
})
</script>
Try this its work
very simply:
$("input").click(function (event) {
var urlid = this.id;
alert(urlid);
})
for button:
$("button").click(function (event) {
var urlid = this.id;
alert(urlid);
})
You might try use event passed as argument into any event handler instead of this for event.target is referring to element actually triggering your handler (being clicked) and event.delegateTarget being element handler has been attached to initially. In both cases you might have to use $() for using jQuery or simply stick with accessing .id in either case.
In your case this would be
$("input").click(function (event) {
var urlid = $(event.delegateTarget).attr('id');
alert(urlid);
});
to ensure handler is always accessing that it has been attached to, here.
Except for this quite simple scenario relying on this is sometimes trickier than using provided arguments.
EDIT : However, your case seems to be related to issues encountered by Tusha Gupta, for sure. Your buttons aren't "inputs" so that handlers are never attached, actually.
$(function () {
$("button").click(function () {
alert($(this).attr("id"));
});
});

How to decide which element is being clicked in jQuery?

I have more similar elements in HTML which are being added continously with PHP. my question is the following:
With jQuery, I would like to add a click event to each of these <div> elements. When any of them is being clicked it should display it's content. The problem is that I guess I need to use classes to specify which elements can be clickable. But in this case the application will not be able to decide which specific element is being clicked, right?
HTML:
<div class="test">1</div>
<div class="test">2</div>
<div class="test">3</div>
<div class="test">4</div>
<div class="test">5</div>
jQuery try:
$("test").on("click", function()
{
var data = ???
alert(data);
});
UPDATE - QUESTION 2:
What happens if I'm placing <a> tags between those divs, and I want to get their href value when the DIV is being clicked?
I always get an error when I try that with this.
this refers to the element triggering the event. Note that it is a regular js element, so you'll need to convert it to a jQuery object before you can use jQuery functions: $(this)
$(".test").on("click", function()
{
var data = $(this).text();
alert(data);
});
Like this:
$(".test").on("click", function(event)
{
var data = $(event.target);
alert(data.text());
});
this variable contains the reference of current item
$(document).ready(function() {
$(".test").click(function(event) {
var data = $(this).text();
alert(data);
});
})
;
The class selector in jquery is $(".ClassName") and to access the value, use $(this) as such:
$(".test").on("click", function(){
var data = $(this).text();
alert(data);
});
You can use this inside the function which mean clicked div
DEMO
$(".test").on("click", function () {
alert($(this).html());
});

replacing element with jQuery

I have <form>s on my page that I want to replace with <button>s. The thing that is causing me difficulty is that I want to use the value of the <form>'s submit input as the html for the button.
<form action="/postcomment/" method="post">
<inputs>
.
.
.
<input type="submit" value="Reply">
</form>
Becomes
<button class="postcomment">Reply</button>
I'm having a hard time wrapping my mind around the chaining here. I need to grab the data values (e.g. "Reply") and then insert them into the button elements in one jQuery operation (or else manage the ordering with something like .index()) and I haven't figure out how to do that yet.
Working example here: http://jsfiddle.net/Mch86/
$(document).ready(function(){
$('form').each(function(){
button = $('<button>' + $('input[type="submit"]', this).val() + '</button>').addClass($(this).attr('action').replace(/\//g, ''));
$(this).replaceWith(button);
});
});
Do something like this:
$('input[type="submit"]').replaceWith(function () {
return $('<button>').text(this.value).addClass('postcomment');
});
jsFiddle Demo
This will replace all of your submit buttons (<input type="submit">) with a <button>, keeping the text on the button.
replaceWith() allows you to use a function as its parameter, which has a reference to the individual submits themselves (this).
Since you said you have multiple forms:
$(function() {
$('form').each(function() {
var str = $(this).find('input[type="submit"]').val();
$(this).replaceWith($('<button/>').addClass("postcomment").text(str));
});
});
You could do:
var label = $('form input:submit').val();
var action = $('form').attr('action').replace(/\//g, '');
var button = $('<button />', { class: action});
button.html(label);
$('form').replaceWith(button)
;
fiddle here: http://jsfiddle.net/be3af/1/

Categories

Resources