简体   繁体   中英

Accessing form elements using jquery and DOM

Here is the form

<form method="post">

    <input type="hidden" name="resulttype" value="Create">              
    <table>
        <tr>
            <td>Name</td>           
            <td><input type="text" id="name" value="Abhishek"/></td>
        </tr>
        <tr>
            <td>User Name</td>
            <td><input type="text" id="username" name="username" value="AbhishekSimion"></td>
        </tr>
        <tr>
            <td>Email</td>
            <td><input type="text" id="email" name="email" value="a@a.com"></td>
        </tr>
        <tr>
            <td>Department</td>
            <td><input type="text" id="department" name="department"></td>
        </tr>
        <tr><td colspan="2"><input type="button" id="button" value="Done!"></td></tr>
    </table>
</form>

here is the Javascript part

var x = document.getElementById("name");
var email = $("input#email").val();  

var dataString = 'name='+ x + '&email=' + email;
$(function() {
$("#button").click(function() {
    callme();
    });
  });
function callme()
{
    alert(dataString);
    var msg = $.ajax({
        type: "POST",
        url: "/temp/AjaxPostSend",
        data: dataString,
        async: false,
        success: function(html){
          alert( "Data Saved: " + msg );
        }
     }).responseText;

}

Why do I get a message " name=null&email=undefined " in my alert box? What is wrong here?

Note: I am using JQuery v1.5.2

At least the email value should work...

In any case, don't create the string manually. Set data to an object containing the values:

data: {name: $('#name').val(), email: $('#email').val()},
// or
data: $('#yourformID').serialize(),

This way, jQuery will take care of proper escaping.

Also note that IDs have to be unique. If you have other elements with the same IDs farther up the page, it won't work. Changes the IDs then.

Update:

The flow of your code is not correct. This part:

var x = document.getElementById("name");
var email = $("input#email").val();  

var dataString = 'name='+ x + '&email=' + email;

will be executed before the page finished loading . That means (a) that the elements are not available yet and (b) even if they were, the user would not have been able to enter any information.

You have to read the values at the time you want to sent the form :

$(function() {
    $("#button").click(callme);

    function callme() {      
        $.ajax({
            type: "POST",
            url: "/temp/AjaxPostSend",
            data: {name: $('#name').val(), email: $('#email').val()},
            success: function(msg){
                alert( "Data Saved: " + msg );
            }
         });
    }

});

Also note that

var msg = $.ajax({...}).responseText;

will not work as the Ajax request is asynchronous . That means callme() will return before the Ajax response is available. The response text is available as argument to the success callback.

Correction: I saw the async: false , but it seemed I had a bit error in my brain;) In this case the above statement would work indeed. But you should avoid synchronous Ajax (should be called Sjax then) calls at it blocks the client.

try this

var myname = $('#name').val()
var mymail = $('#email').val();

DEMO

also you can use like below

data: { name: myname, email: mymail }

var msg = $.ajax({
        type: "POST",      
        url: "/temp/AjaxPostSend",
        data: { name: myname, email: mymail }
        async: false,
        success: function(html){
          alert( "Data Saved: " + msg );
        }
     }).responseText;

UPDATE

try with

<input type="text" id="myname" name="myname" value="Abhishek"/> and then
var myname = $('#myname').val()

for sending date over POST use

 data: $('#yourformID').serialize(),

To get the value of an input using plain JavaScript, you'll have to access the variable called value .

var x = document.getElementById("name").value;

Your second variable should work as expected, however it is possible to omit the input from the selector, since IDs are always unique, and it saves you a few bytes.

var email = $("#email").val();

Also, there is an easier way to send a form with ajax. Serialize the form. Notice data: ...

var msg = $.ajax({
        type: "POST",
        url: "/temp/AjaxPostSend",
        data: $("form").serialize(),
        async: false,
        success: function(html){
          alert( "Data Saved: " + msg );
        }
     }).responseText;

change

var x = document.getElementById("name");
var email = $("input#email").val();  

to

var x = $("#name");
var email = $("#email").val();  

also, this part:

var x = $("#name");
var email = $("#email").val();  
var dataString = 'name='+ x + '&email=' + email;

needs to go before the callme() function call like this:

var dataString;
$(function() {
$("#button").click(function() {
    var x = $("#name");
    var email = $("#email").val();  
    dataString = 'name='+ x + '&email=' + email;
    callme();
    });
  });

Because,

the value in 'x' is an object and not a string and I think the syntax of '$("input#email")' is wrong. Try $(":input[id='email']").val()

Not sure why email is giving you undefined value, but for name it should be like the following:

var x = document.getElementById("name").value;

OR

var x = $('#name').val();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM