Issues with simple jquery and javascript: unable to add the class ".has-error" and onclick event not properly defined

Currently, I am working with jQuery version 2.1.4 and JavaScript to implement a straightforward form validation using Bootstrap.

During this process, I have encountered three peculiar issues.

  1. While I am confident that my jQuery code is properly functioning in the onblur and onfocus events of the <input> elements (as demonstrated in my fiddle), I am unable to observe the styling of the .has-error class. I have included boostrap.css in the <head> section, however.

  2. The <form-group> component is causing my paragraph to be excessively indented towards the far left of the screen, resulting in it being partially hidden. I might be misusing it, but the reason behind this behavior eludes me.

  3. The "Cancelar" button is not functioning correctly. Despite attempting both

    <s:url value="/listaReservas.jsp" />
    and a plain URL approach similar to the one used in the fiddle, I am still encountering issues. Firefox is displaying an error stating that "cancelar is not defined." Is it permissible to define a standalone JavaScript function as I have done (by mixing JavaScript with jQuery), or is it necessary to bind it using $('#xxxId').click(function(){});???

Any assistance on these matters would be greatly appreciated. Thank you.

Answer №1

.has-error is functional, but some adjustments need to be made. First, the class should be applied to the parent node form-group, and secondly, your <input> field should include the class form-control. The HTML structure should resemble the following:

<div class="form-group has-error">
    <label class="control-label" for="tarjetaId">No. Tarjeta:</label>
    <div class="controls">
        <input class="input-xlarge form-control" id="tarjetaId" name="usuarioCompra.numeroTarjeta" value="" />
    </div>
</div>

Regarding the JavaScript:

$("#tarjetaId").blur(function(){
    var cuenta = $("#tarjetaId");
    if (cuenta.val().length != 20){
        cuenta.closest('.form-group').addClass("has-error");
        $("#comprarButtonId").prop('disabled', true);
    } else {
        cuenta.closest('.form-group').removeClass("has-error");
    }
});

It's worth noting that the .form-group class may cause your layout to have a negative margin. Since you are using .row as its parent, which also has a negative margin, you are effectively applying two layers of negative margins. Having <div class="row"> is unnecessary.

Finally, define the following function outside of $(document).ready():

function cancelar() {
    window.location = "/listaReservas.jsp";
};

In the HTML for the submit button, use onclick="cancelar()" instead of onclick="cancelar".

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

Is it possible to await the response of a request in Socket.io with socket.on('answerToRequest')?

Can the following scenario work out? async function checkSocketStatus(){ socket.emit('checkOtherSocketStatus', otherSocketId); await socket.on('responseCheckSocketStatus', (status)=>{ console.log('status'); } ...

Ways to incorporate a custom JavaScript function that is activated by an external server system?

I'm currently exploring a JavaScript widget that needs to operate within specific constraints: The widget initiates a request to a third-party server using a callback URL The third-party server pings the callback URL after a set period, triggering a ...

transferring information from child to parent with the help of Vue.js and Laravel

As a newcomer to vue.js, I have a child component called 'test' and a parent component called 'showdata'. My issue arises when I try to emit data from the child to the parent - while the emission is successful, displaying the data in th ...

event triggered when the values of dynamically added rows change

I am trying to calculate the product of two input fields and display it without submitting the form. I have incorporated an array and included functionality to add/delete rows, with an onchange function to calculate the product. This solution works well ...

What steps can be taken to ensure web resources such as scripts, images, etc are loaded from the correct location when implementing CORS support in a web application

In my local IIS, I have two asp.net mvc applications running on different ports. One is "App1" on port 1066 and the other is "App2" on port 1067. My requirement is for App2 to post data to an endpoint in App1 for validation. If the data is valid, App1 sho ...

jQuery unable to target Bootstrap button

I've been experiencing some trouble trying to attach a listener to a button I made with Bootstrap. <button type="button" id="buttonone" class="btn btn-default btn-lg good"> <span class="glyphicon glyphicon-minus" aria-hidden="true">< ...

Vue struggles to handle data coming from a composable function

For my specific case, I need to verify whether the user has subscribed to my product through both Stripe and Firebase. To accomplish this, I created a composable function that checks for the current subscription in the Firebase collection. If the user cur ...

Restricting the input range with JQuery

Need assistance with limiting user input in a text box for amounts exceeding a specified limit. Attempted using Ajax without success, considering jQuery as an alternative solution. Any expertise on this matter? function maxIssue(max, input, iid) { v ...

Switching between videos can lead to an undesired bouncing effect on

Whenever I switch between my video thumbnails, there seems to be a slight bounce as the new video loads. To better understand this issue, check out this video: . <!DOCTYPE html> <html lang="en"> <head> <meta charset=" ...

"Stay entertained with a captivating animated gif that appears when you refresh the

I just implemented this code snippet to enable animated gifs to work after refreshing a webpage. It's functioning properly in Chrome, Safari, and Internet Explorer except for Firefox. Can someone please offer assistance? jQuery: $(img).css("backgrou ...

Managing touch devices and animations when hovering

Is there a way to remove or prevent all hover effects on a touch device? I've tried various scripts, but none seem to work for me. How can I test it with dev tools? I attempted this script but received an error: Cannot read property 'addEventList ...

Interact with the exe/jar files on a remote machine using JavaScript

I've been tasked with finding a way to access an executable file (or any file located in a specific location like the C drive) directly from a web browser. The idea is to have a button on a webpage that, when clicked, will run the executable and pass ...

What steps can I take to ensure that when the user clicks the logout button, they are redirected to the home component?

Struggling to find a way to direct the user back to the Home component after logging out. The API functionality has been tested and is working properly. I'm unsure how to properly implement the logout method in the current context to allow for succes ...

Interactive Dropdown Menus for 3 Separate Database Tables

Having trouble creating a dependent drop-down list and would appreciate some help. The error "Undefined variable: input" keeps showing up in my code. https://i.sstatic.net/mBurS.pngFor the initial drop-down, I have 3 fixed options. <option value="busin ...

React Navigation Error: navigateTo must be used within a valid router configuration

When attempting to utilize useNavigation() from react-router-dom, I encounter the following error: Error: useNavigation must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router. NavBar src/components/NavBar.js:6 3 ...

Show the total of a JavaScript calculation in a designated input box

Is there a way to show the total sum of this calculation in an input field? function calculateSum1() { var sum = 0; //loop through each textbox and add their values $("input.miles").each(function() { //only add if the value is a number ...

Button within the Magnific Popup (do not use to close)

I am currently developing a website with a gallery page that utilizes the Magnific Popup plugin. My client has provided lengthy 'captions' for each image, almost like short stories. To display these captions effectively, I have utilized the titl ...

Tips for dividing the AJAX response HTML using jQuery

I have a piece of code that is functioning properly. However, I am having trouble splitting the HTML response using AJAX jQuery. I need to split it into #div1 and #div2 by using "|". Could you please provide a complete code example and explanation, as I am ...

Send both queries using JSON

I am trying to pass company information using Json, and I also want to pass the areas using the same method. However, I am encountering some issues. Can anyone provide assistance? if($_GET['method']=="get_all_companies"){ $query = "SELECT co ...

Angular's route resolve feature does not wait for the promise to resolve before

I just started using angular and I'm facing an issue with my user route. I'm trying to resolve the user object before rendering the view, but even after injecting $q and deferring the promise, the view is loading before the promise gets returned. ...