What is the best way to deactivate the button when there are no arrays present in the input?

In my HTML, the input value is populated by user selection and stored in array format (e.g.

45[45, 6, 33], 67[67,2,5] and so on..
). Essentially, the value will look like this:

<input id="question_string" type="hidden" value="{}">
<input class="submit_updates" name="commit" type="submit" value="Process">

I want to disable the submit button or display an alert message saying 'Select all values' if the input does not contain any arrays within the {}.

Updated:

var question_hash_element = document.getElementById('question_string');
var question_hash = JSON.parse(question_hash_element.value);

   var myArray = new Array();
      myArray[0] = window.batch_question_id;
      myArray[1] = window.answer_id || window.answer_text || window.batch_answer_checkbox
      myArray[2] = window.build_id

This code above stores the values in the {}. I only want to enable the form submission once all fields are selected. If the values are empty within {}, the button should remain disabled; otherwise, it should be enabled.

I attempted the following:

 $('.submit_updates').click(function () {
    if ($('#question_string') == {}) {
      return false;
      alert("Select all the Values");
    } else {
      return true;
    }
  });

Unfortunately, this approach is not functioning correctly.

Any assistance would be greatly appreciated! Thank you

Answer №1

$('button.update_submission').on('click', function (e) {
   e.preventDefault();
   if ( $.trim($('#question_input').val())=='{}' ) {
       console.log('No question provided!');
   } else {
       this.form.submit();
   }
});

Answer №2

You have to ensure the alert message is displayed before returning false.

Here's a better way to handle it:

$('.submit_updates').on("click", function () {
  if ($('#question_string').val() == "{}") { //Adjusted condition
    //Show alert message
    alert("Select all the Values");

    //Disable the submit button
    $(".submit_updates").prop("disabled", true);
    return false;
  } else {
  return true; //Not really needed
 }
});

It is recommended to use on and prop instead of click and attr, as @adeneo suggests.

Answer №3

Check out this code snippet

$(document).ready(function(){
     $('.submit-updates').on('click', function () {
        if ($('#question').val() == "{}") {
              $(this).prop('disabled', 'disabled'); 
              alert("Please select all the values");
        } else {
            // Continue with the logic
        }
      });
});

Code Demo

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

Creating a unique SVG pattern starting from the center

I'm currently working on implementing a grid pattern that spans the entire viewport, following this solution. Although the grid starts from the top-left corner of the viewport, my goal is to have it start from the middle of the screen instead. This w ...

The argument type does not match the parameter type partial<>

While attempting to validate my Ionic React form, I encountered an error when calling the validationSchema within the useForm method. The specific error message received is as follows: Argument of type '{ validationSchema: ......' is not assignab ...

Twilio SMS Notification: The Class extension value provided is not a valid constructor or null

When attempting to utilize Twilio for sending SMS messages in a Vue.js project, I encountered an error while accessing Tools -> Developer Tools. <template> <div> <input type="text" v-model="to" placeholder="Ph ...

Ensuring consistent readability in Bootstrap 4 by wrapping text without affecting the height

Referenced from: Twitter Bootstrap Button Text Word Wrap Is there a way to adjust the word wrap of text inside a button in bootstrap 4 without changing the height, or maintaining equal height for all buttons? For example: <div class="container"> ...

What is the best way to update the text of an <a> element when it is clicked

On my WordPress site, I've implemented a unique custom anchor button: <a class="add-to-cart-button">Buy Now</a> I'm interested in making the button text change when it's clicked. Could this functionality be achieved using java ...

Issues with fonts in Google Chrome Version 32.0.1700.76 m

After recently updating my Google Chrome browser, I noticed that some of the fonts are not displaying correctly. Interestingly, they appear fine on other browsers, but the issue only seems to occur in Chrome v32.0.17...76 m. The fonts I used were "Open Sa ...

Determine the values of a Checkbox and a hidden input field

Below is the HTML code: <table class="tablesorter"> <g:each in="${vehicleInstanceList}" status="i" var="vehicleInstance"> <tr class="${(i % 2) == 0 ? 'odd' : 'even'}" id ="rows"> <td > <g:checkBox ...

Activate dynamic validation to ensure all necessary fields are completed before proceeding without the need to save

Is there a way to display the standard error message that appears next to required fields upon saving a form, without actually saving it? ...

Angular - Triggering actions with ng-hide and ng-show events

Is there a better solution for monitoring hide and show expressions across all elements in my app? I am aware that I can achieve this by wrapping the show directive with a function that simply returns the argument: <div ng-show="catchShow(myShowExpr = ...

Tips for positioning text within an input field above a div element

When a div is placed behind another div, the text in both div elements aligns. .wrapper { box-sizing: border-box; padding: 0; margin: 0; outline: none; padding-right: 20px; } .box { height: 34px; width: 130px; padding: 6px 12px; fon ...

Leveraging PapaParse for CSV file parsing in a React application with JavaScript

I am encountering an issue with reading a CSV file in the same directory as my React app using Javascript and Papaparse for parsing. Below is the code snippet: Papa.parse("./headlines.csv", { download: true, complete: function(results, f ...

Using jQuery, add a class for a specified amount of time in milliseconds

Can a class be temporarily added to an element and then removed after a certain number of milliseconds? For instance; If I were to click on an element with the class .trigger, would it be possible to add the class .loading to another element with the cla ...

Obtaining the response object for the web browser

Greetings! I currently have a function within router.js in NODEJS : const authenticateUser = (req, res, next) => { //something }; Whenever my application is live, this function is triggered. I am looking for a way to examine the response object. Is ...

The resizing issue persists with Angularjs charts

I have recently developed a small web application using AngularJS and I have implemented two charts from the AngularJS library - a bar chart and a pie chart. Although both charts are rendering correctly, they are not resizing properly as the display size c ...

Unable to retrieve the td value for the current row when the button inside the DIV is clicked

I want to extract the value 3 instead of the entire HTML. <div id="ExtraDt" style="overflow: auto; height:500px; width:100%; background-color: #FFFFFF; top: 0px;"> <table id="MasterList1" class="navigateable ...

How to target and append individual table cells to a particular table row using JQuery

Here is a snippet of code to consider: <tbody> <tr class="wsui-table-row-odd"> <td>IamaTextFieldBox</td> <td class="im-label-required">Label required</td> </tr> <tr class="wsui-table-row ...

Is it possible to add an element to the beginning of an array using a chained method without relying on the map function?

Looking for a solution to add an element at the start of an array in a method chain led me to some interesting findings. Initially, I attempted: console.log( [1, 2, 3] .map(a=>a+1) .splice(0, 0, 7) .map(a=>a*10) ) Usin ...

AWS Amplify-hosted Nuxt applications are resilient to errors during the build process

My website is built using Nuxt js and hosted on AWS Amplify. I've encountered a major issue where the website still gets generated successfully even when there's a failure in the nuxt generate command (like a JavaScript error in my code). Below i ...

Is it more efficient to have a single global event listener or multiple event listeners of the same type in each component for productivity?

This particular mixin is a key component in numerous pages, often appearing in multiple sections within the page. data: () => ({ device: { mobile: false, tablet: false, tabletLand: false, notepad: false deskto ...

Sending an incorrect value to the data variable

Apologies for my limited proficiency in English, Hello, I am new to Vue and struggling with an issue that I can't seem to resolve. I am fetching art data from an API (a simple list of dictionaries), and then creating a multi-array structure (list of l ...