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...).
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".
– Sam
@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?
– Sergio
Oh yes, there’s a
id
father only for these fields:campox
– Sam
@Davidfernandes would then be: https://jsfiddle.net/x3ormw3y/2/
– Sergio
Worked perfectly!
– Sam
@Davidfernandes Great!
– Sergio
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!
– Sam
@Davidfernandes because the first code is modern Javascript (ES6) and only works in more modern browsers.
– Sergio