0

This is probably something basic but I'm strugle with it. I construct a binary string for the 12 mounths of the year, using 12 checkboxes as:

const checkboxes = [...document.querySelectorAll('input[type=checkbox]')];
function RegMD() {
    document.getElementById("season").textContent =
      checkboxes.reduce((a, b) => a + (b.checked ? 1 : 0), "");
}

and the html code for it:

<input type="checkbox" id="jan"><label>january</label><br>
<input type="checkbox" id="feb"><label>february</label><br>
<input type="checkbox" id="mar"><label>march</label><br>
...

<br>
<p id="season"></p>
<br>
<button type="button" onclick="RegMD()">Register My Data</button>

The above code generate for me the string and display it. These checkboxes are inputs on a form where I have other input fields as well:

<form id="register_form" method="post" role="form" action="">
    <input autofocus="" id="firstname" name"firstname" placeholder="First Name" type="text" required />
    <textarea id="Address" name="Adress" placeholder="No Address" type="text" rows="3" cols="30"></textarea>
    <select id="country" name="country" required>
            <option selected>Choose</option>
            <option value="10">Germany</option>
            <option value="11">Poland</option>
            <option value="12">United Kingdom</option>
    </select>
    <button type="submit">Submit My New Entry</button>
</form>  

which I send through POST send to a database using:

<?php

if (isset($_POST["firstname"])){

try {
    //open the database
    $pdo = new PDO('sqlite:db/users.db');

    $firstname = $_POST["firstname"]; 
    $Address = $_POST["Address"];
    $country = $_POST["country"];
    
$data = [
    'firstname' => $firstname,
    'Address' => $Address,
    'country' => $country,
];

$sql="INSERT INTO details (firstname, Address, country) VALUES (:firstname, :Address, :country)";

$stmt= $pdo->prepare($sql);
$stmt->execute($data);

$pdo = NULL;
} catch(PDOException $e) {
    print 'Exception : ' .$e->getMessage();
}}
?>

My request is, how can I get the generated string

<p id="season"></p>

and include it in the POST method to be sent into the database? The string now is generated on a separate button click and how I need to declare it to be picked up and sent together with the other information through POST method. Thank you.

############################### Edit. ###############################

by changing the textContent into value in my script:

document.getElementById("season").textContent = checkboxes.reduce((a, b) => a + (b.checked ? 1 : 0), "");

into

document.getElementById("season").value = checkboxes.reduce((a, b) => a + (b.checked ? 1 : 0), "");

and putting a input field for the result:

<input type="text" id="season" name="season" value="" required >

I managed using the button onclick event to display my generated string into a input field and than using SUBMIT to be sent into my database. BUT I receive another issue as you can see it in my printscreen: here all recorded value goes as "value" and the firts 0's are trimmed from my string. Initial textContent are not worked.

I found few solutions to do something before on submit as it is: here and here but i can't make it work.

my full code is:

<!doctype html>
<html>
<head>
  <script type='text/javascript' src="js/jquery.min.js"></script>
</head>
<body>
<form id="register_form" method="post" role="form" action="#">
<table border=0>
<tr><td>First Name: <td><input autofocus="" id="firstname" name="firstname" placeholder="First Name" type="text" required />
<tr><td>Address: <td><textarea id="Address" name="Address" placeholder="No Address" type="text" rows="3" cols="30"></textarea>
<tr><td>Country: <td><select id="country" name="country" required>
            <option value="" selected >Choose</option>
            <option value="10">Germany</option>
            <option value="11">Poland</option>
            <option value="12">United Kingdom</option>
    </select>
<tr><td>Season: <td>
    <input type="checkbox" id="jan"><label>january</label><br>
    <input type="checkbox" id="feb"><label>february</label><br>
    <input type="checkbox" id="mar"><label>march</label><br>
    <button type="button" onclick="RegMD()">Generate season string</button>

<tr><td>Season: <td><input type="text" id="season" name="season" value="" required >

<tr><td><input type="submit" value="Add New Record" >
</table>

