Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill in a form with jQuery

Tags:

I am trying to use jQuery to fill in a form with some default values.

The form is contained in a div which has an id. In fact every element has an id, I did so just to be able to quickly select every piece of the form using $("#id") syntax.
Here is the form:

<div id="panel" style="position: absolute; left: 190px; top: 300px; width: 400px; height: 300px; border: medium groove brown; background: none repeat scroll 0% 0% black; z-index: 100; color: white;"> <form id="form_coord_0">   X <input type="text" style="height: 25px; font-size: 10px;" size="2" name="X" id="coordX_0"/>   Y <input type="text" style="height: 25px; font-size: 10px;" size="2" name="Y" id="coordY_0"/>   <input type="button" id="edit_0" value="M"/>   <input type="button" id="remove_0" value="-"/>   <input type="button" id="add_0" value="+"/>   <input type="button" id="go_0" value="go!"/>   </form> </div>   

I need to set the coordX_0 text field with some value, let's say: 123.

I thought I could do

$("#coordX_0").text.value = 123;   

But it doesn't seem to work. Any hint?

like image 607
nick2k3 Avatar asked Jan 18 '12 17:01

nick2k3


People also ask

What are jQuery forms?

The jQuery Form Plugin allows you to easily and unobtrusively upgrade HTML forms to use AJAX . The main methods, ajaxForm and ajaxSubmit , gather information from the form element to determine how to manage the submit process.


2 Answers

You can use the val() function to set input values

$("#coordX_0").val(123);   

Incidentally, your original code could be made to work by setting value property on the actual, underlying dom element. You access the dom element by indexing your jQuery results:

$("#coordX_0")[0].value = 123;   
like image 85
Adam Rackis Avatar answered Sep 19 '22 19:09

Adam Rackis


All the answers are the exact same so I thought I'd post something different:

var inputs_to_values = {     'coordX_0' : 'some value',     'coordY_0' : 'some other value',     'edit_0'   : 'N',     'remove_0' : '_',     'add_0'    : '-',     'go_0'     : 'stop?' }; $('#form_coord_0').find('input').val(function (index, value) {     return inputs_to_values[this.id]; }); 

You can pass .val() a function, whatever is returned from the function for each element will be the new value:

A function returning the value to set.

this is the current element.

Receives the index position of the element in the set and the old value as arguments.

Source: http://api.jquery.com/val

The above code expects that each input will have a property in the inputs_to_values object so you can convert the ID of the input to the new value for that input.

Here is a demo: http://jsfiddle.net/zYfpE/

like image 42
Jasper Avatar answered Sep 21 '22 19:09

Jasper