jQuery dynamically update data keys & values - javascript

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

Related

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);
});
});

How to get id like "invokedOn" text by a right click event with Bootstrap ContextMenu?

I am using Bootstrap 3.0 ContextMenu. here is a link http://jsfiddle.net/KyleMit/X9tgY/
I need to know how i can get the id or data-Id of the clicked element. i try many of the tricks but i cant get the clicked element id? Like when i clicked on "Jacob" row i get the "Jacob" after clicked. I also need from this line
<td data-id="user-3">
<a data-id="user-3">Jacob<a/>
<td/>
"data-Id"?
i tried var $selectedFileId = $(this).closest('a').html(); or alert($(this).parent('a').html());
Use this code for get clicked element id
jQuery(document).on('click', function(e){
console.log(e.target.id);
})
I get the id by little additions in the contextMenu handler, Changes
// click handler for context menu
function ContextMenuClickHandler() {
$(settings.menuSelector)
.off('click')
.on('click', function (e) {
$(this).hide();
var $invokedOn = $(this).data("invokedOn");
var $selectedMenu = $(e.target);
// My Changes
var $selectedFileId = $(this).data("invokedOn").find('.yourClass').attr('id');
settings.menuSelected.call($(this), $invokedOn, $selectedMenu, $selectedFileId);
});
}

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"));
});
});

Get a field with jQuery when a button is clicked

I have a table full of appointments. Every appointment has two buttons. One for canceling the event, one for accepting it.
I am struggling to get the appointmentId in the jQuery function when I click on a button. Can you please give me a hint how to do this? The appointmentId is in the table as a hidden input field.
// my html code
<tr>
<td align="left">
<input type="hidden" name="appointmentId" value="234">
John Smith - 14.03.2013 at 9 o'clock
</td>
<td align="right">
<input type="button" id="acceptEvent" class="acceptEvent" value="Accept">
<input type="button" id="cancelEvent" class="cancelEvent" value="Cancel">
</td>
</tr>
// my jQuery code
$("body").delegate('.acceptEvent', 'click', function() {
console.log('accept event clicked');
// get the appointmentId here
});
$("body").delegate('.cancelEvent', 'click', function() {
console.log('cancel event clicked');
// get the appointmentId here
});
Use closest to grab the parent tr element, then select your hidden field.
The reason that this is the correct answer is because it takes the context of the click event with $(this). Then it travels up the DOM tree to your root table row element and selects the child by name. This ensures that you are always in the correct row.
EDIT: I know you already selected an answer, but this was really bothering me that it wasn't working properly. I had to walk down twice using .children() to get it to work though you could also use .find('input[name="appointmentId"]'). Even though you've already selected your answer, I hope this will help you.
$('.acceptEvent').click(function() {
var myVal = $(this).closest('tr').children().children().val();
});
$('.cancelEvent').click(function() {
var myVal = $(this).closest('tr').children().children().val();
});
In the click function, you have access to the button that was clicked with this so you can do:
$("body").on('click', '.cancelEvent', function() {
var input = $(this).closest('tr').find('input[name="appointmentId"]').val();
});
Assuming you have no other IDs or classes to key off of, you can use jQuery's Attribute Equals Selector in reference to the clicked button's parent tr element:
$('.acceptEvent').click(function() {
// get the appointmentId here
var appointmentId = $(this).closest('tr').find('input[name="appointmentId"]').val();
});
I'll do it like that :
$("body").on('.acceptEvent', 'click', function() {
var id = $('input[name="appointmentId"]').val();
//Or search in the parent <tr>
var id = $(this).parent().find('input[name="appointmentId"]').val();
console.log('accept event clicked');
console.log('Id is ' + id);
});

Categories

Resources