0

I have a few dynamically builded forms and belonging ID's. The ID's look like id='send_1'... id="send_2"...

Gernerally it will be posted only one form but I don't know how many forms will be created so that I need one general jQuery-function that does the work. At the moment the code below works just for one ID. So I thought it must be possible to loop within a selector with something like while or foreach if something like that exists?

$(document).on("submit", "#paypal", function(e){
    e.preventDefault();

    if ( /\,/.test( $('#send_1').val() ) ) {
        $('#send_1').val($('#send_1').val().replace(/,/g, '.'));
    } else {
        alert('no comma');
    }
    return  false;
});

So how can I do this foreach #send_X when I do not know how many forms will exist and even don't want to write hundred times the same code just changing the _x?

If there is someone who could help I really would appreciate.

John
  • 261
  • 2
  • 6
  • 16

3 Answers3

2

if you need loop solution see below code might be help

$(document).on("submit", "#paypal", function(e){
    e.preventDefault();

    var i=1;
    $( "li" ).each(function( index ) {                   
        if ( /\,/.test( $('#send_'+i).val() ) ) {
            $('#send_'+i).val($('#send_'+i).val().replace(/,/g, '.'));
        } else {
            alert('no comma');
        }
        i++;
    });
    return  false;
});

or try changing

  $('#send_1').val()

with

  $( "input[id^='send']" ).val();

might work i am not sure

see this link

Nikunj Chotaliya
  • 802
  • 8
  • 19
0

You could use a for loop like this (I've stripped out your if statement to simplify):

$(document).on("submit", "#paypal", function(e) {
  e.preventDefault();

  var n = $("form").length; // get the number of forms

  for (var i = 1; i <= n; i++) {
    var form = $("#send_" + i); // gives you the form object        
  }
});

Demo here

Hope this helps.

Ash
  • 2,108
  • 2
  • 17
  • 22
0

You can add data-x-id for submit buttons and after get id from:

$(document).on("submit", "#paypal", function(e){
    e.preventDefault();
    var id = $(e.target).attr('data-x-id');
    // for minimal work with dom
    var element = $('#send_'+id);
    var value = element.val();
    if ( /\,/.test( value ) ) {
        element.val(value.replace(/,/g, '.'));
    } else {
        alert('no comma');
    }
    return  false;
});