When there is no value in the input, the function will not be triggered

I need some assistance with my website development project. I want to implement a feature where, if the user enters input but doesn't submit anything, instead of triggering the function togglePopup(), a different function called togglePopup2() will be activated. How can I achieve this functionality? Below is the code snippet I am currently working with:

<form  autocomplete="off" >
            <input style="border: 2px solid #222; border-radius: 6px;" type="text" id="lname" name="lname" maxlength="10"><br><br><br>
            <input style="border: none; border-radius: 6px; color: ivory; text-shadow: 0px 10px 20px; #222;background: dodgerblue; padding: 15px; font-size: 15px;" value="Submit environment name" type="button"  onclick="togglePopup()">
          </form><script>
              var x;
document.querySelectorAll('input')[1].addEventListener("click", ()=>{
  x = document.querySelector('input').value;
})
          </script> 

Currently, when the button is clicked after entering input, the togglePopup() function is triggered. I would like to modify this behavior so that the function only runs when there is text in the input field. If no text is entered, I want the alternative function togglePopup2() to run instead. What steps should I take to make this happen?

Answer №1

Give this a shot:

let userInput;
 document.querySelectorAll('input')[1].addEventListener("click", () => {
   userInput = document.getElementById('lname').value;
   if (userInput !== '') {
     openPopup()
   } else {
     openSecondPopup()
   }
 })

 function openPopup() {
   console.log('togglePopup');
 }

 function openSecondPopup() {
   console.log('togglePopup2');
 }
<form autocomplete="off">
  <input style="border: 2px solid #222; border-radius: 6px;" type="text" id="lname" name="lname" maxlength="10"><br><br><br>
  <input style="border: none; border-radius: 6px; color: ivory; text-shadow: 0px 10px 20px; #222;background: dodgerblue; padding: 15px; font-size: 15px;" value="Submit environment name" type="button">
</form>

Answer №2

const changeButtonColor = ()=>{
  document.querySelector('button').style.backgroundColor = "green";
}
const resetButtonColor = ()=>{
  document.querySelector('button').style.backgroundColor = "red";
}
document.querySelector('form').onsubmit = (e)=>{
  e.preventDefault();
  console.log(document.querySelector('input').value.trim() === "");
  if(document.querySelector('input').value.trim() === ""){
    resetButtonColor();
  } else {
    changeButtonColor();
  }
};
input{
  border: 2px solid #222;
  border-radius: 6px;
  margin: 5px 0;
}

button{
  border: none;
  border-radius: 6px;
  color: ivory;
  text-shadow: 0px 10px 20px;
  background: dodgerblue;
  padding: 15px;
  font-size: 15px;
  margin: 5px 0;
}
<form  autocomplete="off" action="#" method="post">
  <div>
    <input type="text" id="lname" name="lname" maxlength="10">
  </div>
  <div>
    <button type="submit">Submit environment name</button>
  </div>
  <div id="result"></div>
</form>

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

Harness the power of multiple backgrounds with just one CSS style!

I'm exploring a way to incorporate multiple images as backgrounds into my website design. For instance, having a car image on the index page and a notepad image on the about me page. My attempt involved using the following code: body { back ...

Access the video content on Instagram by utilizing the oembed endpoints

THE SCENARIO For the past 9 months, I've had a piece of jQuery ajax code that has been functioning without any issues. However, in the last couple of weeks, it seems to have encountered some problems. This particular code utilizes Instagram's e ...

Before invoking the .load() method, it's important to verify if the element is present on

I am currently utilizing jQuery's .load() method to dynamically modify page content. My goal is to verify if the content I intend to load actually exists. Using an example from the jQuery documentation: $( "#new-projects" ).load( "/reso ...

Having trouble sending a function as a prop to a child component in React

Something odd is happening, I'm confident that the syntax is correct, but an error keeps popping up: Error: chooseMessage is not a function // MAIN COMPONENT import React, { useState } from 'react' export default function LayoutMain(prop ...

How can I transfer information from an HTML file (using the ejs template engine) to Node.js?