<script>
const checkboxes = [...document.querySelectorAll('input[type=checkbox]')];
function RegMD() {
    document.getElementById("season").value = checkboxes.reduce((a, b) => a + (b.checked ? 1 : 0), "");
}
</script>
</form>

<?php
IF (isset($_POST['firstname'], $_POST['country'], $_POST['season'])      // checking texfield and combobox if are empty
   AND !empty($_POST['Address']))                                        // checking textarea if is empty
{ 
try {
    $firstname = $_POST["firstname"]; 
    $Address = $_POST["Address"];
    $country = $_POST["country"];
    $season = $_POST["season"];
    
$data = ['firstname' => $firstname,
         'Address' => $Address,
         'country' => $country,
         'season' => $season,
        ];

$pdo = new PDO('sqlite:db/users.db');
$pdo -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO details (firstname, Address, country, season) 
                     VALUES (:firstname, :Address, :country, :season)";
$stmt = $pdo->prepare($sql);
$stmt -> execute($data);
$pdo = NULL;
} catch(PDOException $e) {print 'Exception : ' .$e->getMessage();}
} 
?>
</body>
</html>

How can I make it work?

########################### Second Edit. ###########################

the value from my database for the string insert was fixed by changing the column declararion of my database from INTEGER to VARCHAR as was proposed by ADyson.

How can i move the javascript to be generated and submited on SUBMIT?

Nico Haase
  • 11,420
  • 35
  • 43
  • 69
  • 3
    Put the value into a hidden field in the form (additionally to putting it into the `

    ` element if you want).

    – ADyson Dec 14 '22 at 11:13
  • Does that code work? `if (isset($_POST["firstname"])){` should never trigger, `name"firstname"` is missing a `=` – brombeer Dec 14 '22 at 11:28
  • Are your checkboxes inside form element? Change temporary form method to "get" so you can see what's sent to php. Or print out print_r($_REQUEST); to see what form is sending. – MilanG Dec 14 '22 at 12:48
  • @MilanG OP doesn't want to send the checkbox values directly...read the question again. `Change temporary form method to "get" so you can see what's sent to php`...that's really not necessary. A far better way, without needing to interfere with the code, would be to simply look in the Network tool in the browser's Developer Tools. You can see the payload of any request through that (and lots of other useful information). Your suggestion sounds like the sort of primitive debugging I might have resorted to when using Internet Explorer 5 or something...long long ago. The world moved on thankfully – ADyson Dec 14 '22 at 12:51
  • @brombeer , yes there is a "=" and whit it is working – Szabolcs Horvath Dec 14 '22 at 14:18
  • 1
    Re your update: by any chance did you define the "season" field as numeric in your database, instead of string or varchar? – ADyson Dec 25 '22 at 09:24
  • @ADyson, of course you are right again, it was set as INTEGER (12), with varchar works like a charm. Thank you. Can you guide through the onsubmit as well? – Szabolcs Horvath Dec 25 '22 at 10:33
  • 1
    Please never add answers to the question itself. Rather post the answer **as an answer** – Nico Haase Dec 25 '22 at 15:07

2 Answers2

2
  1. Instead of having a p element <p id="season"></p>, you can use a readonly input field, inputs are picked up by the form and sent automatically: <input id="season" readonly>.
  2. To have it calculated automatically you can instead of a click event handler add an submit event handler to the form element. Alternatively if you wish to display the the updates to the user you can use the change event on the checkboxes. And update the value of the input: document.getElementById("season").value = ...

P.S. It's better to register event handlers in JS rather than in the HTML: element.addEventListener('change', updateValue);

Tuhis
  • 138
  • 8
  • thje

    element is there to see the script is working, i dont need it to be visible, so i can go with your proposal to use , but my problem is thet this value is generated by a button click, so i need to transfer it somehow on submit. Ill try first you idea with the and see how i manage it

    – Szabolcs Horvath Dec 14 '22 at 14:15
1

Thank you guys for all your advises, finally i solved it as you giuded me with: onsubmit="return RegMD();"

<form id="register_form" method="post" role="form" action="#" onsubmit="return RegMD();">

and

<input type="hidden" id="season" name="season" value="">