How to reference button in jQuery? - javascript

In the HTML, I have a button defined like this:
<button type="button" onclick="toggleEdit();">Edit</button>
At the end of the page, I have this script I am working on:
<script language="JavaScript">
<!--
function toggleEdit() {
var btn = $(this);
var li = btn.parent();
var textArea = li.children('.readOnly');
...
}
//-->
</script>
I cannot reference the button I have clicked in the script. The btn variable is an object, but I don't know anything else than that.
I found many examples on the internet that are using this approach:
$(document).ready(function () {
$('#buttonID').click(function () {
...
but I cannot reference the button via ID because it is added dynamically. So, how do I reference it? Thanks.

Just to keep it your way, you have to tell the code that this will refer to the button instead of the actual function.
To do this you can just add an extra argument to the toggleEdit function.
The new HTML would look like this (no apply or call function needed):
<button type="button" onclick="toggleEdit(this);">Edit</button>
Then your new JavaScript would look like this:
<script language="JavaScript">
<!--
function toggleEdit(t) {
var btn = $(t);
var li = btn.parent();
var textArea = li.children('.readOnly');
...
}
//-->
</script>

You can pass the event into the function, and then use that.
<button type="button" onclick="toggleEdit( event );">Edit</button>
Then in your function, you can get the target of the event:
function toggleEdit( e ) {
var btn = $( e.target );
var li = btn.parent();
var textArea = li.children('.readOnly');
...
}

Related

Disable load function untill button is selected in javascript?

Hi this is an odd question and i will try to ask it correctly. I have a function using javascript called load canvas.
function loadCanvas(canvas) {
relevant code here...
}
I also have a normal button called btn.
<button class="btn" type="button">Play!</button>
I am wondering can i disable the function until the play button is selected? The function is for a game using javascript. So on load there isnt anything there until i press play then it appears!
any ideas/help please?
$(document).ready(function(){
var loadCanvas= function (canvas) {
relevant code here...
}
$("#test").on('click',loadCanvas()); // using jquery
document.getElementById("test").addEventListener("click",loadCanvas()); // using javascript
<button class="btn" id="test" type="button">Play!</button>
})
If you are having issue because other method is triggering the function you can add a flag with a boolean and turn it on when you click..
Something like that:
The button don't change at all
<button class="btn" type="button">Play!</button>
The js code with this change:
var buttonClicked = false;
function loadCanvas(canvas) {
if(buttonClicked){
relevant code here...
}
}
And in the on click function add this before call the function:
buttonClicked = true;
At the end your js should look like this:
var buttonClicked = false;
function loadCanvas(canvas) {
if(buttonClicked){
relevant code here...
}
}
$(".btn").click(function(){
buttonClicked = true;
var canvas = ...;
loadCanvas(canvas );
});
EDIT
If you have more buttons with the class .btn you should use an id and change the selector of the .click() with the selector of the id instead of the class selector
As you mentioned in the comments <script type="text/javascript"> loadCanvas("game"); </script> You are calling the function as soon as the page loads. So you will have to change it to:
<button class="btn play-button" type="button">Play!</button>
<script type="text/javascript">
$('.play-button').click(function(e){
loadCanvas("game");}
);
</script>
If you are not using jquery you will have to handle the click event by javascript.
You got to do following:
function loadCanvas(game) {
alert('loading canvas');
}
<button class="btn" type="button" onclick="loadCanvas('game')">Play!</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);
});
});

Why is the button disapearing?

