Concealing information based on the value of a variable

Creating a dynamic price estimator.

I need help writing a jQuery function that can hide or show a specific div element based on the value of a variable.

For example, let's say I have an HTML div with the ID 'Answer':

<div id="answer">Hide Me</div>

$("#answer")...

And a variable called x:

var x = 30

To hide the div using CSS:

#answer{
visibility:hidden;
}

How can I create a function that checks if x is greater than 20 and hides the div accordingly?

I understand there are multiple ways to achieve this and it may not necessarily require jQuery. If there is a different approach using JavaScript alone, please share as I am eager to learn.

Any guidance would be appreciated.

Thank you!

Answer №1

Keep in mind that you have the option to both remove or include a class:

$('#response').removeClass('hidden');
$('#response').addClass('hidden');

However, the most efficient way is to use $('#response').hide(); or $('#response').show();

Answer №2

Run this function with the variable v:

var checkVariable = function(v) {
   var targetElement = $('#answer');
   if (parseInt(v) > 20) {
      targetElement.hide();
   } else {
      targetElement.show();
   }
}

For instance, if the variable is obtained from a selection:

$('#selectId').on('change', function() {
   checkVariable($(this).val());
});

Answer №3

Eliminate the styling with ease by utilizing jQuery

if(y < 10){
 $('#result').remove();
}

Answer №4

Feel free to utilize this option

   $("#solution").hide();

Answer №5

@kapantzak's response seems solid. It's important to separate logic from style, so if you're not planning on using a variable for the element more than once, it may be unnecessary. Here's a revised version:

var checkElement = function(value) {
   var target = $('#answer');
   if (parseInt(value) > 20) {
      target.addClass('hidden');
   } else {
      target.removeClass('hidden');
   }
}

In your CSS, add this rule:

#answer.hidden{
 display: none;
}

Consider that display: none; hides the object completely while visibility: hidden keeps the space occupied by the hidden object.

Answer №6

Learning HTML

<input id="changingValue">
...
<div id="answer">Don't Show Me</div>

CSS (optional if you validate values on page load)

#answer{ display:none;}

JavaScript

var range = 30;
$(function(){
    $("#changingValue").change(function(){
         if(parseInt($("#changingValue").val())<range) { $("#answer").show(); }
         else { $("#answer").hide(); }
    });
});

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

Footer not being pushed down by content in mobile view on page

Hello everyone, Can you assist me with a query, please? My form works perfectly fine in desktop view, but it gets cut off on mobile view and I'm unsure of the reason why. Here is my code: .upload-pic { position: absolute; max-width: au ...

Reduce the size of a webpage by 10%

Have you ever noticed that when you press Ctrl+- on any browser, the page scales down to 90% of its original size? It actually looks nicer at 90%, so I want my webpage to default to opening at 90% instead of 100%. I've tried following common approach ...

Having Trouble with the Spacing Between Navbar and Page Content in Bootstrap?

Let's tackle the issue at hand: Here is the code snippet. A lot of it has been borrowed from examples and tutorials. <!-- Navigation --> <nav class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <!-- Brand a ...

Unable to interpret Python/Django-generated JSON object on client side

I'm encountering an issue while passing a data object from a Python/Django application to the frontend using AJAX in JSON format. Despite everything appearing to be functioning correctly, I am unable to properly parse the JSON object within JavaScript ...

What is the best way to convert the information from a <SelectInput /> component or similar components into another language?

Within my React admin v3 application, When retrieving data from the servers for my entity, I receive a unique identifier called a slug. This slug is a special key that needs to be translated on the client side. Here is an example of my <CallMeBackCre ...

HTML View of JSON Object Hierarchy

Hello, I have been trying various methods but am struggling to figure out how to display the following JSON object as a tree HTML view with ul li items using JavaScript. Can anyone help me with this? [ { "CategoriesModelId": 7, "Name": "Parent ...

Tips for connecting elements at the same index

.buttons, .weChangeColor { width: 50%; height: 100%; float: left; } .weChangeColor p { background: red; border: 1px solid; } .toggleColor { background: green; } <div class="buttons"> <p><a href="#">FirstLink</a></ ...

Can anyone tell me what I might be doing incorrectly when comparing these two timestamps?

I am facing an issue while comparing two timestamps in Angular. Here is the code snippet: public isAuthenticated(): boolean { const token = localStorage.getItem('Fakelife'); const lifetime = new Date().getTime(); const result = life ...

Convert JavaScript objects to strings with JSON strings already included as values

Although this question may seem like a duplicate, I have not been able to find the answer. My issue is with stringifying a JavaScript object that contains JSON strings as values. Here is an example: var obj = {id:1, options:"{\"code\":3,\" ...

Generating a fresh object from an existing object by incorporating updated values using Angular and Ionic version 3

Currently, I am actively working on an Ionic 3 project that utilizes Angular framework. Within my project, I have a JSON object called 'person' which consists of data fields such as name, job, and home. One feature in my app is an Ionic toggle b ...

Ways to identify when a React child element is overflowing

tl;dr How can I create a component that hides overflow and toggles views with a button? For example, the user can initially see tabs 1, 2, and 3 while tabs 4, 5, and 6 are hidden. Clicking a button will hide tabs 1, 2, and 3, and show tabs 4, 5, and 6 with ...

The Json object's size increases exponentially with each subsequent return

There seems to be a strange issue with the PHP file that is causing the JSON objects to duplicate. The first time I run the script, I receive 5 rows, which matches the number of rows in the table. However, on the second run, I get double the results. Wha ...

Eliminating rows from a DataTable through an Ajax request

I have a DataTables table from datatables.net with a custom column containing icons for various actions. One of these actions is deleting a row without reloading the data. I'm looking for a built-in function to remove datatable rows locally after dele ...

Is it possible to retrieve the original array after removing filters in Angular?

Within my component, I have an array that I am filtering based on a search string. The filtering works as expected when the user inputs characters into the search field. However, I am encountering an issue when attempting to display all records again after ...

Text in various styles is layered on top of an image, ensuring that text in one style does not overlap text in another style

Struggling with placing text over an image? Trying to achieve different text styles but ending up with overlapping lines? Here's a snippet of HTML that works with only one text style: <li style="" class="portfolio-content-CV"> <div class ...

What is the best way to retrieve widget options when inside an event?

Creating a custom jQuery widget: jQuery.widget("ui.test",{ _init: function(){ $(this.element).click(this.showPoint); }, showPoint: function(E){ E.stopPropagation(); alert(this.options.dir); } } Initializing the cu ...

Massive HTML Table Containing Rows upon Rows

Currently, I have a server that can provide me with a list of objects in json format, and my goal is to showcase them in a table on the client side. Initially, I thought about dynamically modifying the DOM after receiving data from the server. Building th ...

Error: The function $.get is not recognized when using jQuery with babel-node

Currently, I am executing the code below from a test.js file using babel-node in the command line: babel-node test.js installation of jquery npm i --save jquery test.js: import $ from 'jquery'; $.get("www.google.com"); Upon execution, I en ...

Employing identification as a variable

I'm currently attempting to retrieve the text within a span element that has a class of "link," but I seem to be encountering some issues. <div id="item-0" class="box"> ....... </div> <div id="item-1" class="box"> <p>& ...

Refresh element once AJAX call is completed successfully

Issue Despite a successful AJAX request, I am encountering difficulties updating an element on the webpage. JavaScript Code $(function() { $(".upvote").click(function() { var id = $(this).parent().find("input").val(); $.ajax( ...