Home > Back-end >  Replace all input fields in form with select - keeping the original name attribute of each element w
Replace all input fields in form with select - keeping the original name attribute of each element w

Time:04-08

I have a form with some inputs like this:

<div id="buttons">
  <label>Quantity:</label>
  <input name="quantity_1"  type="text" value="1" />
  <input name="quantity_2"  type="text" value="1" />
  <input type="submit" name="Add" value="Add" id="Add" />
</div>

And a working jquery script, that transforms all these inputs to selects:

$('[name^="quantity_"]').replaceWith('<select name="quantity">'  
        '<option value="1">1</option>'  
        '<option value="2">2</option>'  
        '<option value="3">3</option>'  
        '<option value="4">4</option>'  
        '<option value="5">5</option>'  
        '</select>');

But as you can see, it will replace all names attribute to "quantity" instead of "quantity_1", "quantity_2" and so on (i have not two, but many of them). What i can add to this code, to make it work properly?

CodePudding user response:

Consider the following.

$(function() {
  $('[name^="quantity"]').each(function(i, el) {
    $(el).replaceWith("<select name='quantity_"   (i   1)   "'><option>1</option><option>2</option><option>3</option><option>4</option><option>5</option></select>");
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="buttons">
  <label>Quantity:</label>
  <input name="quantity_1" type="text" value="1" />
  <input name="quantity_2" type="text" value="1" />
  <input type="submit" name="Add" value="Add" id="Add" />
</div>

You need to perform the action on each element, so use .each().

See More: https://api.jquery.com/each/

CodePudding user response:

So, yes, many thanks to Twisty, with a little change i finally got the right version:

$(function() {
  $('input[name^="quantity"]').each(function(i, el) {
    $(el).replaceWith("<select name='quantity_"   ($(el).attr('name').replace("quantity_", ""))   "'><option>1</option><option>2</option><option>3</option><option>4</option><option>5</option></select>");
  });
});

Hope it will also help someone in future!

  • Related