skip to Main Content

This is my first question on StackOverflow so I would appreciate any help in both the formating and the explaining of this post! Thank you!

I’ve been trying to finish an assignment about creating a form that takes 4 inputs and turns them into a QR Code, while also saving its data in a simple .txt file.

I found two templates that each manage to do exactly that. Yet when I try to merge them together into a single HTML file it seems to not work.

<!DOCTYPE html>
<html>
<head>
    <title>Contact form</title>
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.4.1/css/all.css"
        integrity="sha384-5sAR7xN1Nv6T6+dT2mhtzEpVJvfS3NScPQTrOxhwjIuvcA67KV2R5Jz6kr4abQsz"
        crossorigin="anonymous">
    <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <style>
        html, body {
            min-height: 100%;
            padding: 0;
            margin: 0;
            font-family: Roboto, Arial, sans-serif;
            font-size: 14px;
            color: #666;
        }

        h1 {
            margin: 0 0 20px;
            font-weight: 400;
            color: #1c87c9;
        }

        p {
            margin: 0 0 5px;
        }
        #qrcode{
            float: left;
        }

        .main-block {
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            background: #1c87c9;
        }

        form {
            padding: 25px;
            margin: 25px;
            box-shadow: 0 2px 5px #f5f5f5;
            background: #f5f5f5;
        }

        .fas {
            margin: 25px 10px 0;
            font-size: 72px;
            color: #fff;
        }

        .fa-envelope {
            transform: rotate(-20deg);
        }

        .fa-at, .fa-mail-bulk {
            transform: rotate(10deg);
        }

        input, textarea {
            width: calc(100% - 18px);
            padding: 8px;
            margin-bottom: 20px;
            border: 1px solid #1c87c9;
            outline: none;
        }

        input::placeholder {
            color: #666;
        }

        button {
            width: 100%;
            padding: 10px;
            border: none;
            background: #1c87c9;
            font-size: 16px;
            font-weight: 400;
            color: #fff;
        }

        button:hover {
            background: #2371a0;
        }

        img.qr-code {
            margin: 100px;
            width: 200px;
            height: auto;
        }

        @media (min-width: 568px) {
            .main-block {
                flex-direction: row;
            }

            .left-part, form {
                width: 50%;
            }

            .fa-envelope {
                margin-top: 0;
                margin-left: 20%;
            }

            .fa-at {
                margin-top: -10%;
                margin-left: 65%;
            }

            .fa-mail-bulk {
                margin-top: 2%;
                margin-left: 28%;
            }
        }
    </style>
</head>

<body>
    <div class="main-block">
        
        <div id="qrcode" class="left-part"></div>
        
        <form id="myForm">
            <h1>Generador de Qr</h1>
            <div class="info">
                <input type="text" id="input1" type="text" name="codigo" placeholder="Codigo">
                <input type="text" name="laboratorio" placeholder="Laboratorio" id="input2">
                <input type="text" name="producto" placeholder="Producto" id="input3">
                <input type="text" name="precio" placeholder="Precio" id="input4">
            </div>
            <p>Principio Activo</p>
            <div>
                <textarea id="principio-activo" rows="4"></textarea>
            </div>
            <button type="button" id="submit-button">Guardar Datos</button>
            <button id="generate" style="margin-top: 5px;">Generar Qr</button>
        </form>
    </div>
    <!-- Script para generar la descarga de datos-->
    <script>
        document.getElementById('submit-button').addEventListener('click', function () {
            // Get the form data
            const codigo = document.querySelector('[name=codigo]').value;
            const laboratorio = document.querySelector('[name=laboratorio]').value;
            const producto = document.querySelector('[name=producto]').value;
            const precio = document.querySelector('[name=precio]').value;
            const principioActivo = document.getElementById('principio-activo').value;

            // Create a text content
            const textContent = `Codigo: ${codigo}nLaboratorio: ${laboratorio}nProducto: ${producto}nPrecio: ${precio}nPrincipio Activo:n${principioActivo}`;

            // Create a blob with the text content
            const blob = new Blob([textContent], { type: 'text/plain' });

            // Create an object URL
            const url = URL.createObjectURL(blob);

            // Create a download link
            const a = document.createElement('a');
            a.style.display = 'none';
            a.href = url;
            a.download = 'form_data.txt';

            // Append the link to the body and trigger the click event
            document.body.appendChild(a);
            a.click();

            // Clean up
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
        });
    </script>

    <!--Script para generar el Qr-->
    <script>
         $(document).ready(function () {
            $('#generate').click(function () {
                const input1 = $('#input1').val();
                const input2 = $('#input2').val();
                const input3 = $('#input3').val(); // Include input3 value
                const input4 = $('#input4').val(); // Include input4 value
                const data = { input1, input2, input3, input4 }; // Create a JSON object

                // Convert the JSON object to a string and generate a QR code
                const jsonStr = JSON.stringify(data);
                const qrCodeUrl = `https://chart.googleapis.com/chart?cht=qr&chl=${encodeURIComponent(jsonStr)}&chs=200x200`;
                $('#qrcode').html(`<img src="${qrCodeUrl}" alt="QR Code">`);
            });
        });
    </script>
</body>
</html>

I tried changing the name variables, rewriting it from scratch yet somehow only one of the buttons works.

2

Answers


  1. The problem happens because when you click on Generar Qr button , the form is submitted and your code for generating the qr will not be excecated, that is the natural behavior of forms.
    to solve that, you have to prevent submitting the form when clicking on Generar Qr button, you can do it using event.preventDefault().

    Here are the modifications required on your code:

    <script>
             $(document).ready(function () {
                $('#generate').click(function (event) {
                    event.preventDefault();
                    const input1 = $('#input1').val();
                    const input2 = $('#input2').val();
                    const input3 = $('#input3').val(); // Include input3 value
                    const input4 = $('#input4').val(); // Include input4 value
                    const data = { input1, input2, input3, input4 }; // Create a JSON object
                    console.log(data);
    
                    // Convert the JSON object to a string and generate a QR code
                    const jsonStr = JSON.stringify(data);
                    const qrCodeUrl = `https://chart.googleapis.com/chart?cht=qr&chl=${encodeURIComponent(jsonStr)}&chs=200x200`;
                    $('#qrcode').html(`<img src="${qrCodeUrl}" alt="QR Code">`);
                });
            });
    </script>
    
    Login or Signup to reply.
  2. When you generate the QR code the page is refreshed, so it does work. you can stop this by adding ‘return false’ to the end of the generator script.

    <!--Script para generar el Qr-->
    <script>
         $(document).ready(function () {
            $('#generate').click(function () {
                const input1 = $('#input1').val();
                const input2 = $('#input2').val();
                const input3 = $('#input3').val(); // Include input3 value
                const input4 = $('#input4').val(); // Include input4 value
                const data = { input1, input2, input3, input4 }; // Create a JSON object
    
                // Convert the JSON object to a string and generate a QR code
                const jsonStr = JSON.stringify(data);
                const qrCodeUrl = `https://chart.googleapis.com/chart?cht=qr&chl=${encodeURIComponent(jsonStr)}&chs=200x200`;
                $('#qrcode').html(`<img src="${qrCodeUrl}" alt="QR Code">`);
    
                return false;
    
            });
        });
    </script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search