0

Can someone help me with this JS code? :)

Hello, peoples! I have a little problem with the code below. I don't understand why variable phone inside the RegExpression function doesn't take the value introduced by me. The code will run If i write phone = '123-321-1111' instead of phone = document.getElementById('nr'). Maybe I write something wrong. I mention that I am a beginner in JS. Thank you! :) <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <script language="Javascript" type="text/javascript"> function RegExpression() { phone = document.getElementById('nr') re = /^[\(]?(\d{3})[\)]?[ -\.]?(\d{3})[ -\.]?(\d{4})$/ if(re.test(phone)) { MyArray = re.exec(phone) alert('Area code: ' + MyArray[1] + '\nExchange: ' + MyArray[2] + '\nNumber: ' + MyArray[3]) } } </script> </head> <body> <form name="Myform" action="http://www.google.ro" method="post"> <p> <input id="nr" type="text" name="number"> <input name="Run Reg Expression" value="Run Reg Expression" type="button" onclick="RegExpression()"/> </p> </form> </body> </html>

7th Jun 2018, 8:44 PM
Denis Peptanariu
Denis Peptanariu - avatar
3 Respostas
+ 3
Add .value to the 'phone' variable assignment as follows: var phone = document.getElementById('nr').value; // <- You forgot .value Hth, cmiiw
7th Jun 2018, 9:05 PM
Ipang
+ 4
You're welcome Denis Peptanariu, glad if it helps ; )
7th Jun 2018, 9:32 PM
Ipang
+ 1
Oh! It's working now. Thank you, Ipang.
7th Jun 2018, 9:29 PM
Denis Peptanariu
Denis Peptanariu - avatar