0

Both first and last name values return as empty or undefined, same things with the console.log data.

But the razor page antiforgery token works fine in jquery

I have tried using $('#Last_Name').val() and tried using $('#Add_Form input[name="First_Name]"').val(); but which done seem to work

Here is my code

$(document).ready(function () {       
    $('#Add_Submit').click(function (e) {
        e.preventDefault();
        console.log(data);
           alert(first_Name + ' ' + last_Name);
        alert(first_Name + ' ' + last_Name);
        alert(first_Name2 + ' ' + last_Name2);
        Dawn(data);

    });


   var last_Name2 =  $("#First_Name").val();
    var first_Name2 = $("#Last_Name").val();

      var last_Name =  $('#Add_Form input[name="First_Name]"').val();
    var first_Name = $('#Add_Form input[name="Last_Name]"').val();
    var email = "$('#Email').val()";
      var token = $('#Add_Form input[name="__RequestVerificationToken"]').val();

Both values return null

Layout page

Layout page

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - Xxx</title>

<environment include="Development">
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
<link href="~/lib/xa/css/main.css" rel="stylesheet" />

<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha384-xBuQ/xzmlsLoJ TNrHIW2I5f" crossorigin="anonymous"></script>



@*<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>*@
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/additional-methods.min.js"></script>

<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>


</environment>
<environment exclude="Development">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute"
crossorigin="anonymous"
integrity="sha384-ggOyR0i voRxT2MZw1T"/>
</environment>
<link rel="stylesheet" href="~/css/site.css" />
</head>

finally my razor page

<form asp-action="Address_Add" id="Add_Form">

                @Html.AntiForgeryToken()
                <div asp-validation-summary="ModelOnly" class="text-danger"></div>



                <div class="form-group ">
                    <label asp-for="Title" class="control-label"></label>
                    @Html.DropDownList("AddressType", new SelectList(ViewBag.Titled, "Value", "Text"), new { @class = "form-control", @style = "width: 50px;" })
                    <span asp-validation-for="Title" class="text-danger"></span>
                </div>

                <div class="form-group">
                    <label asp-for="First_Name" class="control-label">First Name</label>
                    <input asp-for="First_Name" required class="form-control" maxlength="50" />
                    <span asp-validation-for="First_Name" class="text-danger"></span>
                </div>

                <div class="form-group">
                    <label asp-for="Last_Name" class="control-label">Last Name</label>
                    <input asp-for="Last_Name" required class="form-control" maxlength="50" />
                    <span asp-validation-for="Last_Name" class="text-danger"></span>
                </div>


                <div class="form-group">
                    <label asp-for="Gender" class="control-label">Gender</label>
                    @Html.DropDownList("AddressType2", new SelectList(ViewBag.Gender, "Value", "Text"), new { @class = "form-control", @style = "width: 50px;" })
                    <span asp-validation-for="Gender" class="text-danger"></span>
                </div>




                <br />
                <hr />
                <br />
                <div class="form-group">
                    <input type="submit" id="Add_Submit" value="Go !" class="btn btn-default" />
                </div>
                <br />
                <hr />
                <br />
            </form>

whats wrong here ?

UPDATED: Here is my full html code

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Personals - xxxxx</title>


    <link rel="stylesheet" href="/lib/bootstrap/dist/css/bootstrap.css" />
    <link href="/lib/xxxxx/css/main.css" rel="stylesheet" />

    <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha384-xBuQ/xzmlsLoJpyjoggmTEz8OWUFM0/MakNTNrHIW2I5f" crossorigin="anonymous"></script>



    <script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
    <script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/additional-methods.min.js"></script>

    <script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>




    <link rel="stylesheet" href="/css/site.css" />
</head>
<body>
    <header>

    </header>
    <div class="container">
        <div class="topnav text-center">
            <a class="active" href="#home">Home</a>

            <input type="text" placeholder="Search.."><button type="button" class="btn btn-primary btn-sm">Search</button> <div class="mr-6">
                <a class="dept dropdown-item" href="#">

                </a>
            </div>
        </div>


        <div id="cookieConsent" class="alert alert-info alert-dismissible fade show" role="alert">
            Use this space to summarize your privacy and cookie use policy. <a class="alert-link" href="/Home/Privacy">Learn More</a>.
            <button type="button" class="accept-policy close" data-dismiss="alert" aria-label="Close" data-cookie-string=".AspNet.Consent=yes; expires=Wed, 22 Jul 2020 04:52:05 GMT; path=/; secure">
                <span aria-hidden="true">Accept</span>
            </button>
        </div>
        <script>
        (function () {
            var button = document.querySelector("#cookieConsent button[data-cookie-string]");
            button.addEventListener("click", function (event) {
                document.cookie = button.dataset.cookieString;
            }, false);
        })();
        </script>

        <main role="main" class="pb-3">



            <script>


    $(document).ready(function () {





        $('#Add_Submit').click(function (e) {
            e.preventDefault();




        var data = { __RequestVerificationToken: token, Email: email, First_name: first_Name, Last_name: last_Name };

            console.log(data);
            alert(first_Name + ' ' + last_Name + ' '+  token + '' + ehi);
            alert(first_Name2 + ' ' + last_Name2 + ' '+  token+ '  '+ehi);

            Dawn(data);
              alert('back on track2');
        });

        var ehi = 'test';
          var last_Name2 =  $("#First_Name").val();
        var first_Name2 = $('#Last_Name').val();

          var last_Name =  $('#Add_Form input[name="First_Name]"').val();
        var first_Name = $('#Add_Form input[name="Last_Name]"').val();
        var email = "$('#Email').val()";
            var token = $('#Add_Form input[name="__RequestVerificationToken"]').val();





           function Dawn(data) {


                        $.ajax({

                            type: "POST",
                            url: "Personal",
                            dataType: 'json',
                            data: data,

                            success: function (message) {


                                $('#Greetings').slideDown(900).show().text(message.msg);
                                $('#Greetings2').slideDown(900).show().text('<div><a href="/accounts">Continue</a></div>');


                            },
                            error: function (message) {

                                $('#list').show().html(message.quantity + ' ' + message.total).css("blue");
                            }

                        });
        };

      alert(first_Name + ' ' + last_Name + ' '+  token);
            alert(first_Name + ' ' + last_Name + ' '+  token);

    });
            </script>






            <div class="container">
                <div class="col-md-12"><div class="col-md-6"><h2>Personal Details</h2> </div><div class="col-md-6 text-right">Others here</div></div>
                <div class="row">
                    <div class="col-md-3">


                        <div class="Navigation_Accounts table-bordered">

                        </div>
                    </div>
                    <div vclass="col-md-1">
                    </div>
                    <div class="col-md-8">
                        <form id="Add_Form" action="/Users/Address_Add" method="post">






                            <div class="form-group ">
                                <label class="control-label" for="Title">Title</label>
                                <select class="form-control" id="AddressType" name="AddressType" style="width: 50px;">
                                    <option value="1">Mr</option>
                                    <option value="2">Mrs</option>
                                    <option value="3">Miss</option>
                                    <option value="7">Other</option>
                                </select>
                                <span class="text-danger field-validation-valid" data-valmsg-for="Title" data-valmsg-replace="true"></span>
                            </div>

                            <div class="form-group">
                                <label class="control-label" for="First_Name">First Name</label>
                                <input required class="form-control" maxlength="50" type="text" id="First_Name" name="First_Name" value="" />
                                <span class="text-danger field-validation-valid" data-valmsg-for="First_Name" data-valmsg-replace="true"></span>
                            </div>

                            <div class="form-group">
                                <label class="control-label" for="Last_Name">Last Name</label>
                                <input required class="form-control" maxlength="50" type="text" id="Last_Name" name="Last_Name" value="" />
                                <span class="text-danger field-validation-valid" data-valmsg-for="Last_Name" data-valmsg-replace="true"></span>
                            </div>


                            <div class="form-group">
                                <label class="control-label" for="Gender">Gender</label>
                                <select class="form-control" id="AddressType2" name="AddressType2" style="width: 50px;">
                                    <option value="1">male</option>
                                    <option value="2">female</option>
                                </select>
                                <span class="text-danger field-validation-valid" data-valmsg-for="Gender" data-valmsg-replace="true"></span>
                            </div>




                            <br />
                            <hr />
                            <br />
                            <div class="form-group">
                                <input type="submit" id="Add_Submit" value="Go !" class="btn btn-default" />
                            </div>
                            <br />
                            <hr />
                            <br />
                            <input name="__RequestVerificationToken" type="hidden" value="CfDJ8IPMXGj67c9AsKAqp5ytxNgw3nQRaoxH5ekN2mt67i-rJK0fT7U_EnyJ4pJzXxftBIZpYdFHhoCBJc9bas0yw-HH2d5Ia9Y-XuHwX7SKCLNVGk3-2zkZX6WhAcz4JOW55KiSETnvgedW_yXzU8U2ddI" />
                        </form>
                    </div>
                </div>
            </div>


        </main>
    </div>

    <footer class="border-top footer text-muted">
        <div class="container">
            &copy; 2019 - xxxxx - <a href="/Home/Privacy">Privacy</a>
        </div>
    </footer>


    <script src="/lib/jquery/dist/jquery.js"></script>
    <script src="/lib/bootstrap/dist/js/bootstrap.bundle.js"></script>


    <script src="/js/site.js?v=4q1jwFhaPaZgr8WAUSrux6hAuh0XDg9kPS3xIVq36I0"></script>


</body>
</html>
5
  • Please paste your html code also Commented Jul 23, 2019 at 4:31
  • Could you double check your code for typos? Here, for example: var first_Name2 = $("#Last_Name]").val(); is the ] expected? Also, can you post your HTML code? Commented Jul 23, 2019 at 4:31
  • Could you try something like var last_Name2 = $("input[name*="First_Name]").val(); <---* Commented Jul 23, 2019 at 4:40
  • @kunalverma the brackets are not properly closed Commented Jul 23, 2019 at 5:35
  • @BrunoMonteiro I have updated it, and that was not the problem Commented Jul 23, 2019 at 5:35

1 Answer 1

1

You need to move your variables inside your onclick function. Like this:

$(document).ready(function () {       
    $('#Add_Submit').on("click", function (e) {
        e.preventDefault();
        var last_Name2 =  $("#First_Name").val();
        var first_Name2 = $("#Last_Name").val();

        var last_Name =  $('#Add_Form input[name="First_Name"]').val();
        var first_Name = $('#Add_Form input[name="Last_Name"]').val();
        var email = "$('#Email').val()";
        var token = $('#Add_Form input[name="__RequestVerificationToken"]').val();
        console.log(data);
        alert(first_Name + ' ' + last_Name);
        alert(first_Name + ' ' + last_Name);
        alert(first_Name2 + ' ' + last_Name2);
        Dawn(data);
    });   
})

Also, it is preferable to use .on("click") instead of .click()

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks @Raghuram however its only alert(first_Name2 + ' ' + last_Name2); that works, as the other values are empty. I will wait to see if there are any other inputs before marking it correct
@Ehi I modified the position of quotes. Try the new version. If that does not work, try to give separate id to every element and use $('#elementId').val(); instead of using [input name] tags.
super. It works, but I had to tweak the code a bit, but the changes made worked. thank you
the only thing I dont understand, is that in my previous projects, I always assign the values outside the onclick event and they always worked
Your issue was wrong syntax: var last_Name = $('#Add_Form input[name="First_Name]"').val(); should be var last_Name = $('#Add_Form input[name="First_Name"]').val();. But you will still get null values because variables will be initialized on load, which means they will not have user entered data. If variables are initialized inside on click function, they will have the latest values entered by the user.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.