86

I am using a jquery template to dynamically generate multiple elements on the same page. Each element looks like this

<div id ="DynamicValueAssignedHere">
    <div class="something">Hello world</div>
    <div class="formdiv">
        <form name="inpForm">
            <input type="text" name="FirstName" />
            <input type="submit" value="Submit" />
        </form>
    </div>
</div>

I would like to use Jquery to process the form on submit. I would also like to revert the form values to their previous values if something should go wrong. My question is How can I get the value of input box using Jquery? For example, I can get the value of the div with class "something" by doing

var something = $(#DynamicValueAssignedHere).children(".something").html();

In a similar fashion, I want to be able to retrieve the value of the textbox. Right now, I tried

var text = $(#DynamicValueAssignedHere).children(".formdiv").findnext('input[name="FirstName"]').val();

but it doesn't seem to be working

João Pimentel Ferreira
  • 14,289
  • 10
  • 80
  • 109
  • 4
    For once, plain javascript might be easier: `$('input')[0].form.FirstName.value` will access the field's value – cnlevy Jan 14 '15 at 23:54

8 Answers8

163

You have to use value attribute to get its value

<input type="text" name="FirstName" value="First Name" />

try -

var text = $('#DynamicValueAssignedHere').find('input[name="FirstName"]').val();
Dipak
  • 11,930
  • 1
  • 30
  • 31
  • 8
    @curiouspanda: Just a tip. If the "name" values are unique, you don't need to use $('#DynamicValueAssignedHere'). Just go directly using $('input[name="FirstName"]').val(). I still prefer using ids to deal with components. – davidbuzatto Jul 25 '12 at 16:39
  • 3
    @davidbuzatto - Name values are not unique. Only the ID for the outermost div is unique. Dipaks solution worked though. –  Jul 25 '12 at 16:53
  • Here's some info and a fiddle http://dipaksblogonline.blogspot.in/2018/05/get-form-fields-value-using-jquery.html – Dipak May 20 '18 at 13:09
60

It can be much simpler than what you are doing.

HTML:

<input id="myField" type="text" name="email"/>

JavaScript:

// getting the value
var email = $("#myField").val();

// setting the value
$("#myField").val( "new value here" );
Henrik Andersson
  • 45,354
  • 16
  • 98
  • 92
davidbuzatto
  • 9,207
  • 1
  • 43
  • 50
  • 1
    I cant use an ID for the field because my page can contain multiple forms with the same elements (I am using jquery repeater templates) –  Jul 25 '12 at 16:39
  • @curiouspanda: Ok, so you can do this using Dipaks aproach. Even using the repeater templates, I think that you can work with unique ids, maybe setting a prefix for each field set component id. – davidbuzatto Jul 25 '12 at 16:45
  • @curiouspanda do dynamic IDs have something in common? – Ram Jul 25 '12 at 16:47
  • this should be the answer. much cleaner. – laycat Mar 22 '14 at 03:39
  • how about if I shoulf get the value from a form in an other page? – Lina Dec 15 '14 at 11:42
10

An alternative approach, without searching for the field html:

var $form = $('#' + DynamicValueAssignedHere).find('form');
var formData = $form.serializeArray();
var myFieldName = 'FirstName';
var myFieldFilter = function (field) {
  return field.name == myFieldName;
}
var value = formData.filter(myFieldFilter)[0].value;
Lucas Moeskops
  • 5,445
  • 3
  • 28
  • 42
3

$("form").submit(function(event) {
    
      var firstfield_value  = event.currentTarget[0].value;
     
      var secondfield_value = event.currentTarget[1].value; 
     
      alert(firstfield_value);
      alert(secondfield_value);
      event.preventDefault(); 
     });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" >
<input type="text" name="field1" value="value1">
<input type="text" name="field2" value="value2">
</form>
Milan Krushna
  • 317
  • 2
  • 5
  • 1
    While this code snippet may solve the question, [including an explanation](//meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, as this reduces the readability of both the code and the explanations! – Blue Aug 12 '16 at 14:33
1

if you know the id of the inputs you only need to use this:

var value = $("#inputID").val();
Severiano
  • 1,083
  • 3
  • 25
  • 54
1
var textValue = $("input[type=text]").val()

this will get all values of all text boxes. You can use methods like children, firstchild, etc to hone in. Like by form $('form[name=form1] input[type=text]') Easier to use IDs for targeting elements but if it's purely dynamic you can get all input values then loop through then with JS.

Alex Reynolds
  • 6,264
  • 4
  • 26
  • 42
1

You can get any input field value by $('input[fieldAttribute=value]').val()

here is an example

displayValue = () => {

  // you can get the value by name attribute like this
  
  console.log('value of firstname : ' + $('input[name=firstName]').val());
  
  // if there is the id as lastname
  
  console.log('value of lastname by id : ' + $('#lastName').val());
  
  // get value of carType from placeholder  
  console.log('value of carType from placeholder ' + $('input[placeholder=carType]').val());

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="formdiv">
    <form name="inpForm">
        <input type="text" name="firstName" placeholder='first name'/>
        <input type="text" name="lastName" id='lastName' placeholder='last name'/>
        
        <input type="text" placeholder="carType" />
        <input type="button" value="display value" onclick='displayValue()'/>
        
    </form>
</div>
noone
  • 6,168
  • 2
  • 42
  • 51
0

You can try these lines:

$("#DynamicValueAssignedHere .formdiv form").contents().find("input[name='FirstName']").prevObject[1].value
veben
  • 19,637
  • 14
  • 60
  • 80