Skip to content Skip to sidebar Skip to footer

How To Find A Sibling Element's Value Using Jquery Upon Click

I'm trying to find the value of the userid and password in the below HTML using the following jQuery code, but it doesn't return any value. What am I doing wrong?
var userid = $("#userid").val();
var pass   = $("#password").val();

Solution 2:

Just do:

$.post('/login', $('#login').serialize(), function() {});

in place of your $.ajax call :), the .serialize() takes all the form inputs' values and pass them to the server, encoded for you as well :)


Solution 3:

You have quite a few issues so here's the corrected code with notes:

jQuery

$(function() {
// same as document.ready
    $('#login').submit(function(event){            
    // runs whenever the form is submitted - either enter or submit button is clicked
        event.PreventDefault();
        // since the form is submitted via ajax you wil want to keep the page from changing
        alert('user id is: '+$('#userid').val());
        // no need to reach back through the DOM with .parent() use the ID its the fastest, also you get input values with .val()
        $.ajax({
            type:"POST",
            url:"/login",
            data: $('#login').serialize()
            // serialize() creates an object of all the form data based on the name attribute and values - very clean
        });
    });
});

HTML

<div id='mainpane'>
    <form id='login' method='post' action=''>
        <p>User Id:<input id='userid' type='text' name='userid'/></p>
        <p>Password:<input id='password' type='text' name='password'/></p>
        <p><input id='submit' type='submit' name='Submit' value='Submit'/></p>           
    </form>
    <div id="message"></div>
    <p>Not a member? <a href="user-signup.html">Signup</a></p>
</div>

Inputs are self closing.


Solution 4:

you try this code

 $(document).ready(function() {
        $('#login').delegate('input#submit','click',function(){

            alert('user id is: '+$(this).parent().parent().find('#userid').val());
            var request = $.ajax({
                type:"POST",
                url:"/login",
                data: {userid:$('#userid').val(), password:$('#password').val()}
                });

            });
        });

Post a Comment for "How To Find A Sibling Element's Value Using Jquery Upon Click"