Can someone help me convert this jQuery code into vanilla JavaScript?

Hey, I'm facing an issue where I can't use jQuery. Can someone assist me in converting these 3 selectors to JavaScript? I tried using document.getElementById('FeedbackLightBox_txtName').value; but it didn't work as expected.


    <script type="text/javascript">
    function SetButtonStatus() {
        var tb1 = document.getElementById('FeedbackLightBox_txtName').value;
        var tb2 = document.getElementById('FeedbackLightBox_txtMessage').value;
        var tb3 = document.getElementById('FeedbackLightBox_txtEmail').value;
        if (tb1.length >= 5 && tb2.length >= 5 && tb3.length >= 5)
            makeBtn();
        else
        $('#FeedbackLightBox_btnSubmit')[0].control.set_enabled(false);
    }
    function makeBtn() {
        $('#FeedbackLightBox_btnSubmit')[0].control.set_enabled(true);
    }
    function ClearValues(sender, args) {
        $('#FeedbackLightBox_txtName').val('');
        $('#FeedbackLightBox_txtMessage').val('');
        $('#FeedbackLightBox_txtEmail').val('');
        args.set_cancel(true);
        return false;
    }
</script>

Answer №1

Is this what you're looking for?

document.getElementById('SubmissionButton').control.set_enabled(false);

document.getElementById('NameInputField').value = '';

Just For Your Information

When you mention

$('#SubmissionButton')[0] // it provides access to the HTML element object, similar to saying `document.getElementById('Subm..)`.  

Answer №2

Uncertain of the location where .control.set_enabled(false); is defined within the element, but I presume you are aware.

function ConfirmButtonStatus() {
        var input1 = document.getElementById('FeedbackLightBox_txtName').value;
        var input2 = document.getElementById('FeedbackLightBox_txtMessage').value;
        var input3 = document.getElementById('FeedbackLightBox_txtEmail').value;
        if (input1.length >= 5 && input2.length >= 5 && input3.length >= 5) {
                activateButton();
        } else {
            document.getElementById("FeedbackLightBox_btnSubmit").control.set_enabled(false);
        }
}
function activateButton() {
        document.getElementById("FeedbackLightBox_btnSubmit").control.set_enabled(true);
}
function ResetValues(sender, information) {
        document.getElementById("FeedbackLightBox_txtName").value = '';
        document.getElementById("FeedbackLightBox_txtMessage").value = '';
        document.getElementById("FeedbackLightBox_txtEmail").value = '';
        information.set_cancel(true);
        return false;
}

Answer №3

It appears that you have a form structured like this:

<form id="FeedbackLightBox_form" onsubmit="return validate(this)" action="">
  Name: <input name="FeedbackLightBox_txtName"><br>
  Message: <teaxtArea name="FeedbackLightBox_txtMessage"></textarea><br>
  Email: <input name="FeedbackLightBox_txtEmail"><br>
  <input type="submit" id="FeedbackLightBox_btnSubmit">  <input type="reset">
</form>  

If you want to ensure that something is entered in each field before submission, the validation process would look like this:

function validate(form) {
  var control, controls = form.controls;
  for (var i=0, iLen=controls.length; i<iLen; i++) {
    control = controls[i];
    if (control.type != 'submit' && control.value.length < 5) {
      return false;
    }
  }
}

The unnecessary clearForm function can be omitted if you include a reset button, but here it is anyway:

function clearForm() {
  document.getElementById('FeedbackLightBox_form').reset();
}

Likewise, the oddly named makeBtn function can be simplified as follows:

function makeBtn() {
    document.betElementById('FeedbackLightBox_btnSubmit').disabled = false;
}

Perhaps it would make more sense to rename it to enableBtn?

Answer №4

It seems like jQuery is specifically being used here to retrieve HTML elements, which could lead to redundancy. To optimize your code, consider defining these elements as global variables before your functions or passing them as arguments to prevent duplication.

var input1 = document.getElementById('FeedbackLightBox_txtName');
var input2 = document.getElementById('FeedbackLightBox_txtMessage');
var input3 = document.getElementById('FeedbackLightBox_txtEmail');
var button = document.getElementById('FeedbackLightBox_btnSubmit');

function CheckInputStatus() {
    if (input1.value.length >= 5 && input2.value.length >= 5 && input3.value.length >= 5)
        enableButton();
    else
        button.control.set_enabled(false);
}
function enableButton() {
    button.control.set_enabled(true);
}
function ResetFields(sender, args) {
    input1.value = '';
    input2.value = '';
    input3.value = '';
    args.set_cancel(true);
    return false;
}

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

Efficient Ways to Store Text and Images in Vue.js

I have developed a tool that enables users to upload an image and overlay custom text on it, which can be viewed and edited in the browser. My query is whether it is feasible to save the combined image and text as separate files (e.g., jpg/png) using VueJS ...

Toggle between classes by clicking on the next or back button

