Concealing a div based on empty textboxes using backbone and javascript

I need assistance with displaying or hiding a div based on the length of text boxes. My project is structured using Backbone, so I am unsure about where to insert the code..

Here is my current code;

<input type="text" id="txtUsername" placeholder="username"><br> <input
type="text" id="txtPassword" placeholder="password">

<div id="results">
  // text here
</div>

Javascript

$('#chooseScan').addClass('hide');
        if ($('#txtUsername').val().length > 0 && $('#txtPassword').val().length > 0) {
            $('#results').removeClass('hide');
            $('#results').addClass('show');
        }

Answer №1

Your code had a few errors that weren't initially visible:

  1. Make sure to include '#' before the id.
  2. To get the length, use $('#txtUsername').val().length.
  3. Ensure you have included the jQuery file reference (if not done already).
  4. Check if it is 'chooseScan' or 'results' for the $('#chooseScan').addClass('hide') line.

Here is the corrected code:

<html>
<head>
 <script type="text/javascript" src="jquery-1.8.2.min.js"></script>
<style type="text/css">
.hide { 
    visibility: hidden;
}
.show {
    visibility: visible;
}
</style>
<script type="text/javascript">
$(document).ready(function() {

     $('#results').addClass('hide');
     $('#txtUsername').bind('input', function() { 

        if ($('#txtUsername').val().length > 0 && $('#txtPassword').val().length > 0) {
            $('#results').removeClass('hide');
            $('#results').addClass('show');
        }
} );

 });

</script>

</head>
<input type="text" id="txtUsername" placeholder="username"><br> 
<input type="text" id="txtPassword" placeholder="password">
<div  id="results">

  // text here</div>

</html>

Answer №2

To connect the keyup event to your textboxes, you can follow this example: DEMO

$(document).ready(function() {    
    $('#usernameInput').bind('keyup', toggleVisibility);
    $('#passwordInput').bind('keyup', toggleVisibility);    
});


function toggleVisibility(){
    if ($('#usernameInput').val().length > 0 && $('#passwordInput').val().length > 0) {
        $('#outputSection').removeClass('hidden');
        $('#outputSection').addClass('visible');
    }
    else {
        $('#outputSection').removeClass('visible');
        $('#outputSection').addClass('hidden');

    }   
}

In addition, there are a few issues with your existing code:

  1. Utilize $('#IDofInputTag') to target elements by their ID
  2. Employ $('#IDofInputTag').val().length to determine the length of their values

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

There seems to be a lack of response from the Foursquare API in Node.js

Seeking guidance on retrieving a photo from a Foursquare venue using Node.js platform. Despite having the correct id and secret, the code is returning an unexpected result. My goal is to obtain the prefix and suffix of the image to properly display it as o ...

Facing an issue with sending data in AJAX Post request to Django View

I have been trying to send data from the frontend to the backend of my website using AJAX. Below is the post request view in my Django views: def post(self, request): id_ = request.GET.get('teacherID', None) print(id_) args = {} ...

Move the internal array pointer forward to the next record in order to apply the insertAfter function within the jquery code

As a new jQuery user, I'm attempting to develop a jQuery function using data provided by PHP. My goal is to arrange DIV elements in order of their values using insertAfter method. However, I seem to be encountering some difficulty in advancing the poi ...

Display a particular div upon clicking a specific link, while concealing the other divs

As a beginner in the world of jQuery and coding, I'm encountering some difficulties that I need help with. My goal is to have the 'Vlogging' link activated and show 'Details 1' when the page loads. Then, upon clicking on either &a ...

Simple method for implementing a fade effect on a React component with raw JavaScript techniques?

I am seeking a way to have my React component smoothly fade in upon being mounted. The component's outermost DIV starts with inline style display:none. Within the componentDidMount() method, I've written the following code: let el = document.que ...

What is the best way to create a Snap.svg map using AngularJS?

