Ask your JavaScript questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

Parse <input type = "checkbox" id = "CX"> to array, sort and re-display results JavaScript

  • SOLVED

TASK: (http://verlager.com) Populate myArray from form containing input fields with checkbox inputs. But the problem is the ID's #C1 to #C3 aren't natively storable in the myArray "paid" var. Can we fix that? Then sort the array myArray to sortedObjs. Then use sortedObjs to display the new values in the sorted order.



<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script src = "https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>

HTML:

<form id = "reg" >
<input type = "checkbox" id = "C1" /> <input type = "text" id = "P1" /> <input type = "text" id = "Y1" />
<input type = "checkbox" id = "C2" /> <input type = "text" id = "P2" /> <input type = "text" id = "Y3" />
<input type = "checkbox" id = "C3" /> <input type = "text" id = "P2" /> <input type = "text" id = "Y3" />
</form>

JAVASCRIPT:

// STEP 1 LOAD ARRAY from screen ID's

<script>

myArray = [];

for (n = 1; n <= 3; n++) {

myArray.push ({

paid: $('#C' + n).val(), // Doesn't work, needs attention.
name: $('#P' + n).val(),
rate: $('#Y' + n).val()

);
}}

// STEP 2 Sort myArray [works perfectly]

const sortedObjs = _.orderBy(myArray, 'name', 'asc');

console.log(Object.values(sortedObjs));

document.getElementById("reg").reset();


// STEP 3 populate the form with sorted values from sortedObjs

let g = 0;

sortedObjs.forEach((item, g) => {
let n = g + 1;

$('#C' + n).val(item.paid); // Doesn't work, needs attention.
$('#P' + n).val(item.name);
$('#Y' + n).val(item.rate);

});

alert ("Player list is sorted!");

}

</script>

Answers (1)

2018-11-16

Rainner Lins answers:

Checkboxes usually don't have a value, they have a "checked" state that is either true or false. You could convert it to 1 or 0 for sorting purposes.

You could use this to get the value:


$('#C' + n).prop('checked') ? 1 : 0


And this to set it:


$('#C' + n).prop('checked', item.paid)


More info in prop() here:

http://api.jquery.com/prop/