Incorporating JavaScript: Demonstrating content on button click based on pattern matching

I want to display content in a div when the user clicks on a button. There are three buttons: test connection src, test connection dest, and next.

When I click on the test connection src button and there is no input, it should display a message. However, when the user clicks on the input field, the message should hide. Currently, I am able to show the message but not hide it when clicking on the input field.

If the input field matches the pattern (regex), it should display a message "connection successful" when test connection src is clicked. Right now, I am unable to show "connection successful" in

<div id = "inp_src_success"></div>
and
<div id = "inp_dest_success"></div>
.

The same process applies to the button test connection dest.

Clicking on the next button should only be enabled once both connections become successful.

$(document).ready(function () {
  $("#test_btn_src").on("click", function(){
    var inpsrc = document.getElementById('inp_src').value;
    //alert(inpsrc);
    if(inpsrc.trim() == null || inpsrc.trim() == "") {
      document.getElementById('inp_src1').innerHTML = 'IP src should be filled out';
    }
    else {
      $("inp_src").keypress(function(key){
          if (key){
              $("inp_src1").hide();
          }
      });
    }
  });
$("#test_btn_dest").on("click", function(){
    var inpdest = document.getElementById('inp_dest').value;
    //alert(inpsrc);
    if(inpdest.trim() == null || inpdest.trim() == "") {
      document.getElementById('inp_dest1').innerHTML = 'IP src should be filled out';
    }
    else {
      $("inp_dest").keypress(function(key){
          if (key){
              $("inp_dest1").hide();
          }
      });
    }
});

document.getElementById("mybtn").onclick = function () {
    location.href = "www.google.com";
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

<body>
  <div id = "inp_src_success"></div>

  <div>
    <label>Enter Source Server IP Here</label>
    <input  id = "inp_src" name="txtbox_ip_src" minlength="7" maxlength="15" class="form-control" type="text"
        placeholder="Source Server Ip:"
        pattern="(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"
        required onkeypress="myFunction()" />
        <div id = "inp_src1"></div>
        <button id  = "test_btn_src" class="btn btn-primary success" type="button" style=" font-size: 10px; margin-top:7px;">Test Connection Src</button>
  </div>
  <div id = "inp_dest_success"></div>
  <div>
    <label>Enter Destination Server IP Here</label>
      <input id = "inp_dest" name="txtbox_ip_src" minlength="7" maxlength="15" class="form-control" type="text"
          placeholder="Destination Server Ip:"
          pattern="(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"
          required  onkeypress="myFunction1()" />
      <div id = "inp_dest1"></div>
      <button id  = "test_btn_dest" class="btn btn-primary success" type="button" style=" font-size: 10px; margin-top:7px;">Test Connection Dest</button>
  </div>
  <button  id = "mybtn" class="btn btn-primary nextBtn pull-right" type="button">Next</button>

Answer №1

There are several recommendations for improving your JavaScript code. I suggest utilizing global variables for easier element manipulation, especially since these elements are used in multiple places.

Below is a snippet with my comments added. I will be using vanilla JavaScript instead of jQuery for this example.

I have included type="submit" for the buttons to leverage the browser's validation functionality.

In the provided snippet, you can see different ways to implement validation.

I enclosed your form within form tags, considering it's a form that requires validation and possible submission.

$(document).ready(function() {
  //Global vars for reuse
  var sourceValid = false;
  var destinationValid = false;

  var btnTestSrc = document.getElementById("test_btn_src");
  var btnTestDest = document.getElementById("test_btn_dest");
  var btnSubmit = document.getElementById("mybtn");

  btnSubmit.disabled = true;

  var txtInpSrc = document.getElementById("inp_src");
  var txtInpDest = document.getElementById("inp_dest");

  var inpSrc1 = document.getElementById('inp_src1');
  inpSrc1.style.display = "none";
  var inpDest1 = document.getElementById('inp_dest1');
  inpDest1.style.display = "none";
  //

  //Add an event listener to the button similar to your jQuery usage.
  btnTestSrc.addEventListener("click", function() {
    sourceValid = InputHasValue(txtInpSrc);
    inpSrc1.style.display = sourceValid ? "none" : "block";

    if (sourceValid && destinationValid)
      btnSubmit.removeAttribute("disabled");
    else
      btnSubmit.setAttribute("disabled", true);
  });

  //Real-time validation as user types
  txtInpSrc.addEventListener("keyup", function() {
    inpSrc1.style.display = InputHasValue(this) ? "none" : "block";
  });

  btnTestDest.addEventListener("click", function() {
    destinationValid = InputHasValue(txtInpDest);
    inpDest1.style.display = destinationValid ? "none" : "block";

    if (sourceValid && destinationValid)
      btnSubmit.removeAttribute("disabled");
    else
      btnSubmit.setAttribute("disabled", true);
  });

  txtInpDest.addEventListener("keyup", function() {
    inpDest1.style.display = InputHasValue(this) ? "none" : "block";
  });

  btnSubmit.addEventListener("click", function() {
    alert("submit");
  });
});

function InputHasValue(input) {
  var val = input.value.trim();

  return val ? true : false;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<body>
  <form>
    <div id="inp_src_success"></div>

    <div>
      <label>Enter Source Server IP Here</label>
      <input id="inp_src" name="txtbox_ip_src" minlength="7" maxlength="15" class="form-control" type="text" placeholder="Source Server Ip:" pattern="(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"
        required />
      <br />
      <div id="inp_src1">IP src should be filled out</div>
      <button id="test_btn_src" type="submit" class="btn btn-primary success" type="button" style=" font-size: 10px; margin-top:7px;">Test Connection Src</button>
    </div>
    <div id="inp_dest_success"></div>
    <div>
      <label>Enter Destination Server IP Here</label>
      <input id="inp_dest" name="txtbox_ip_src" minlength="7" maxlength="15" class="form-control" type="text" placeholder="Destination Server Ip:" pattern="(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"
        required />
      <br />
      <div id="inp_dest1">IP dest should be filled out</div>
      <button id="test_btn_dest" type="submit" class="btn btn-primary success" type="button" style=" font-size: 10px; margin-top:7px;">Test Connection Dest</button>
    </div>
    <button id="mybtn" type="submit" class="btn btn-primary nextBtn pull-right" type="button">Next</button>
  </form>
</body>

Answer №2

Creating HTML Elements with jQuery

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

      <body>
        <div id = "inp_src_success"></div>

        <div>
          <label>Fill in Source Server IP Address</label>
          <input id = "inp_src" name="txtbox_ip_src" minlength="7" maxlength="15" class="form-control" type="text"
              placeholder="Source Server Ip:"
              pattern="(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"
              required onkeypress="myFunction()" />
              <div id="inp_src1"></div>
              <br>
              <button id = "test_btn_src" class="btn btn-primary success" type="button" style="font-size: 10px; margin-top: 7px;">Test Connection Src</button>
        </div>
        <div id="inp_dest_success"></div>
        <div>
          <label>Provide Destination Server IP Address</label>
            <input id="inp_dest" name="txtbox_ip_src" minlength="7" maxlength="15" class="form-control" type="text"
                placeholder="Destination Server Ip:"
                pattern="(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"
                required onkeypress="myFunction1()" />
            <div id="inp_dest1"></div>
            <br>
            <button id="test_btn_dest" class="btn btn-primary success" type="button" style="font-size: 10px; margin-top: 7px;">Test Connection Dest</button>
        </div>
        <button id="mybtn" class="btn btn-primary nextBtn pull-right" type="button">Next</button>

Handling Events with JavaScript (JS)

$(document).ready(function () {
          $("#test_btn_src").on("click", function(){

            var inpsrc = document.getElementById('inp_src').value;
            //alert(inpsrc);
            if(inpsrc.trim() == null || inpsrc.trim() == "") {
              document.getElementById('inp_src1').innerHTML = 'IP src should be filled out';
            }
            else {

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

            }
          });
          $("#test_btn_dest").on("click", function(){
            var inpdest = document.getElementById('inp_dest').value;
            //alert(inpsrc);
            if(inpdest.trim() == null || inpdest.trim() == "") {
              document.getElementById('inp_dest1').innerHTML = 'IP dest should be filled out';
            }
            else {

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

            }
          });

          document.getElementById("mybtn").onclick = function () {
              location.href = "www.google.com";
          };
        });

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

I'm experiencing difficulties with arranging images side by side on my bootstrap website

I am facing an issue while using Bootstrap 5 where the images are not aligning horizontally as expected. Instead, they are getting added in the lower row. I have tried various solutions but nothing seems to work. Any help on this matter would be greatly ap ...

What is the best way to convert CSS to JSS for Material-UI styling?

I need to convert some basic CSS to JSS and include it in the global Styles.js file. The original CSS is as follows: .formdetail { display: grid; grid-row-gap: 10px; grid-template-columns: 1fr 3fr; margin: 20px; } .formdetail .cell { display: ...

Exploring the power of jQuery Ajax with JSON Data

I've been struggling to extract a specific part of the JSON response, but I can't seem to figure it out. json = '{ "now": "2010-09-23 22:06:53 EST", "data":[ {"id":"1","year":"2010","month":"09","day":"23","hours":"08","minutes":"09","se ...

How to load a table file in JavaScript synchronously

I came across this particular method for accessing a local text file. However, I am facing an issue as I do not want the file to be read asynchronously. My goal is to have the function read the file and return the output as a string variable instead. The ...

Tips for assigning the result of a Fetch API call to a variable

Hello everyone! I'm currently working on a project that requires me to retrieve the latitude or longitude of a location using the Google Maps API. However, I am facing an issue with returning values using the Fetch API and its promises. I have succe ...

Share a Node.js Express.js npm package for universal access within the project

Here is my current folder structure. /app.js /src /routes /controllers Within the routes folder, there are multiple javascript files that all require the passport.js package like so: const passport = require('passport'); Is it possible to c ...

Using CSS pseudo elements before and after on an input range

I am looking to create a slider that dynamically displays boundaries. After searching online, I came across some code that I modified to suit my needs. This code uses only HTML and CSS and looks great in Chrome, but not so good in Firefox (I also tried it ...

Using innerHTML in PHP to create a dynamic two-step echo effect

step 1: I am creating a form where input fields will be dynamically generated using innerHTML. var d = document.getElementById("d1p_1"); d.innerHTML += "<input class='add' name='field_" + i + "' type='text'>"; step 2: ...

Simple steps to change JSON Object to JavaScript array

Referring to this question and this other one, I am seeking advice on how to handle a JSON object structure different from the examples provided: This is my JSON Object: var myData = { "04c85ccab52880": { "name": "name1", "firstname": ...

IE 7 textarea malfunctioning with word spacing issues

I have a website using the LAMP stack with a form that users fill out. Strangely, when I view the submitted form data in IE 7, it adds line breaks between each word. The form is simple with input elements and a text area. Submitting the form in FF3+, IE8, ...

The HTML page is experiencing loading inconsistencies

I am just venturing into the realm of web development (although I am not new to coding), so please bear with me. For my project, I decided to use Django and integrated some free Bootstrap themes that I stumbled upon online. While working on my home page, ...

Expand Tooltip on the Fly

Is there a way to make a tooltip expand horizontally instead of overflowing below the page? I have a tooltip that can be quite lengthy, and due to its max-width being set at 200px, it extends beyond the bottom edge of the page. I am currently able to set ...

Having trouble with the "Cannot POST /contact.php" error message?

Help needed with ERROR "Cannot POST /contact.php". Here is the code: Code from index.html <form action="/contact.php" method="post"> <div class="w3-row-padding" style="margin:0 -16px 8px -16px"> <div class="w3-half"> ...

AngularJs monitoring changes in service

Why does changing the message in the service not affect the displayed message in 1, 2, 3 cases? var app = angular.module('app', []); app.factory('Message', function() { return {message: "why is this message not changing"}; }); app ...

What is the process for choosing an element that is embedded within another element?

I'm attempting to apply a red border class to an image located inside another div, using data attribute. I've completed the first part of this task, here's my code: HTML: <div class="delivery-method col-lg-5"> <div class="letter r ...

Is it feasible to access a service instance within a parameter decorator in nest.js?

I am looking to replicate the functionality of Spring framework in nest.js with a similar code snippet like this: @Controller('/test') class TestController { @Get() get(@Principal() principal: Principal) { } } After spending countless ho ...

Increase the width of columns when hiding additional columns

I have the following HTML and CSS code. If one of the columns is hidden, I would like the other 3 columns to expand. I don't believe using col-md-3 will work in this situation. Is there a way to achieve this? <link href="https://stackpath.boots ...

The ThemeProvider does not automatically provide theme injections

After creating a theme using the createTheme method from @mui/material/styles, I attempted to apply this theme using ThemeProvider from the same package. This snippet showcases the dark theme that was created: export const darkTheme = createTheme({ pale ...

Tips for converting inline CSS to stand-alone attributes without any cost

I am attempting to modify an au generated HTML code, for example: <div class="intro editable" id="field_text">text <strong>text</strong> text <span style="text-decoration: underline;">text</span> <span style="color: #ff00 ...

Veracode Scan finds vulnerability in jQuery html method with Improper Neutralization of Script-Related HTML Tags in a Web Page error

Veracode has flagged the issue Improper Neutralization of Script-Related HTML Tags in a Web Page (Basic XSS) within the following line of code. $('#SummaryDiv').html(data); $.ajax({ url: 'Target_URL', type: &a ...