Currently, I am working on my own project using a combination of Node.Js (Express), MongoDB, JavaScript/jQuery, and HTML with EJS as the template engine. So far, I have some understanding of how to send data from the Node.js router to views and how to sen ...

Summing up various results from promises [Protractor]

On my webpage, I have set up two input text boxes and a label. My aim is to extract the numbers from these elements, sum up the numbers in the text boxes, and then compare the total with the number in the label. Does anyone know how I can achieve this? He ...

How can I transfer an array from a servlet to HTML using jQuery?

As I parse an uploaded XML file with the dom, the generated string combines the hostname and osname values separated by a , delimiter. The variable s holds this string which is then sent back to HTML using the response.getWriter object obj. However, instea ...

Guide on storing images in a designated folder using CodeIgniter

My code is located in view/admin_view2.php <?php echo form_open_multipart('home_admin/createBerita'); ?> <div class="form-group" > <label class="control-label">upload foto</label> <inpu ...

Utilizing Async and await for transferring data between components

I currently have 2 components and 1 service file. The **Component** is where I need the response to be displayed. My goal is to call a function from the Master component in Component 1 and receive the response back in the Master component. My concern lies ...

Is it recommended to place JavaScript/CSS at the bottom of an HTML document?

I am currently utilizing jQuery Mobile, and at the moment, my <head> section looks like this: <head> <meta charset="UTF-8"> <meta name="viewport" content="initial-scale=1, maximum-scale=1"> <title>help</title> <link ...

Exploring new options to deduct time from Kendo UI timepickers without relying on Javascript

My current project involves an Asp.net MVC 4 application that includes a Time entry screen. This screen utilizes various Kendo controls and Razor Html helpers to enhance the user experience, such as: @(Html.Kendo().TimePickerFor(m => m.StartTime).Name( ...

what is the best way to center list items in material ui?

I have been attempting to align the list items (checkbox, text, and buttons) within a Material UI list in the center, but all my attempts have been unsuccessful. Is there anyone who knows how to resolve this issue? Your help would be greatly appreciated! h ...

Data Malfunction Leads to Failure of Ajax POST Request in Client-Side Operation

I am facing an issue where my Ajax POST calls are failing when I attempt to assign complex JavaScript objects to the [data] key/value pair after using JSON.stringify() for serialization. Could anyone advise on what additional ajax call configuration is re ...

Guidance on incorporating static files with Spring MVC and Thymeleaf

I'm seeking guidance on how to properly incorporate static files such as CSS and images in my Spring MVC application using Thymeleaf. Despite researching extensively on this topic, I have not found a solution that works for me. Based on the recommenda ...

module vue/ref-transform cannot be located

I recently started working on a project in vue.js and had everything running smoothly (homepage). However, I encountered an error after installing bootstrap-vue using the following commands: $ yarn add bootstrap bootstrap-vue. $ npm install bootstrap boots ...

To achieve smoother transitions when concealing content, ensure the divs are programmed to

I have successfully implemented code that removes a div and animates the content inside to create a sliding effect. However, I am facing an issue where the divs below seem to jump up and I am looking for a way to make this transition smoother. Here is the ...

Incorporating a transparent icon onto an HTML background

I'm struggling to place a transparent white envelope icon on a green background. I don't understand why it's not working, especially when the telephone icon worked fine. Side Question.: Any recommendations for how to add something above the ...

VueJS: Preloading data prior to and following component initialization

VueJS is a new technology for me, and I'm currently working on a component that needs to retrieve data from an API before loading the corresponding route. The component should only load once the data is fetched. Additionally, after the component is cr ...

Toggle visibility of column in table using cookies

I was looking to store user preferences for shown/hidden columns in the browser using cookies, so that the table layout wouldn't reset upon page refresh. Fiddle : http://jsfiddle.net/HvA4s/72/ HTML <a href="edit" id=edit>Show/Hide Columns< ...

Tips for properly invoking an asynchronous function on every rerender of a component in Vue.js

Situation: An analysis module on a website that needs to display three different data tables, one at a time. Approach: The module is a component containing three buttons. Each button sets a variable which determines which table to render. Depending on the ...