Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

201
Views
How to allow javascript form to skip questions without producing text which assumes an answer?

I have created a page with a form for people to complete, which when completed produces a text file of the person's answers.

However I want people to have the option of skipping a question if they don't want to answer it.

The problem with the code below is that if you skip a question it still produces the preceding/following text and spaces.

i.e. if a person doesn't want to answer the question about their age, the below code will still produce text which reads "Age:[space][space]" in the text file.

If someone skips a question how to I stop the text file still producing the above? Ideally I want it to be completely ignored in the text file if the question hasn't been answered.

    // Get the data from each element on the form.
    const name = document.getElementById('txtName');
    const age = document.getElementById('txtAge');
    const email = document.getElementById('txtEmail');
    const country = document.getElementById('selCountry');
    const msg = document.getElementById('msg');
    
    // This variable stores all the data.
    let data = 
        '\r Name: ' + name.value + ' \r\n ' + 
        'Age: ' +age.value + ' \r\n ' + 
        'Email: ' + email.value + ' \r\n ' + 
        'Country: ' + country.value + ' \r\n ' + 
        'Message: ' + msg.value;
    
    // Convert the text to BLOB.
    const textToBLOB = new Blob([data], { type: 'text/plain' });
    const sFileName = 'formData.txt';      // The file to save the data.

    let newLink = document.createElement("a");
    newLink.download = sFileName;

    if (window.webkitURL != null) {
        newLink.href = window.webkitURL.createObjectURL(textToBLOB);
    }
    else {
        newLink.href = window.URL.createObjectURL(textToBLOB);
        newLink.style.display = "none";
        document.body.appendChild(newLink);
    }

    newLink.click(); 
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Create a simple function like this

const fn = (pre, v, post) => v.length? `${pre || ''} ${v} ${post || ''}`;

use it like this

let data = 
        fn('\r Name: ', name.value, ' \r\n ') +
        fn('Age: ', age.value, ' \r\n ') + 
        .... etc
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!