Looking to create a multi-step form where the initial step is visible while the rest are hidden using the "hide" class. I want to toggle visibility of each step with Next and Back buttons, displaying only one step at a time. Can someone assist with this? ...

Utilizing Node.js within a closed intranet environment

Utilizing Nodejs's npm has proven to be quite convenient. Thus, I made the decision to incorporate it into my company's project. However, a predicament arises as my company mandates development within a closed network. This restricts my access s ...

Error: The jQuery Class is returning an undefined value

I have been working on creating a basic AJAX request class in jQuery. However, I've encountered an issue with the 'process' function where I can get the response from the variable 'response'. When I return 'response', it ...

Standardizing the file name in Internet Explorer 11 and generating a new file using JavaScript

While attempting to upload a file and normalize its name, I encountered an issue with IE11 not supporting the 'normalize' method. After some research, I discovered the 'unorm' polyfill which resolved the normalization problem. However, ...

Refreshing an external file in Node.js at regular intervals

Seeking guidance on loading external files in node. I'm currently working with an external JSON file that houses some configuration settings, and this file gets updated by an outside process every 10 minutes. How can I automate the reloading of this ...

Handling exceptions in Express.js with EJS templating using Node.js

I have encountered an issue with routing while developing my first node.js/express web-app. I suspect it has something to do with the way I am connecting the router in Express 4. Here is some debug information related to the problem: var router = express ...

Prompt user to confirm action with jQuery before proceeding

I am facing an issue with a checkbox in my form. I would like to prompt the user for confirmation before they check the box. However, currently, the confirmation message appears only after the box is checked. My goal is to allow the user to "cancel", so it ...

Is there a way to apply the active class without relying on an anchor element?

After creating a one-page website, I utilized JavaScript to prevent the hash from appearing in the URL. Here is the HTML code: <ul class="click crsl"> <li><a class="page1 dot active"></a></li> <li><a class=" ...

The paste event triggers before any text is input into the textbox

events: { "paste .youtube-url" : "addUrl" } addUrl: function(){ console.log(this.$(".youtube-url").val()); Imagine pasting the text "bad" into the textbox for the first time. Console Output: (an empty string) Then, if you paste and append something l ...

JSON data localization

I am currently in the process of developing a hybrid mobile application with PhoneGap as the platform. My goal is to localize the app's data so that it can be accessed offline. Essentially, I want all JSON data received from the API to be stored local ...

Looking to reset the default display option in a select dropdown using JavaScript or jQuery?

Here is some HTML code for a select element: <select> <br> <option>1</option><br> <option>2</option><br> </select> This select element will initially display the first option item (display ...

I am experiencing difficulty with implementing a page break within the <tr> and <tbody> elements

Below is the code I am working with: {% for item in child.items %} {%set ns.count = ns.count + 1%} <tbody style="page-break-inside: avoid"> <tr style="page-break-inside: avoid"> ...

Error occurs while running NPM script

My current task involves updating the dependencies of a React application. One of the key scripts in this app is defined in the package.json file, which is responsible for generating a message bundle for each locale. "scripts": { "build:langs": "NODE_EN ...

Determine the week number based on a specified starting day for the week

If I have a custom week start day other than Monday, how should the getWeekNumber() prototype for the Date class be modified? Here is the existing code for calculating the ISO Week Number: Date.prototype.getWeekNumber = function() { // Create a dupli ...

When debugging in ASP MVC4, JavaScript will only evaluate HiddenFor once you've paused to inspect it

Struggling with evaluating a hidden field in JavaScript (ASP MVC4). I've set up a model in my View with a hidden input for one of the properties. @Html.HiddenFor(mdl => mdl.FilterByUser, new { @id = "filterByUserId" }) Within my Helper, I have a ...

Tips on ensuring that the Google Maps marker remains in the center as you drag the map with the AGM component

I've implemented AGM (Angular Google Maps) in my Ionic Project to showcase Google Maps, and I'm looking to have the marker stay centered on the map even when it is dragged. Is there a way to achieve this with AGM? Please let me know if I have mad ...

Concern with Isotope's masonry feature

I'm at my wit's end! The container div I'm dealing with is 1170px wide. My goal is to fit in 3 divs within this width. The first div is 275px wide, the second is 580px wide, and the third is also 275px wide. Altogether, these divs should ad ...

What is the best way to incorporate an environmental variable in my AngularJS controller?

My API Key is securely stored in my '.env' file to keep it hidden from Git. Here's a snippet of my .env file: API_TOKEN=secrettokengibberish When working on my Angular controller, I need to retrieve this variable for my AJAX call. This i ...

How to Properly Manipulate DOM Elements in an Angular Directive

My directive, powerEntry, has different CSS classes that I want to add or remove based on the model state. Currently, in my link function, I have some logic like this: Script.JS if (calcState.availablePoints > 0 && isHighEnoughLevel) { ...