Automatically reveal or conceal an element based on the entry of a value in an input field, without relying on the keyup() or click events

I have a form field with a Bootstrap Datepicker that populates an <input> tag with a selected date.

<div class="wrapper">
   <div class="form-group">
      <label>Select Date</label>
      <div class="input-group">
        <input name="date_info" type="text" class="form-control datepick validate_date" placeholder="Date" readonly>
      </div>
      <small class="validate_date_error">This field is mandatory!</small>          
      <small class="validate_date_success">This is Fine!</small>
  </div>

  <button class="next">Next</button>
</div>

I want the functionality where clicking the .next button will display .validate_date_error if the date is not selected or empty.

If a date is selected, I want to show .validate_date_success without needing an additional click or the [Enter] key.

Here is my JavaScript code:

$(function() {
    $('.datepick').datepicker({
        autoclose: true,
        format: 'dd-mm-yyyy'
    });
});


$(".next").click( function() {
    var check_date = $(".validate_date").val();

    if( check_date === "" ){
       $(this).parent().find('.validate_date_error').show();
    }else {
       $(this).parent().find('.validate_date_error').hide();
       $(this).parent().find('.validate_date_success').show();
    }
});

If anyone can help me with this, I would greatly appreciate it.

You can view my updated code on JS Fiddle

Answer №1

When you pick a date from the datepicker, you can utilize the onchange event,

$('input[name=date]').change(function() { 
        var selected_date = $(".validate_date").val();
        $('.validate_date_error').hide();
        if(selected_date === ""){
            $('.validate_date_success').hide();
        } else {
            $('.validate_date_success').show();
        }
});

Hopefully, this solution resolves your issue.

Answer №2

Utilizing the JQuery function change is recommended in this scenario. The function is triggered every time the value in an input field is altered, making it ideal for your requirements.

To implement this, consider assigning an id to your input field, for example:

<input id="date" name="date_info" type="text" class="form-control datepick validate_date" placeholder="Date" readonly>

Next, in your JavaScript file, include the change method:

$('#date').change(function () {
    if($(this).val() !== '') //If a date has been selected
    {
        //display a success message
    }
    else
    {
        //display an error message
    } 
})

Of course, this is a basic example. You can customize the condition to suit your specific needs.

You can access the corresponding fiddle http://jsfiddle.net/zNbUT/750/

I trust this information proves helpful to you.

Answer №3

Would you like to explore an alternative approach using the .on(event, callback) method?

$(function() {
    $('.datepick').datepicker({
        autoclose: true,
        format: 'dd-mm-yyyy'
    });
});

$("input[name='date']").on('change', function (e) {
    if (e.target.value) {
    $('.validate_date_error').hide();
    $('.validate_date_success').show();
  } else {
    $('.validate_date_error').show();
  }
})

$(".next").click( function() {
            var check_date = $(".validate_date").val();

      if( check_date === "" ){
        $(this).parent().find('.validate_date_error').show();
      }else {
        $(this).parent().find('.validate_date_error').hide();
        $(this).parent().find('.validate_date_success').show();
      }
});

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

Instead of providing proper JSON, the system is giving back [object, Object]

