1

There's three input fields inside '.edit'. How to get the value of each one of them using jQuery?

$submit.click(value);      

function value () {
    for (var i = 0; i < 3; i++) {
        var $input = $('.edit').children('input').eq(i).val();
        console.log($input);
    }
}

<div class="edit">
    <h3>Headline</h3>
    <span>Text</span>
    <input type="text" id="one">
    <span>Text</span>
    <input type="text" id="two">
    <span>Text</span>
    <input type="text" id="three">
    <button class="submit">Submit</button>
</div>

Doesn't work. Why? And also is it possible to set a default value: .val() || 'unknown'?

6

2 Answers 2

5

You need to loop through the inputs under .edit on submit click and obtain each input value using $(this)

$('.submit').click(function(){

  $('.edit').find('input[type=text]').each(function(){

  console.log($(this).val());

});
    
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="edit">
    <h3>Headline</h3>
    <span>Text</span>
    <input type="text" id="one" value="default">
    <span>Text</span>
    <input type="text" id="two">
    <span>Text</span>
    <input type="text" id="three">
    <button class="submit">Submit</button>
</div>

2
  • Thank you. Is it possible to set a default value? Somenthing like || 'default' in vanilla?
    – Artem Z
    Mar 12, 2016 at 10:50
  • you can use the html value attribute , check the edit... Or with jquery val as $("#element").val('default'); called on page load.
    – KAD
    Mar 12, 2016 at 10:52
2

$('.submit').click(function() {
  $('.edit').find('input').each(function(index, value) {

    console.log("index is " + index + " " + "value is " + $(this).val())


  })

})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="edit">
  <h3>Headline</h3>
  <span>Text</span>
  <input type="text" id="one" value='1'>
  <span>Text</span>
  <input type="text" id="two" value='2'>
  <span>Text</span>
  <input type="text" id="three" value='3'>
  <button class="submit">Submit</button>
</div>

You can use .each()

Description: Iterate over a jQuery object, executing a function for each matched element.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.