Conceal the <p> tag if the content inside is either "0" or blank

I'm currently working on a basic calculator project and I've hit a roadblock. I need to hide certain elements based on conditions. The code snippet with explanations is provided below.

function calculateArea() {
  var length = document.getElementById("length").value;
  var width = document.getElementById("width").value;
  var area = length * width;
  var rate = 7.8;
  var total = area * rate;
  document.getElementById("result").innerHTML = total;
}


$('#width').keypress(function(event) {
  if (((event.which != 46 || (event.which == 46 && $(this).val() == '')) ||
      $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
    event.preventDefault();
  }
}).on('paste', function(event) {
  event.preventDefault();
});

$('#length').keypress(function(event) {
  if (((event.which != 46 || (event.which == 46 && $(this).val() == '')) ||
      $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
    event.preventDefault();
  }
}).on('paste', function(event) {
  event.preventDefault();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <span>Length:</span>
  <input class="calculation-field" type="text" id="length" name="length" placeholder="e.g. 120">
</div>

<div>
  <span>Width:</span>
  <input class="calculation-field" type="text" id="width" name="width" placeholder="e.g. 2.8">
</div>

<button onclick="calculateArea()">Calculate</button>

<!--- Display the following elements only if the area value (with id=wynik) is greater than 0 and is filled --->
<p id="condition">Result:</p>
<p type="text" id="result"></p>

As you can see, I need to conditionally show these two "p" elements based on the id=wynik value being filled and greater than 0. How can I achieve this?

Answer №1

If you want to keep them hidden until something is written on them, and the value on it is greater than 0, the most effective way to do so is by hiding them by default using the following code:

<p id="demand" style="display: none;">Result is:</p>
<p type="text" id="result" style="display:none;"></p>

Once you start writing HTML to them, you can reveal them using jQuery:

function calculateValue() {
  var p = $("#area").val();
  var h = $("#height").val();
  var k = p * h;
  var e = 7.8;
  var s = k * e;
  document.getElementById("result").innerHTML = Math.trunc(s);
  if(s>0){
    $("#demand").show();
    $("#result").show();
  }
}

You can test a functional version of your code in this JSFiddle:

https://jsfiddle.net/0arcxze4/2/

Answer №2

Instead of simply checking the value, why not try this:

if($(this).val() == '0' || $(this).val() == '' ) {
  $('#wynik').hide();
}

You can use jQuery to show the HTML element initially hidden with CSS. It seems like you're showing them after calculating, which is perfectly fine.

But if you prefer a more challenging approach, you can do it this way:

$('#wynik').css('display', function(i, v) {
  return ($(this).text() == '0' || $(this).text() == '') ? 'none' : 'block'
});

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

Implementing Express.js allows for the seamless casting of interfaces by the body within the request

I have created a similar structure to ASP.NET MVC and uploaded it on my github repository (express-mvc). Everything seems fine, but I am facing an issue with casting the body inside the request object to match any interface. This is what I am aiming for: ...

Different methods for dynamically altering the style attribute

Here's some code I wrote: <html> <head> <style> .containerTitle { background-color:silver; text-align:center; font-family:'Segoe UI'; font-size:18px; font-weight:bold; height:30px; } ...

Generate a CSV file using Javascript

I am working with an HTML table (table id='testTable') and a button in the HTML code: <button id="btnExport" onclick="javascript:xport.toCSV('testTable');">CSV</button> There is also JavaScript code involved: toCSV: func ...

NodeJS guide: Enabling cross-domain access for web services

Currently, I am developing a nodejs server and facing the challenge of needing to access additional services through ajax from a different domain. Can anyone provide guidance on how to bypass the cross-domain restriction within nodejs code? Please note th ...

Discovering documents using the outcome of a function in mongoose

Hey there, I have a scenario with two schemas known as user and driver, both containing latitude and longitude attributes. My goal is to search the database for nearby drivers based on the user's current location (latitude and longitude) using a custo ...

Struggling to Align NAV buttons to the Right in React Framework

My current Mobile Header view can be seen here: https://i.stack.imgur.com/CcspN.png I am looking to achieve a layout similar to this, https://i.stack.imgur.com/pH15p.png. So far, I have only been able to accomplish this by setting specific left margins, ...

Monitoring and analyzing conversations within a chat platform

In our Node.JS chat system, we have implemented three channels for message delivery: one using the mqtt protocol, another using the third-party service pusher channels, and a third using a message fetch service based on the gcm protocol. Messages sent from ...

Exploring Jasmine and Karma for testing Angular 5 HTTP requests and responses

I am brand new to the concept of Test-Driven Development (TDD) and I am currently in the process of debugging a complex Angular 5 application for the company I work for. The application is functioning without any issues, but now I need to incorporate test ...

Sending input values from textboxes to the Controller

I currently have the following code snippets: Home Controller: public IActionResult Index() { return View(); } public ActionResult Transfer() { string path = @Url.Content(webRootPath + "\\SampleData\\TruckDtrSource.json&q ...

Tips for incorporating a dynamic basePath into your NextJS project

For my new app, I am trying to include the groupID in the URL before the actual path, such as 'https://web-site.com/1/tasks'. The NextJs docs mention a basePath that is set at build time and cannot be modified. With numerous routes in my current ...

Can you please enlighten me on how to obtain the HTML for the selected area of the cursor in Tiptap?

I've successfully created a customized text editing tool using tiptap/react. My question is, how can I retrieve the html or json of a selected area when I highlight text with the cursor? For instance, if I have a custom tag 'say-as' within ...

Using jQuery to create an array variable and Passing the array to a different PHP page

Although I have managed to create a function that works perfectly for me, I am facing an issue with the jQuery part at the bottom. Currently, I am only able to trigger an alert message and not store the data as a real variable. The function is functionin ...

Steps for dynamically expanding a textarea in Selenium WebDriver when the element path is constantly changing

I am facing a challenge with resizing a textarea that has a dynamic xpath. I am unable to use the following JavascriptExecutor commands: (JavascriptExecutor) driver.executeScript("document.getElementById('someID').setAttribute('rows', ...

Difficulty accessing `evt.target.value` with `RaisedButton` in ReactJS Material UI

My goal is to update a state by submitting a value through a button click. Everything works perfectly when using the HTML input element. However, when I switch to the Material UI RaisedButton, the value isn't passed at all. Can someone help me identif ...

Obtain the rotational value in 3D CSS using JavaScript by extracting it from the matrix3d()

My element has been 3D transformed in the following way: .foo { transform: rotateX(-30deg) rotateY(35deg); } Now, I am looking to retrieve these values using JavaScript. Extracting the 3D matrix is simple: var matrix = $('.foo').css('tr ...

Is there a significant distinction between value and defaultValue in React JS?

React's homepage features the final illustration (A Component Using External Plugins) with a textarea: <textarea id="markdown-content" onChange={this.handleChange} defaultValue={this.state.value} /> While typing, the ...

Having trouble displaying DIV Content with CSS through printing

<script type="text/javascript"> function PrintElem(elem) { Popup($(elem).html()); } function Popup(data) { var mywindow = window.open('', 'mydiv', 'height=550,width=750'); mywindow.doc ...

Issues with Three.js raycaster intersectObjects

I am currently working on a 3D scatter plot where spheres are used to represent the points, and I am attempting to show information from the points when they are clicked. After researching various answers on this platform, I believe I am moving in the righ ...

Are there any solutions for the malfunctioning v8 date parser?

The V8 Date parsing functionality is not functioning properly: > new Date('asd qw 101') Sat Jan 01 101 00:00:00 GMT+0100 (CET) I have attempted to use a delicate regular expression like the following: \d{1,2} (jan|feb|mar|may|jun|jul|a ...

Can a JavaScript framework be created to ensure all browsers adhere to standards?

As someone who isn't an expert in JavaScript, I wonder if it's feasible to create a comprehensive embeddable JavaScript file that ensures all browsers adhere to standards. Could there be a compilation of known JavaScript hacks that compel each br ...