2

I have a form field in html that goes along the lines of:

<form id="tasklist">
  <input type="text" id="name" ...></input>
  ... more form elements here ...
</form>

Now in my jQuery code, I would like to get the value of these form elements, but I am unable to see what I'm doing wrong with the following code:

$(document).ready(function(){
  $("#tasklist").submit(function(){
    alert($("#name").val()); // This does not alert anything on form submit
  });
});

I have made sure all of my html id's are unique, the javascript code is placed at the bottom of the document, in script tags and any other alert placed there works (i.e. alert("hello world"); place before the submit method.

I have seen a few other questions like this on stackoverflow, i.e. (Jquery form field value and Retrieving the Value of an input text field in Jquery) but they do not seem to solve my problem.

Any ideas?

1
  • 1
    +1 for being the one of the few who listen form submit event and not click on the button. Commented Feb 26, 2013 at 14:56

2 Answers 2

2

When a form is submitted, the page reloads. You need to prevent that!

$(document).ready(function(){
  $("#tasklist").on('submit', function(e){
     e.preventDefault();
     alert( $("#name").val() );
  });
});

And close the functions properly!

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

3 Comments

Sorry, I copied an pasted, parts and typed parts in to stackoverflow. The functions are closed properly in my code. Firebug shows no JS errors.
@Husman - It's a rather simple function. If the ID is correct, and jQuery is included, it should work just fine.
It is indeed, in any case the culprit was IE, not the code itself which works fine in Firefox and Chrome.
1

You have some typos : the functions are not closed. It cause JS errors and could stop the script execution.

Try :

$(document).ready(function(){
  $("#tasklist").submit(function(){
    alert($("#name").val()); // This does not alert anything on form submit
  });
});

Update

Basic fiddle exemple : http://jsfiddle.net/UQTY2/28/

2 Comments

Sorry, I made a typo on stackoverflow. It is fixed in my document, firefox console shows no JS errors in my document.
The problem was with IE, not the code which works in firefox and chrome. Thanks anyway.

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.