Function to rearrange values in a group of 5 fields of a form, using jQuery

Asked

Viewed 51 times

0

I have 5 fields of a form and I would like to, through a function, rearrange the values of the form so that the first fields are filled and the last empty ones, according to the values existing in the ascending order.

For example:

HTML:

<input id="campo1" type="text" /><br>
<input id="campo2" type="text" value="uva" /><br>
<input id="campo3" type="text" /><br>
<input id="campo4" type="text" value="laranja" /><br>
<input id="campo5" type="text" /><br>

When calling the function, it would look like this:

<input id="campo1" type="text" value="uva" /><br>
<input id="campo2" type="text" value="laranja" /><br>
<input id="campo3" type="text" /><br>
<input id="campo4" type="text" /><br>
<input id="campo5" type="text" /><br>

Updating: The order of values must obey the id of the fields in ascending order (campo1, campo2...).

1 answer

2


You can do it like this:

var inputs = Array.from(document.querySelectorAll('#campox input'));
var valores = inputs.filter(el => el.value.trim());
inputs.forEach((el, i) => el.value = valores[i] && valores[i].value || '');

jsFiddle: https://jsfiddle.net/x3ormw3y/2/

Basically the steps are:

  • puts all inputs in an array
  • filters the empty elements
  • traverse inputs again using the values of the new array only with inputs filled

In Javascript ES5 could be

var inputs = [].slice.call(document.querySelectorAll('#campox input'));
var valores = inputs.filter(function(el){
    return el.value.trim();
});
inputs.forEach(function(el, i){
    el.value = valores[i] && valores[i].value || '';
});
  • Sergio, your code has 2 problems: if I change the "orange" to the field1, the result would be "grape, orange"; the correct would be "orange, grape"... Another thing is that there are other fields in the form, and your code selects all of them, not just the fields "field1" to "field5".

  • @Davidfernandes ah, so you don’t want to order the fields in alphabetical order but order to not have empty fields in the middle, is that it? Regarding inputs, what is the parent element of these inputs? has some specific class?

  • Oh yes, there’s a id father only for these fields: campox

  • @Davidfernandes would then be: https://jsfiddle.net/x3ormw3y/2/

  • Worked perfectly!

  • @Davidfernandes Great!

  • Sergio, now that I’ve seen that the last two lines don’t work in the mobile browser. It’s like an error and the rest of my script below is ignored. I used your second code and there was no error on the phone. oBG!

  • @Davidfernandes because the first code is modern Javascript (ES6) and only works in more modern browsers.

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.