89

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

1
  • 4
    For once, plain javascript might be easier: $('input')[0].form.FirstName.value will access the field's value
    – cnlevy
    Commented Jan 14, 2015 at 23:54

8 Answers 8

165

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();
3
  • 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. Commented Jul 25, 2012 at 16:39
  • 3
    @davidbuzatto - Name values are not unique. Only the ID for the outermost div is unique. Dipaks solution worked though.
    – user1625066
    Commented Jul 25, 2012 at 16:53
  • Here's some info and a fiddle dipaksblogonline.blogspot.in/2018/05/…
    – Dipak
    Commented May 20, 2018 at 13:09
62

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" );
5
  • 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)
    – user1625066
    Commented Jul 25, 2012 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. Commented Jul 25, 2012 at 16:45
  • @curiouspanda do dynamic IDs have something in common?
    – Ram
    Commented Jul 25, 2012 at 16:47
  • this should be the answer. much cleaner.
    – laycat
    Commented Mar 22, 2014 at 3:39
  • how about if I shoulf get the value from a form in an other page?
    – Lina
    Commented Dec 15, 2014 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;
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>

1
  • 1
    While this code snippet may solve the question, including an explanation 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
    Commented Aug 12, 2016 at 14:33
1

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

var value = $("#inputID").val();
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.

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>

0

You can try these lines:

$("#DynamicValueAssignedHere .formdiv form").contents().find("input[name='FirstName']").prevObject[1].value

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.