2

I have an input field with the the id "id_email". A user will enter his email into this field on my form. I am trying to run some validation code on the email that the user inputs. I would like to pass the inputted value to the server to compare it to the database, but jQuery keeps returning a blank string.

HTML:

<div class="fieldWrapper">
                <label for="email">Email</label>
                <input type="text" placeholder="Email" id="id_email" name="email" maxlength="75">
           </div>

Javascript:

function CheckDuplicateEmail(invalidForm)
{
  $("#id_email").focusout(function()
  {
    $.ajax({ type: "POST",
             url: "/CheckDuplicateEmail/",
             dataType: "json",
             data: {"email" : $("#id_email").html()},
             success: function(jsonObject) 
             { 
                if (jsonObject === "exists")
                {
                    $("this").append("<ul class=\"errorlist\"><li>This email already exists<li></ul>")
                    invalidForm = true;
                }
                else
                {
                    invalidForm = false;
                }
             }
    });
  });
}

When I look at the AJAX post that is being sent to the server, I can see that email is blank. The line $("#id_email").html() is failing. I know that the selector is working correctly because the AJAX request is sent to the server. This implies that $("#id_email").focusout is working correctly. Since this statement uses the same selector as the $("#id_email").html() statement, I have to assume the html() function is wrong. Note that I tried the text() function with the same results.

Does anyone have any idea what is wrong?

4

2 回答 2

3

更改此行data: {"email" : $("#id_email").html()},

data: {"email" : $("#id_email").val()},

.html()不适用于输入元素。您需要使用.val()来获取输入值。

于 2012-09-17T02:50:29.277 回答
3

利用$("#id_email").val()

function CheckDuplicateEmail(invalidForm)
{
  $("#id_email").focusout(function()
  {
    $.ajax({ type: "POST",
             url: "/CheckDuplicateEmail/",
             dataType: "json",
             data: {"email" : $("#id_email").val()},
             success: function(jsonObject) 
             { 
                if (jsonObject === "exists")
                {
                    $("this").append("<ul class=\"errorlist\"><li>This email already exists<li></ul>")
                    invalidForm = true;
                }
                else
                {
                    invalidForm = false;
                }
             }
    });
  });
}

您可以查看这篇文章以了解更多何时使用 getter.html().val().text()

于 2012-09-17T02:50:42.327 回答