skip to Main Content

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?

2

Answers


  1. Chosen as BEST ANSWER

    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="">
    

    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);

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search