Check out my function below: function retrieveData(){ $.getJSON( "viewcustomers.php", function(data) { var records = []; $.each( data, function( key, val ) { records.push( "<td>" + val + "</td>" ); ...

Evaluating Vue with AVA - The key is in the whitespace

Currently, I am engrossed in a Laracast Episode about Vue Testing with AVA. Everything has been going smoothly so far, but now I have encountered an intriguing bug. This is my notification.js: import test from 'ava'; import Notification from &ap ...

Discovering the most concise string within the array

I've been working on a JavaScript program function that is supposed to return the smallest string in an array, but I keep encountering an error whenever I run it. Below is the code I have written: function findShortestWordAmongMixedElements(arr) { ...

Issue with preventdefault() function in Internet Explorer 8

I've encountered a problem while working on a page that heavily utilizes ajax. Everything seems to be functioning well across different browsers, except for one final step that is broken in IE8 and below. You can view the issue on this demo page: To ...

Use jQuery's .replaceWith method only once for each instance

Encountering a problem with my code that involves jQuery, and I'm struggling to find a solution. $("a[href=##]").replaceWith("<label>" + $("a[href=##]").text() + "</label>"); The issue arises when I have multiple links with the same href ...

How to resolve undefined Axios Authorization headers in Vue.JS and Node.JS interactions?

Encountering an issue while trying to set authorization headers for my axios instance. Here is the code snippet from my Vue.JS application running on http://localhost:8080 : axios.defaults.headers.common['Authorization'] = 'Bearer ' ...

The issue arises when the jQuery $.get() method fails to deliver the expected response to the client, despite returning a status code of

I am having trouble with sending a REQUEST to a server in order to retrieve a message. I have tried using the jQuery method $.get(), and it seems to have successfully reached the server. However, I am facing an issue where I am unable to send a RESPONSE b ...

Encountering an issue with extending the MUI color palette, receiving a "reading 'dark'" error due to properties of undefined

Encountering an issue when trying to expand the MUI color palette—getting this error instead: Error: Cannot read properties of undefined (reading 'dark') Take a look at my theme.ts file below: const theme = createTheme({ palette: { pri ...

Mastering the art of utilizing middleware in every HTTP request using Node.js Express

I am currently developing a middleware for my nodejs application and I need to include a header in the request within the middleware before sending it to my index.js endpoint. middleware1.js exports.mw1 = function(req, res, next) { next(); }; middlewa ...

Customizing the tab content background color in MaterializeCSS

I've been struggling to customize the background color of my MaterializeCSS tabs content by referring to their official documentation: If you visit the website, you'll notice that the default tabs have a white background, while the 'Test 1& ...

Personalized FullCalendar header title

Is there a way to display a unique header title for each calendar in my collection of 16? I've been trying various modifications to the code snippet below with no success: firstDay: <?php echo $iFirstDay; ?>, header: { left: 'prev,next ...

Divide and conquer- Lighttpd's mod_wstunnel combines separate messages by using UNIX socket communication to the backend server

In my experience with lighttpd's mod_wstunnel, I have encountered a peculiar issue. When I send two messages in quick succession from the backend using a UNIX socket to communicate between lighttpd and the backend, I noticed that lighttpd logs show th ...

Styling elements with pseudo-classes when a horizontal scroll bar is activated

I have been experimenting with CSS pseudo-classes, specifically the before and after classes. While I have had no issues with the before class, I am running into a horizontal scroll problem when using the after class. I want to avoid using overflow: hidde ...

Is there a way to verify if a FormData file has no content?

Currently working on an AJAX form where users can choose a background color or upload a background image. The aim is to have the bgColor field ignored if a file is specified for bgImg. <label>Color: <input type="color" name="bgColor" value="#0000 ...

Utilizing the JSON.parse method in JavaScript in conjunction with an Ajax request while incorporating the escape character "\n" for new line functionality

https://jsbin.com/zuhatujoqo/1/edit?js,console Edit: json file has this line: {"pd":"ciao \\n ste"} I need to retrieve a valid JSON file through an ajax call. Then parse the result using JSON.parse. I'm confused about the behavior of t ...

Arrange list items in a circular pattern

Is there a way to achieve the desired appearance for my navbar like this link? I have tried rotating the text, but the vertical text ends up too far from the horizontal. Any suggestions? .vertical { float:right; writing-mode:tb-rl;/*IE*/ w ...

Utilizing streams for file input and output operations in programming

This unique piece of code allows for real-time interaction with a file. By typing into the console, the text is saved to the file and simultaneously displayed from it. I verified this by manually checking the file myself after inputting text into the cons ...

Requesting information from a model using a JavaScript variable in a cshtml file in an ASP.NET application

Is there a way to use a JavaScript variable to retrieve a specific item from an array stored in a model? Below is a code snippet: function CreateCategoryList() { var limit = @(Model.CategoriesCount.ToString()); for (i=0; i<limit; ...

Using weasyprint to convert a single HTML page into a PDF

I have encountered a challenge while attempting to convert an HTML page with a single table (containing images or text in the td elements) to a PDF using the Python module weasyprint. The issue I am facing is that weasyprint is inserting page breaks withi ...

Unexpected JSON data submission

I am encountering an issue with JSON. Since I am not proficient in JSON, identifying the problem is challenging. Here is the JSP code snippet. $(document).ready( function(){ window.onload = dept_select; $("#sales_dept_id").change ...