Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To pass Element Id In Javascript As Argument or parameter

Tags:

javascript

how it is possible to get element from the id of input element and pass it as parameter to java script function.

 <html>
 <body>
 <input type="text" id="name">
 <input type="button" onclick="call(id_of_input_type_text)" value="Click 
  me">
 <script>
 var call(id_of_input_type_text) = function(){
 var x = document.getElementById(id_of_input_type_text).value;
 alert(x);
 }
 </script>
 </body>
</html>

Sir/Mam I want to use single function like validation and get there value by pass id in the function so please help me regarding this problem

like image 619
Shaurya Srivastava Avatar asked May 26 '17 06:05

Shaurya Srivastava


People also ask

Can we pass ID as parameter in JavaScript?

You can definitely send an element's ID to a javascript function.

Can you give an element an ID in JavaScript?

IDs should be unique within a page, and all elements within a page should have an ID even though it is not necessary. You can add an ID to a new JavaScript Element or a pre-existing HTML Element.

How can I get the ID of an element using JavaScript?

The buttonPressed() callback function will have a returned event object which has all the data about the HTML element that is clicked on. To get the clicked element, use target property on the event object. Use the id property on the event. target object to get an ID of the clicked element.

How do you add an element to a ID?

To add an id attribute to an element: Select the element using the document. querySelector() method. Use the setAttribute() method to add an id attribute to the element.


2 Answers

Option 1 (from your question):

Note you can use call('name') in this case.

var call = function(id){
  var x = document.getElementById(id).value;
  alert(x);
}
<input type="text" id="name">
<input type="button" onclick="call(document.getElementById('name').id)" value="Click me">

Option 2 (send the element, so you won't need to get it in the function):

var call = function(elem){
  var x = elem.value;
  alert(x);
}
<input type="text" id="name">
<input type="button" onclick="call(document.getElementById('name'))" value="Click me">
like image 177
Jurij Jazdanov Avatar answered Oct 13 '22 01:10

Jurij Jazdanov


Use the same function with different arguments for each call. Like you can use:

<input type="button" onclick="call('name')" value="Click Me">

And it will alert the value of input field with id 'name'.

Hope this helps.

like image 31
Pranit Jha Avatar answered Oct 13 '22 01:10

Pranit Jha