Displaying the appropriate DIV element based on the value entered by the user

I am encountering some difficulties...

I have an <input> field. Depending on the input, one of the various <div> elements should be displayed. For now, it's just a text (e.g. "Your plan contains less than 1500 kcal!"), but later, the div elements will be blocks with images, buttons, etc.

I have come across some ideas using jQuery, but since I am new to it, I find it hard to understand. So, I tried using the if-function and changing the style from none to block.

What am I missing? The div doesn't seem to appear... As a beginner in JavaScript, any tips you have, please explain it as though to a complete novice :)

Thank you everyone!

HTML

<body style="background-color:#000000">

<form>
    <p>
        <label for=bedarf> Mein Bedarf </label>
        <input type="bedarf" name="bedarf" id="bedarf" placeholder="2345">
        <button class="button1" type="button" id="berechnen" onclick="planholen()" > Plan anzeigen </button><br><br><br>
</form>

<div class="anzeige" id="erster" ><p>Dein Plan enthält weniger als 1500 kcal!</p></div>
...
<div class="anzeige" id="dreizehnter" ><p>Dein Plan enthält weniger als 3900 kcal!</p></div>

</body>

CSS

<style>

label {
    width: 100px;
    display: inline-block;
    font-family: Arial;
    color: #ffffff;
}

input {
    width: 120px;
    height: 25px;
    text-align: center;
    font-family: Arial;
    font-size: 14px
}

...

JS

<script>

