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

1

I have 5 fields of a form and I would like, through a function, to rearrange the values of them by having the first fields filled and the last ones empty, according to the existing values in 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 the values must obey the id of the fields in ascending order (field1, field2 ...).

    
asked by anonymous 14.09.2016 / 15:54

1 answer

1

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: link

Basically the steps are:

  • puts all inputs in an array
  • filters the empty elements
  • run the inputs again using the values of the new array only with the 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 || '';
});
    
14.09.2016 / 16:01