0

I do not know why I cannot get access to the input text when the code does not have any error.

<form action="#">
                <table width="80%" align="center">

                    <tr>
                        <td>Write your name</td>
                        <td><input type="text" name="yourName" placeholder="Name" /></td>

                        <td><input type="button" value="Submit" id="sendName"/></td>
                    </tr>
                </table>

            </form>
            <p />
            <div id="nameResult"></div>

and the js (jQuery):

$(document).ready(function(){

    $('#sendName').click(function(){
            $(document).ready(function(){

                var tag = $('#yourName').val();

                $('<p>Name ' + tag + '</p>').appendTo('#nameResult');

            });
    }); 

})

The output is always undefined. I do not know what I am doing wrong.

4
  • 1
    You realize the input has no ID, it has a name ? Commented Apr 18, 2015 at 22:26
  • you had not defined id for you input but trying to access the value using id i.e. #yourName in JS script Commented Apr 18, 2015 at 22:29
  • 1
    Why on earth are you calling $(document).ready inside the click event? Commented Apr 18, 2015 at 22:29
  • Put the listener on the form's submit handler as the form can be submitted without clicking the button. Commented Apr 18, 2015 at 22:33

1 Answer 1

1

You are calling nameas if it is an id using #.

Change this

<input type="text" name="yourName" placeholder="Name" />

to this, in which the input control has an id defined:

<input type="text" id="yourName" name="yourName" placeholder="Name" />

If you prefer to stick to name and do not want to define an id, then you can do this as well:

var tag = $('input[name="yourName"]').val();
Sign up to request clarification or add additional context in comments.

2 Comments

@user6527926 please see the update, you can also just use this var tag = $('input[name="yourName"]').val(); in your jquery
I will no worries, I have to wait 10 mins to do it... :) Thanks again

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.