function planholen() {
    var a = document.getElementById("erster");
    var b = document.getElementById("zweiter");
    ...
    var m = document.getElementById("dreizehnter");

    var val = parseInt(document.getElementById("bedarf"));

    if (val < 1500) { a.style.display = "block"; } else
    ...
    if (val < 3900) { m.style.display = "block"; } 

</script>

Answer №1

Check out my updated version below to see if it makes sense to you. Don't worry if it seems overwhelming at first, it will become enjoyable again soon :)

<!doctype html>
<html lang="en>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Your diet-Plan</title>
<style type="text/css">
form {
margin-bottom: 2rem;
}

label {
width: 100px;
display: inline-block;
font-family: Arial;
color: #fff;
}

input {
width: 120px;
height: 25px;
text-align: center;
font-family: Arial;
font-size: 14px;
}

.button1 {
width: 130px;
height: 25px;
position: absolute;
left: 250px;
top: 4px;
}

button {
background-color: #ddca07; /* Green */
border: none;
color: white;
height: 30px;
width: 50px;
padding: 2px 10px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 20px;
margin: 4px 2px;
-webkit-transition-duration: 0.4s; /* Safari */
transition-duration: 0.4s;
cursor: pointer;
}

button {
background-color: black;
color: white;
border: 1px solid #ddca07;
width: 140px;
height: 25px;
font-size: 16px;
font-style: bold;
}

button:hover {
background-color: #ddca07;
color: black;
}

.anzeige {
font-family: Arial;
color: #fff;
}

.anzeige:empty {
display: none;
}
</style>
</head>
<body style="background-color:#000000">
<form id="diat">
<label for=bedarf>Mein Bedarf</label>
<input type="text" name="bedarf" id="bedarf" placeholder="2345">
<button class="button1" type="submit">Plan anzeigen</button>
</form>
<div class="anzeige" id="anzeige"></div>

<script>
function planholen( event ) {
event.preventDefault();
var bedarf = parseInt( document.getElementById('bedarf').value ) || 0;
var bedarfGerundet = Math.ceil( bedarf / 100 ) * 100;
var anzeige = document.getElementById('anzeige');
if( bedarf > 0 ) {
anzeige.innerHTML = 'Dein Plan enthält weniger als ' + bedarfGerundet + ' kcal!';
}
else {
anzeige.innerHTML = '';
}
}

document.getElementById('diat').addEventListener('submit', planholen);
</script>
</body>
</html>

I adhered to your requirements as much as possible but made a few additions for better functionality.

  1. I included
    .anzeige:empty { display: none; }
    in your CSS to simplify the logic for hiding the div. Simply empty the div to hide its content.
  2. I retained the original input name as bedarf for future reference.
  3. I assumed the div should be emptied when no input is provided.
  4. I used JS to insert the text dynamically to reduce the initial DOM size.
  5. Changed the function execution from click to submit for accessibility (better usability).
  6. Kept some German phrases as per your original text.

Your existing code had some issues:

  1. var val = parseInt(document.getElementById("bedarf");
    is missing a closing parenthesis
  2. Multiple messages were displayed if the button was clicked multiple times, which may not be intended.
  3. The logic for submitting on return key press was missing.
  4. The formatting of
    if (val < 1500) { a.style.display = "block"; } else
    could be improved for readability.

Hope this explanation helps!

Answer №2

Please see the attached demo versions for your reference.

  <!DOCTYPE html>
  <html>
  <head>
  </head>
  <body>
      <div style="border:solid 1px #ccc; padding:15px; display:block;">
          <div>
              <label>Code:</label>
              <div><input id="code" name="value" /></div>
          </div>
      </div>
      <p>
          <input type="button" value="Submit" id="btn" onclick="getCode(this)">
      </p>
      <div class="display" id="first" style="display:block;">
        <p>Your code is valid!</p>
      </div>
      <div class="display" id="second" style="display:block;">
        <p>Your code is invalid!</p>
      </div>
  </body>
  <script>
      function getCode(element) {
          if(document.getElementById('code').value < 1500){
            document.getElementById('first').style.display = 'none';
          }
          if(document.getElementById('code').value < 2000){
            document.getElementById('second').style.display = 'none';
          }
      }
  </script>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to protect passwords internally via URL and AJAX?

During my time at a previous company, we had an internal website that required a password to be entered at the end of the URL in order to view it. I suspect this was done using AJAX, but I am unsure. Even if AJAX was used, I do not know how to code it myse ...

Steps for triggering a function when the 'Enter' key is pressed in a TextInput in a React Native application

I'm currently working on creating a Search Bar feature. I would like the user to input text into the TextInput field, and when they press 'Enter', I want it to trigger my function. <TextInput //when the user presses Enter, call the functi ...

Step-by-step guide on achieving 100% height for the <main> element in a Material UI drawer demo

I have a question regarding the Material UI drawer. In my project, I am trying to change the background color of the main tag. However, the main tag's height is restricted to the content inside. Check out this link for reference Setting the height t ...

Separate a string using commas but disregard any commas inside quotation marks

Similar Question: JavaScript code for parsing CSV data There is a string that looks like this: "display, Name" <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3d49584e497d49584e49135e5250">[email protected]</a> ...

Generating dynamic forms using JSON Schema in Angular 8 can greatly streamline the form creation process

Struggling with generating dynamic forms from JSON Schema in Angular 8, I stumbled upon a couple of libraries. One seemed outdated with its last commit around 2 years ago, while the other appeared to be a more recent fork of it for Angular 8. The first li ...

Querying MongoDB with Mongoose to find objects in an array based on a specific date stored

I am currently working on constructing a mongoose query to retrieve records that match a specific date. It seems like the query is functioning properly, but I'm not getting any results displayed because the date stored in my array of objects is a stri ...

Quick tip on closing an Angular-ui modal from a separate controller

I am currently using Angular-ui to display a modal with a form inside. Here is the code snippet: app.controller('NewCaseModalCtrl', ['$http', '$scope','$modal', function ($http, $scope, $modal, $log) { $scope.ite ...

By using .innerHTML to create an element, the validation of HTML form fields can be circumvented

After inserting a form field with standard HTML validation constraints (pattern & required), using the .innerHTML property does not trigger validation. While I understand the difference between creating an element with .innerHTML and document.createElement ...

Data cannot be transferred to a child element unless it has been initialized during the definition phase

Passing an array data from parent to child component has brought up some interesting scenarios: parent.component.html: <child-component ... [options]="students" > </child-component> Status I: Setting the array on definition ...

Programmatically setting focus in Ionic

In my Ionic and Angular component, I am attempting to programmatically set focus after the page has loaded. Here is the code: item.component.html: <ion-row> <ion-col col-5> <ion-item > <ion-label&g ...

Error in executing Javascript function

Below is a Javascript function I created for expanding and collapsing content: function showAns(inp){ var hide="#hideAns"+inp; var show="#showAns"+inp; var ansdiv ="#ans"+inp; $(hide).click(function(){ $(ansdi ...

Replicate the styling of CSS class A and apply it to class B

Let's take a look at some code: <button id="test" class="ui-state-hover" value="Button"> In Context: I'm utilizing the JQuery UI CSS class ui-state-hover on an HTML button to ensure it always appears as if it's being hovered over. H ...

Tips for implementing ::before and ::after pseudo-elements within an anchor tag

Can you provide guidance on adding ::before pseudo-element inside an anchor tag? https://i.sstatic.net/tojNE.jpg ...

403 Forbidden error occurs when AJAX value %27 is triggered

Stack Overflow has seen a multitude of inquiries related to apostrophes in form fields, particularly concerning unencoded values. An insightful post sheds light on the limitations of using encodeURIComponent(str) for handling apostrophes and suggests crea ...

Javascript auto submission fails to execute following the completion of the printer script

As someone new to javascript, I have a question. I have a function called sendToQuickPrinter() that prints correctly, but after it finishes executing, I need to automatically submit a form to return to my "cart.php" page. I feel like I'm almost there, ...

How can React useEffects avoid an infinite loop when using setData()?

const [resourceType, setResourceType] = useState("posts"); const [data, setData] = useState(""); useEffect(() => { console.log("use effects called: " + resourceType); fetch(`https://jsonplaceholder.typicode.com/${resourceType}`) .then((result ...

Steps for sorting items from a list within the past 12 hours

I'm currently working with Angular and I have data in JSON format. My goal is to filter out items from the last 12 hours based on the "LastSeen" field of the data starting from the current date and time. This is a snippet of my data: { "Prod ...

The environmental variables stored in the .env file are showing up as undefined in Next.js 13

I am having trouble accessing the environment variables stored in my .env.local file within the utils folder located in the root directory. When I try to console log them, they show as undefined. console.log({ clientId: process.env.GOOGLE_ID, clien ...

Creating a like and dislike button using Jquery's ajax functionality

Hey everyone, I'm currently working on implementing a like and dislike button similar to Facebook's on my website. I have a list of posts displayed using PHP loops and I want a single button to change color to blue if liked and remain the default ...

React Native displaying identical path

Is there a way to dynamically change routes in React Native when a button is pressed? Inside my SplashContainer component, I have the following method: handleToSignUp = () => { console.log("Running handleToSignUp") this.props.navigator.push({ ...