I am in the process of creating a web interface for an online board game. My goal is to load a Snap.svg map using Snap.load asynchronously. Once the map is loaded, I intend to attach a watch to a scope property and apply colors to the map based on that pr ...

retrieve information using Python in JavaScript

I am in the process of developing a website using Python, Javascript (JQuery), and AJAX. While I know how to initiate a Python script with Ajax, I am unsure of how to send data back to Javascript from Python. For instance, if there is an error in a form s ...

Implementing SVG in NextJS 13 with custom app directory: A step-by-step guide

Recently, I decided to explore the app directory and unfortunately ran into some issues. One of the main problems I encountered was with image imports. While PNG images imported without any problem, SVG images seemed to break when importing in /app. For i ...

Generating a JavaScript variable linked to a Rails Active Record relationship

I'm trying to implement an active record association in the DOM, but I'm encountering some difficulties. Here is my editor class: .editing .row .col-sm-3 .col-sm-8 .text-left #font-20 .title-font . ...

Cannot seem to get my AJAX code working correctly to show comments

Having some trouble with my comment system code. The PHP part is working fine, comments are being inserted into the table without any issues. However, I am struggling with the Ajax part. The comments are not being displayed unless the page is reloaded. C ...

When attempting to clear a specific word or character, the entire text is cleared instead

Currently, I am utilizing fabric js along with reactjs to incorporate text onto the canvas. While the text is successfully added, I encountered an issue when attempting to clear specific characters or selected words, resulting in the whole text being cle ...

Developed a hierarchical JSON format using a JavaScript array

I am aiming to generate a properly structured nested JSON file from an array, with unique key values. Currently, I can only output the JSON without any nesting. The desired structure to be displayed in the console is : { "Key" : "data1", "header" ...

Is there a way to automatically fill in a MUI textfield in a React Hook form with data retrieved from Firestore?

Utilizing React Hook Forms alongside MUI TextField components has been a productive challenge for me. I've been able to successfully fetch data from Firestore and aim to prefill the form with this retrieved information. Although I am employing useFor ...

How come the 'npm install canvas' command did not generate a JavaScript file as expected?

My venture into the world of node packages has just begun. I recently tried installing canvas to my project using this command: npm install canvas Prior to successfully executing the installation, it was necessary for me to first install gtk and cairo by ...

AngularJS modal behaving oddly when checkboxes are used

My Angular app is available in this plunker. Upon clicking the button, a modal dialog opens displaying a list of items. Two of these items are pre-checked based on conditions set in the checkbox table input. The following function handles pushing and spl ...

React displaying an error indicating that the setTimeout function is undefined?

While attempting to integrate the XTK library with React, I encountered an issue where it kept throwing an error stating that the setTimeout function is not a valid function. Surprisingly, my code appears to be flawless and works perfectly fine when used d ...

Tips for efficiently updating numerous words in text on a webpage powered by AJAX, as well as in select attributes, by implementing a Tampermonkey script

My approach involves translating specific text, words, and terms within an HTML document using a tree walker to target only text nodes: var replaceArry = [ [/View your user account/gi, 'Tu cuenta'], // etc. ]; var numTerms = replac ...

How can we determine if a Node.js application will remain operational?

How is the longevity of a Node.js app determined? For example, consider this code snippet: console.log('Hello World'); In this case, the phrase will be printed and the app will exit immediately. However, with a web server that is actively lis ...

Having trouble debugging the current TypeScript file in VS Code because the corresponding JavaScript file is missing

In my current project using Visual Studio Code version 1.17, I am focusing on debugging the current typescript file. As part of my setup, I have a build task in place which generates a corresponding javascript file structure like so: src/folder1/folder2/m ...

Ensuring the existence of a MySQL database prior to executing a Node.js application

I am currently working on a Node.js/Express application that communicates with a MySQL server using Sequelize. I want to make sure that a particular database is created before the app starts running when using npm start. I think I need to create a one-ti ...