How can I get the value of an HTML button as a parameter for my javascript?

I have several buttons corresponding to several text areas. I need to send a function to handle all these buttons and handle each one separately

<html> <head> <script src="jquery-1.6.js"></script> <script type="text/javascript"> function getUniqueButtonValue(value) { alert(value); $("value").hide(); } </script> </head> <body> <button id=someUinqueId value=something>Clear Selection</button> </body> </html> 
+4
source share
6 answers

Leaving aside the fact that you put a unique identifier in the value attribute, and not in the id attribute ... here a fiddle .

 $(document).ready(function(){ $("button").click(function(){ var me = $(this); // do whatever with me alert(me.val()); me.hide(); }); }); 
+5
source

There seems to be a lot of problems with the code you posted in your question. First, (unless you use <!DOCTYPE html> as your doctype), you cannot have id values ​​starting with a number.

Secondly, jQuery (I assume it is jQuery and not some other JS library) in your getUniqueButtonValue function getUniqueButtonValue not work, because the selector will look for the value element, which is unlikely to exist.

I assume that the value attribute of your button intended to match the id another element that you want to hide when the button is clicked.

Since you have jQuery code in your example, I will give you a jQuery solution since it is much simpler:

 $(document).ready(function() { $("button").click(function() { alert(this.value); $("#" + this.value).hide(); }); }); 

In addition, you do not close the body tag, but I assume that this is just a mistake when copying and pasting the code into the question.

+3
source

You can do it:

 <button id=123 value=uniqueId545 onclick="javascript:getUniqueButtonValue($(this).val());">Clear Selection</button> 
+2
source

try it

 $("#123").click(function(){ getUniqueButtonValue($(this).val()); }); 
+1
source

I'm not sure what you are trying to do here. If I understood correctly, this is what you want (ids should not start with a number, so I put "a" before 123:

 $("#a123").click(function(){ getUniqueButtonValue($("#a123").getAttribute('value'); } function getUniqueButtonValue(value) { alert(value); $("#"+value).hide(); } </script> </head> <body> <button id=123 value=uniqueId545>Clear Selection</button> </html> 
+1
source

You can save a lot of work by trying:

 <button class="clearbutton" value="#Foo">Clear Foo</button> <input type="text" name="foo" id="foo" /> 

With the following JavaScript:

 $('.clearbutton').click(function(e) { $($(this).val()).val(''); }); 
+1
source

Source: https://habr.com/ru/post/1369154/


All Articles