Rohith Kumar
Rohith Kumar

Reputation: 13

How to get the values from form fields using dynamic created id or id as an variable using jQuery

I have created a small application where I dynamically created form elements and their id using jQuery. Later for form validation i need to get the fields of the the entries. I am able to get the values of the input fields but not able to the file, radio and other select fields. Here is the small code only for file

var x = 1;    
function validate() {
  for(i=0;i<10;i++) {
    var filename = $('input[id="f'+ i +'"]').val().replace(/.*(\/|\\)/, '');
    alert(filename);
  }
  
  return false;
}

$(document).ready(function() {   
  $("#fd").on("click",".but",function() {
    $(this).parent().remove();
  });

  $("#c").click(function() {       
    var txt = "<div class='di'><input type='file'id='f"+ x +"'><input type='text' id='t"+ x +"'><button class='but' id='d'> "+ x +" Button </button></div>";
    x++;
    $("#fd").append(txt);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="c">Create Element</button>
<br> <br>
<form action="temp.php" onsubmit="return validate()" method="GET">
  <div id="fd">
    <button id="d">First Element</button>
    <input type="submit" name="submit">
  </div>
</form>

How to retrieve data using dynamically created id for form elements.Consider for 10 elements Thanks for the help.

Code image

Upvotes: 1

Views: 1160

Answers (1)

Tushar Walzade
Tushar Walzade

Reputation: 3809

You can add the same class to all the inputs & use jQuery to get their values as below -

var inputs = $(".className");    // your class name
// iterate over the inputs any way you want
for(var i = 0; i < inputs.length; i++){
    alert($(inputs[i]).val());
}

or this way -

var valueArray = $('.className').map(function() {
    return this.value;
}).get();

Upvotes: 2

Related Questions