The text "Now I'm here..." is supposed to disappear when the button is clicked, not the button itself.
<div id="alpha">Now I'm here...</div>
<button type="button" onclick="remove()">Remove</button>
<script>
function remove()
{
var element = document.getElementById("alpha");
element.parentNode.removeChild(element);
}
/*function add()
{
var ele = document.createElement("p");
var text = document.createTextNode("This is new text");
ele.appendChild(text);
var location = document.getElementById("alpha");
location.appendChild(ele);
}*/
</script>
There is another function called remove that is interfering with your function.
Rename your function and it works fine:
http://jsfiddle.net/fL3gZ/
<div id="alpha">Now I'm here...</div>
<button type="button" onclick="Myremove()">Remove</button>
<script>
function Myremove()
{
var element = document.getElementById("alpha");
element.parentNode.removeChild(element);
}
</script>
What's happening is remove() is being called on the button itself! HTMLElement.prototype.remove is an existing function (in some browsers)! Oh god!
var button = document.getElementsByTagName("button")[0];
// surprise! this is what's actually happening
button.remove();
Check out this alternative approach. See: fiddle
Change HTML to
<div id="alpha">Now I'm here...</div>
<button type="button">Remove</button>
Then use this JavaScript
function remove(id) {
var elem = document.getElementById(id);
if (elem) elem.parentNode.removeChild(elem);
}
var button = document.getElementsByTagName("button")[0];
button.addEventListener("click", function(event) {
remove("alpha");
event.preventDefault();
});
A couple things about this:
I'm favoring a more unobtrusive approach
The remove function is single purpose, and reusable
It will work in more browsers
You won't run into WTFs like you just experienced
remove() is already an excisting javascript method, so you are actually calling that method on your button instead of calling the function.
Just rename the function and it will be fine.
Fiddle: http://jsfiddle.net/WkUqT/7/
function removeText()
{
var element = document.getElementById("alpha");
element.parentNode.removeChild(element);
}
You are probably using chrome as your browser to test that code. Elements in chrome have a self-removal, .remove() method which removes the element itself from its container.
This is the main reason why the code above removes the button, because of this the appended event in your onclick() declaration was not invoked because the element invoking the event does not exist anymore. Try changing the name of your function to removeElement().

Javascript click function not working

I'm trying to write a simple javascript function that will clone some html input fields when the user clicks a button, but for some reason the button's click function isn't being called when I click it. Any ideas why?
Here's the javascript:
<SCRIPT LANGUAGE="JavaScript">
$(document).ready(
function(){
$("#default-label").hide();
$("#default-element").hide();
var counter = parseInt($("#counter").val());
$("#addProduct").click(
function(){
var product = $('#fieldset-default');
var newProduct = product.clone(true);
newProduct.insertAfter(product);
document.getElementById("addProduct").innerHTML = 'Add More';
$("#counter").val(++counter);
}
);
}
);
</script>
My HTML for the button:
<button id="addProduct" type="button" name="add">Add Product</button>
i think you missed jquery plugin,included latest version of jquery library, if not there.

How to access the id of the button who called a Javascript function using $(this)?

I am new to Javascript. I have set a couple of buttons on a page, like this:
<div id='MID_1_4'>
<div id="login">logout</div>
<button type="button" id="logout" onclick="loadXMLDoc2()">Logout</button>
</div>
...
I want to extract the id of the button who called loadXMLDoc2(). This method is defined as following:
function loadXMLDoc2() {
var retr = $(this).attr("id");
document.getElementById("L1_LEFT").innerHTML
= retr;
}
Yet, L1_LEFT is set to undefined when I click on buttons. I thought $(this) meant "the current HTML element". If it is not the button then what is it? And how can I extract the button's id?
this refers to window (the global object) inside the function, this refers to the element in the onclick handler.
while it's bad approach to do javascript in html, try this:
<div id='MID_1_4'>
<div id="login">logout</div>
<button type="button" id="logout" onclick="loadXMLDoc2(this)">Logout</button>
</div>
function loadXMLDoc2(elm) {
var retr = elm.id;
document.getElementById("L1_LEFT").innerHTML
= retr;
}
A better approach is to separate HTML and javascript:
<div id='MID_1_4'>
<div id="login">logout</div>
<button type="button" id="logout">Logout</button>
</div>
(Somewhere in js file )
function loadXMLDoc2(elm) {
var retr = elm.id;
document.getElementById("L1_LEFT").innerHTML = retr;
}
$( document ).ready( function(){
//This function is executed after all elements on the page are ready to be manipulated
$( "#logout" ).bind( "click",
function(){
loadXMLDoc2( this );
}
);
});
Yes indeed, the variable this refers to the target element of an event handler. I think you are over complicating it, however. Try
var retr = this.id;
to obtain your id. KISS!!

Categories

Resources