Pravin Kumar Raja Posted April 1 Posted April 1 I was using map function in my code but it simply do not work! I must be doing some silly mistake but I am not able to find it out. Can you Gurus help? Here is the code: <!DOCTYPE html> <html> <head> <script> getID = (x) => x.id; getText = (x) => x.value; function Click(x) { input = document.getElementsByTagName("input"); alert(Array.from(input.map((x.id == "id") ? getID : getText))); } </script> </head> <body> <input type="input" id="input1"> </input> <input type="input" id="input2"> </input> <button id="id" onclick="Click(this)"> ID </button> <button id="text" onclick="Click(this)"> Text </button> </body> </html> What I want it done is like this: When I click button "ID", list of IDs of the input field should be displayed. Likewise, when I click button "Text", it should display the list of texts which the input fields have currently. The functions getID and getText extracts the ID or text respectively when the argument is a single input field. Regards, Pravin Kumar.
Ingolme Posted April 1 Posted April 1 The getElementsByTagName() method does not return an Array, it returns a NodeList. The NodeList object does not have a map() method, so you have to turn it into an Array. You can do that with Array.from(): let input = Array.from( document.getElementsByTagName("input") ); You should be declaring all your variables with var or let. It seems like you've had this kind of problem before already:
Pravin Kumar Raja Posted April 1 Author Posted April 1 Thanks a lot. That helped! Pravin Kumar. <!DOCTYPE html> <html> <head> <script> let getID = (x) => x.id; let getText = (x) => x.value; function Click(x) { input = Array.from(document.getElementsByTagName("input")); alert(input.map((x.id == "id") ? getID : getText)); } </script> </head> <body> <input type="input" id="input1"> </input> <input type="input" class="input" id="input2"> </input> <button id="id" class="input" onclick="Click(this)"> ID </button> <button id="text" onclick="Click(this)"> Text </button> <script> input = document.getElementsByClassName("input"); </script> </body> </html>
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now