Retrieving value of form fields in Jquery - javascript

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?

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!

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/

Related

Pass name in jQuery form submission

I do not know why the following line will not function properly:
$('form[name="updateNetwork"]').unbind('submit').submit();
I can submit my form with
$("form").unbind('submit').submit();
However doing so will not pass the name attribute of the form which my backend code must identify in order to properly process the form submission. Any assistance would be greatly appreciated.
Thanks
It seems that you have only one form in your page, and that the only reason you're trying to select it with the name attribute in jQuery is so that jQuery will send the name of the form to the server.
Well, that won't work. Once you get a reference to your form via jQuery, it doesn not matter which selector you had used. If what you want is to send a name parameter to your backend code with the form name, use a hidden input inside the form:
<input type="hidden" name="form-name" value="updateNetwork" />
Then, you can get a reference to the form any way you want. The best one, as stated by #anvlasop, is to give your form an id attribute.
EDITED
You were creating the jQuery form object in a wrong way. If you have this:
<input type="submit" name="updateNetwork" />
then you can't do this:
$('form[name="updateNetwork"]).submit();
I assume that you're calling this method, submit(), inside the event handler of the submit event. Don't do that! What you should do, is to only canll preventDefault if there is an error in the validation, and let the form be sent otherwise:
//Never do this:
$('form').bind('submit', function(e) {
var valid;
//code to validate
e.preventDefault();
if (valid) $('form').unbind('submit').submit();
});
Do this:
$('form').bind('submit', function(e) {
var valid;
try {
//code to validate
} catch (error) {
valid = false;
}
if (!valid) e.preventDefault();
});
This also will prevent the sending of the form is there is an exception during validation.
You can give an id to your form. Try something like this html code:
<form id='form_id'>
//your form elements here...
</form>
Then, with jQuery you can have a reference to the form like this:
$("#form_id").unbind('submit').submit();

.val() and .text() don't work?

I want to email div contents via php and form tag. I have 2 divs with these classes:
.simpleCart_items
.simpleCart_total
I want to fetch contents from these divs and insert their contents in inputs or textareas, then submit the form to my php file.
I wrote this JQuery code:
$('#shopform').submit(function(){
var items = $('.simpleCart_items').text();
var tprice = $('.simpleCart_total').text();
$('#itemsinfo').val(items);
$('#totalprice').val(tprice);
});
and these are my inputs:
<textarea id="itemsinfo" style="width:320px; height:160px"></textarea>
<input type="text" id="totalprice"/>
but it doesn't work. The contents didn't move to the input tags.
It must be something else in your HTML or script that you are showing us because when I set up a simple test using your code, it works fine here: http://jsfiddle.net/jfriend00/7q6DP/.
This works perfectly fine for me (in Chrome, Firefox, Safari and IE):
HTML:
<button id="submitForm">Submit</button>
<div class="simpleCart_items">simpleCart items text</div>
<div class="simpleCart_total">simpleCart total</div>
<textarea id="itemsinfo" style="width:320px height:160px"></textarea><br>
<input type="text" id="totalprice"/>
Javascript (after page is loaded):
$('#submitForm').click(function(){
var items = $('.simpleCart_items').text();
var tprice = $('.simpleCart_total').text();
$('#itemsinfo').val(items);
$('#totalprice').val(tprice);
});
Please show the rest of your code and HTML.
The things to check are:
Are there any javascript errors showing in the error console or in the debugger console?
Are you initializing your event handlers after the page has loaded?
Do any javascript errors show in the debug console when you press the submit button?
Is your submitForm event handler getting called? If you set a breakpoint or put an alert in their, does it get hit?
Can you set a breakpoint in your submit handler and see what's happening with the values of items or tprice?
Make sure your class names don't have the leading period on them when you put them in your HTML. It should be class="simpleCart_items", not class=".simpleCart_items".
Your code works just fine when I put it in a page:
http://jsfiddle.net/Guffa/krYQh/
When you click the submit button, the fields are populated with the data. (I added a return false in the submit event handler just to keep the form from posting.)
Some possible errors in your code:
You have used class=".simpleCart_items" instead of class="simpleCart_items".
The form doesn't have id="shopform".
You have use the ids shopform, itemsinfo or totalprice on any other elements.
I guess you should use ".html()" instead of ".text" something like below.
$('#shopform').submit(function(){
var items = $('.simpleCart_items').html();
var tprice = $('.simpleCart_total').html();
$('#itemsinfo').html(items);
$('#totalprice').val(tprice);
});
I suppose you should use .innerHTML instead of .text()
You should be able to use the .val() to get the value for the text areas instead of using .text().
Try using alert(items); before you set the div's contents just to make sure you are actually getting data.

Dropdown javascript / jquery form validation debugging help needed

I have the following jsfiddle setup:
http://jsfiddle.net/xCCA2/
Basically when a the form is submitted, the size select dropdown is validated to make sure a selection has been made. If a valid size has been selected then the form is posted.
If an invalid selection is made, then an alert box "An invalid size has been selected" should popup.
Please can I get help debugging this.
Nb: there will be many forms on a page, and would prefer to uses classes rather than id's also there is some commented out html, where the form has been set a class, this works but anything within the form becomes clickable, which I do not want. Only the button should trigger the validation.
Thanks
try this
$(".wq").live( "click", function () {
alert("test");
if($("select").val()!="")
alert("not empty");
else{
alert("select a val");
return false;
}
// $(this).submit();
});
http://jsfiddle.net/xCCA2/4/
Look here
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
Add
<script type="text/javascript"
src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.8.1/jquery.validate.min.js"></script>
and required to the select
<select required
DEMO HERE

Adding submit event on form prevents submit parameter from being included in HTTP POST

Just what the question title says. I'm using SpringMVC, but that's irrelevant really. I just need to be able to pass the submit button name=value along with the rest of the form parameters for validation and control purposes. Example below for clarification:
The HTML I'm using:
<form action='somepage.htm' method='post'>
<input name='somename' value='bob' />
<input type='submit' name='mybutton' value='click me' />
</form>
The JavaScript (with jQuery) I'm using:
$('form').submit(function() {
$('input[type="submit"]', this).attr('disabled','disabled');
return true;
}
And so the HTTP POST request looks like this without the JavaScript event binding:
somepage.htm?somename=bob&mybutton=click%20me
And with the bound event, it excludes the button parameter as such:
somepage.htm?somename=bob
I need to be able to disable the buttons and still send the button value to the server for processing.
Thanks!
SOLUTION:
The code I actually used to solve this problem is:
$(document).ready(function() {
$('input[type="submit"]').click(function() {
var clone = $(this).clone();
$(clone).attr("type","hidden");
$(this).attr('disabled','disabled');
$(clone).appendTo($(this).parents('form')[0]);
return true;
});
});
And in case anyone was wondering, pressing Enter on a field in the form does in fact trigger the click event on the first submit button in the form!
Disabled inputs cannot be submitted.
http://www.w3.org/TR/html4/interact/forms.html#h-17.12
So maybe the way to go is to add a hidden element <input type='hidden' value='foo' name='bar'/> to stimulate the validation methods on the other end.
I think, if the submit button is clicked, then it's values will also be submitted, like rest of the form.

Clear default values using onsubmit

I need to clear the default values from input fields using js, but all of my attempts so far have failed to target and clear the fields. I was hoping to use onSubmit to excute a function to clear all default values (if the user has not changed them) before the form is submitted.
<form method='get' class='custom_search widget custom_search_custom_fields__search' onSubmit='clearDefaults' action='http://www.example.com' >
<input name='cs-Price-2' id='cs-Price-2' class='short_form' value='Min. Price' />
<input name='cs-Price-3' id='cs-Price-3' class='short_form' value='Max Price' />
<input type='submit' name='search' class='formbutton' value=''/>
</form>
How would you accomplish this?
Read the ids+values of all your fields when the page first loads (using something like jquery to get all "textarea", "input" and "select" tags for example)
On submit, compare the now contained values to what you stored on loading the page
Replace the ones that have not changed with empty values
If it's still unclear, describe where you're getting stuck and I'll describe more in depth.
Edit: Adding some code, using jQuery. It's only for the textarea-tag and it doesn't respond to the actual events, but hopefully it explains the idea further:
// Keep default values here
var defaults = {};
// Run something like this on load
$('textarea').each(function(i, e) {
defaults[$(e).attr('id')] = $(e).text();
});
// Run something like this before submit
$('textarea').each(function(i, e){
if (defaults[$(e).attr('id')] === $(e).text())
$(e).text('');
})
Edit: Adding some more code for more detailed help. This should be somewhat complete code (with a quality disclaimer since I'm by no means a jQuery expert) and just requires to be included on your page. Nothing else has to be done, except giving all your input tags unique ids and type="text" (but they should have that anyway):
$(document).ready(function(){
// Default values will live here
var defaults = {};
// This reads and stores all text input defaults for later use
$('input[type=text]').each(function(){
defaults[$(this).attr('id')] = $(this).text();
});
// For each of your submit buttons,
// add an event handler for the submit event
// that finds all text inputs and clears the ones not changed
$('input[type=submit]').each(function(){
$(this).submit(function(){
$('input[type=text]').each(function(){
if (defaults[$(this).attr('id')] === $(this).text())
$(this).text('');
});
});
});
});
If this still doesn't make any sense, you should read some tutorials about jQuery and/or javascript.
Note: This is currently only supported in Google Chrome and Safari. I do not expect this to be a satisfactory answer to your problem, but I think it should be noted how this problem can be tackled in HTML 5.
HTML 5 introduced the placeholder attribute, which does not get submitted unless it was replaced:
<form>
<input name="q" placeholder="Search Bookmarks and History">
<input type="submit" value="Search">
</form>
Further reading:
DiveintoHTML5.ep.io: Live Example... And checking if the placeholder tag is supported
DiveintoHTML5.ep.io: Placeholder text
1) Instead of checking for changes on the client side you can check for the changes on the client side.
In the Page_Init function you will have values stored in the viewstate & the values in the text fields or whichever controls you are using.
You can compare the values and if they are not equal then set the Text to blank.
2) May I ask, what functionality are you trying to achieve ?
U can achieve it by using this in your submit function
function clearDefaults()
{
if(document.getElementById('cs-Price-2').value=="Min. Price")
{
document.getElementById('cs-Price-2').value='';
}
}

Categories