Imagine a list of records (drawn from a database) displayed in a table. On earlier views of the table some rows have been selected or unselected and that status is shown with a empty or filled checkbox at the beginning of each record row as required.
I would like the user to be able to click or unclick those checkboxes, and have that revised state auto-saved in the background without needing to click an additional submit button,m but so far I have not found a clear example of what I think ought to be fairly simple with javascript.
I'm new at Javascript and have not yet figured out how to tap the attributes of a control when passing these to a script. I created a code snippet to show the basics of the problem.
function toggle_select(id) {
// the id number that is passed is the primary key value for the database record
alert('id '+id+' was clicked'); //this part works, but how to pass the new state to this script?
// ?? can the function read if the checkbox has been checked or unchecked?
// if so, then run a background process (ie. php script?) to update that record to the new checked or unchecked state
// ie. $sql="update recordtable set is_selected='YES/NO' where rec_ID=id limit 1";
};
<table>
<tr><th colspan="2">SELECT REQUIRED RECORDS</th></tr>
<tr><td><input type="checkbox" name="is_selected" checked onclick="toggle_select(1)" /></td><td>Record 1</td></tr>
<tr><td><input type="checkbox" name="is_selected" onclick="toggle_select(2)" /></td><td>Record 2</td></tr>
<tr><td><input type="checkbox" name="is_selected" checked onclick="toggle_select(3)" /></td><td>Record 3</td></tr>
<tr><td><input type="checkbox" name="is_selected" checked onclick="toggle_select(4)" /></td><td>Record 4</td></tr>
<tr><td><input type="checkbox" name="is_selected" onclick="toggle_select(5)" /></td><td>Record 5</td></tr>
<tr><td><input type="checkbox" name="is_selected" onclick="toggle_select(6)" /></td><td>Record 6</td></tr>
</table>
The bottom line: The goal is to click the checkbox and boom, the selected/unselected state of that record is saved to the database without requiring a full form submit/page reload.
Did it!
Here is the script that works (like a charm!)
if I form my checkbox inputs like so...(much simpler than I thought!)
Oh, and here is the content of the .php script