0

I am "somewhat" new to Scala, and am learning some Scala.js. I have a html form and am trying to take the strings from the fields and do some pattern matching to see if they meet basic criteria.

The problem I'm having refers to the method of getting the strings from each field, with jQuery("#id").value. I noticed that no matter what string i input into the fields I get the same "Success" alert for each field. When I printed the result of the jQuery().value method to the javascript console I always get "undefined", so I assume something with that is the problem.

As far as I can tell, the value method returns a scalajs.Dynamic, not a string. I am unsure, therefore, how to simply get the text from these text fields and am sure I'm missing something. Here is my code:

the index.html file:

<html>
<head>
    <title>Learning JQuery</title>
    <meta charset="utf-8">
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>

    <style>
        ...CSS...
    </style>
</head>
<body>

<script type="text/javascript" src="./target/scala-2.11/scala-js-tutorial-jsdeps.js"></script>
<script type="text/javascript" src="./target/scala-2.11/scala-js-tutorial-fastopt.js"></script>

<script type="text/javascript">
    Script().main();
</script>
<div id="wrapper">
    <div id="error"></div>

    <form id="validationForm">

        <label for="email">Email</label>
        <input name="email" id="email">

        <label for="phone">Telephone</label>
        <input name="phone" id="phone">

        <label for="pass">Password</label>
        <input name="pass" type="password" id="pass1">

        <label for="pass">Confirm Password</label>
        <input name="pass" type="password" id="pass2">
        <input id="submitButton" type="submit" value="submit">
    </form>
</div>
</body>
</html>

Script.scala:

import scalajs.js
import org.scalajs.jquery.jQuery

import js.annotation.JSExport
import js.{Dynamic, JSApp}
import js.Dynamic.{ global => g }
/**
  * Created by pslagle12 on 6/21/16.
  */

@JSExport
object Script extends JSApp {

  implicit def dynamicToString(d: Dynamic): String =
    d.toString

  private val fieldsAndErrors = Map(
    ("email" -> "Please enter a valid email address"),
    ("phone" -> "Please enter a valid phone number"),
    ("pass1" -> "Please enter a matching password")
  )

  private val regexTest =
    """/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|
  (\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])
      |(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/""".r

  lazy val email = jQuery("email").value
  lazy val phone = jQuery("phone").value
  lazy val pass1 = jQuery("pass1").value
  lazy val pass2 = jQuery("pass2").value

  @JSExport
  def main(): Unit = {

    jQuery("#validationForm").submit(
      fieldsAndErrors.keys foreach (x => {
        if (errorChecker(x) == "")
          g.alert("Success")
        else
          g.alert(errorChecker(x))
         }
      )
    )
  }

  def isValidEmailAddress(address: String): String =
    if (!regexTest
      .pattern
      .matcher(address)
      .matches()) {
      fieldsAndErrors("email")
    } else ""

  def isValidPhone(number: String): String =
    if (!number.isInstanceOf[Int]) 
      fieldsAndErrors("phone")
    else ""

  def isValidPass(pass1: String): String =
    if (pass1 != pass2) 
      fieldsAndErrors("pass1")
    else ""

  def errorChecker(key: String): String =

    key match {
      case "email" => isValidEmailAddress(email)
      case "phone" => isValidPhone(phone)
      case "pass1" => isValidPass(pass1)
      case _ => isValidPass(pass1)
    }
}

PS: I am aware that there are some other errors in this code. I am mainly concerned with knowing how to get the string from the text input with Scala.js's JQuery api.

Patrick S.
  • 275
  • 1
  • 5
  • 19
  • Can't swear to it, but try `value()` instead of `value` -- I'm not sure they are interchangeable at the facade level. Although I confess I'm a bit surprised this even compiles: if you put a `:String` type ascription on `email` and the like, what happens? – Justin du Coeur Jun 23 '16 at 18:59
  • It compiles. It didn't used to, but I added the implicit conversion at the top of the file to change the Dynamic objects to Strings. I don't know if that is the "best" thing to do, but I am pretty green to Scala. This is my first code in it after having gone through some tutorials in my own time. I added the () at the end of the lazy vals, but no change except strangely the password field tells me the opposite now. I was mistaken in my original post: They all send error messages except now the password one sends "Success" – Patrick S. Jun 23 '16 at 19:14
  • Although I have not programmed in Javascript in the past, I would think it is a common task in to get the text from a text field. Surprised this is such a pain. Makes me think I'm missing something painfully obvious or it's related to how Scala.js handles JQuery. – Patrick S. Jun 23 '16 at 19:19
  • Ah -- hadn't noticed that. I *strongly* recommend against putting in implicit conversions from js.Dynamic. The legitimate uses of that type are so context-dependent that it's likely to get you into deep trouble. Hmm... – Justin du Coeur Jun 23 '16 at 21:51
  • Assumption check: you're not seeing the output until you press the Submit button? Just want to head off the most common problem, which is trying to fetch this stuff before the DOM is ready. (The most common problems are usually jQuery-related, not Scala.js per se.) – Justin du Coeur Jun 23 '16 at 21:52

1 Answers1

1

Ah, wait a second -- I see the likely issue. The identifiers in your jQuery calls are incorrect. You can't say jQuery("pass1"), it has to be jQuery("#pass1"), the same way you did for validationForm. The # tells jQuery to look for an ID named "pass1" -- as it is, I'm not sure what it's trying to look up, but it's probably returning an empty set of objects, so .value isn't producing anything.

This is one of the most common (and easy to make) mistakes in jQuery...

Justin du Coeur
  • 2,699
  • 1
  • 14
  • 19
  • Thanks a lot! I had learned of that issue early on, but it was after I had made the lazy vals and unfortunately never changed them at the time. – Patrick S. Jun 23 '16 at 22:08