Use jQuery to apply a class to some input elements when certain events like keyup or

If I type something in the input field, it should add a border to the li tag containing the text. The current script works fine, but is there a way to make this jQuery script shorter?

Thank you for your help!

.add_border{
border: 2px solid #000 !important;
}
$(document).ready(function(){

$('#input1').on('keyup keydown keypress change paste', function() {
if ($(this).val() == '') { $('#my_block1').removeClass('add_border'); } else {$('#my_block1').addClass('add_border'); }});

$('#input2').on('keyup keydown keypress change paste', function() {
if ($(this).val() == '') { $('#my_block2').removeClass('add_border'); } else {$('#my_block2').addClass('add_border'); }});

}); 
<ul>
<li id="my_block1">
<span>some text 1</span>
<div class="form-group">
<input id="input1" type="text" name="my_item_1">
</div>
</li>
<li id="my_block2">
<span>some text 2</span>
<div class="form-group">
<input id="input2" type="text" name="my_item_2">
</div>
</li>

</ul>

Answer №1

To include a tag in a jQuery selector, you can use the following code:

$('input').on('keyup keydown keypress change paste', function() {       
    if ($(this).val() == '') {
        $('#my_block1').removeClass('add_border');
    } else {
        $('#my_block1').addClass('add_border'); 
    }
});

In response to your latest comment:

.on('input', function() { 

The input event is not a default event. For more information about using the on method in jQuery, please refer to: http://api.jquery.com/on/ and learn more about events here: http://api.jquery.com/category/events/

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

Positioning the label for a Material-UI text field with an icon adornment when the shrink property is set

https://i.stack.imgur.com/E85yj.png Utilizing Material-UI's TextField, I have an Icon embedded within. The issue arises when the label "Your good name here" overlaps the icon instead of being placed beside it. This problem emerged after I included ...

Can you provide guidance on how to zoom in on the Jquery Portlet when clicking the "zoom-in" icon?

After thorough research in various forums, I have not come across any relevant post addressing my specific issue. Therefore, I am reaching out for assistance. I currently have four Jquery Portlets on my page. My goal is to enable a zoom-in feature on o ...

Disabling animations in Reactjs with CSSTransition and Group Transition

Currently, I am experimenting with REACTJS to build a basic app featuring Transitions. In my project file, I have imported CSSTransitions and Group Transition. However, when attempting to implement CSSTransition for specific news items, the animations are ...

retrieve undefined value from redux state in a React Native application

Received the data in reducer but encountering issues accessing it in the component. Below is the connection code: const mapStateToProps =state => { return { name:state.fbLogin.name } } function mapDispatchToProps(dispatch){ ...

Is it possible to dynamically change the background image using ReactJS?

I attempted to dynamically change the background image style for the div below: Below is my code snippet for implementation: render: function() { var divImage = { backgroundImage : "url(" + this.state.song.imgSrc + "),url(" + this.state.nextImgSrc ...

Node.js server encountering a cross-domain error

As a beginner exploring node.js, I am embarking on setting up my very first installation. In my server.js file, I am defining a new server with the following code: var app = require('http').createServer(handler), io = require('socket.io&a ...

The antithesis of jQuery's .parents() selector

I am currently developing a userscript for a webpage with an old-fashioned design consisting mainly of tables. My goal is to access a long table of fields so that they can be filled in automatically by the script. To simplify, the structure is as follows: ...

Prevent a specific folder from being included in expressjs routing

When using my expressjs app, I load public assets like this: app.use(express.static(__dirname + '/public')); Afterwards, I redirect all requests to the index, where every path is handled by Backbone app.get('*', routes.index); I am ...

Employing JavaScript to insert a JSON value as a parameter in an HTML element's attribute

In a JSON file, I have "img" properties with .jpg file paths as their values (e.g "images/image.jpg"). I am attempting to insert these values into the 'src' attribute of existing HTML elements. Below are my attempts so far: I tried creating te ...

Having difficulty displaying form errors using handlebars

My form validation is not working properly. When I enter incorrect information, it alerts correctly, but when I submit the form, it returns [Object object]. What could be causing this issue in my code and how should I handle the data? https://i.stack.imgu ...

Running two servers at the same time using nodemon might seem complex, but it

Is it possible to run two servers (www.js and apiServer.js) simultaneously using nodemon? I have set the value for the "start" key in package.json as https://i.stack.imgur.com/r8M7p.jpg After running nodemon in the command prompt with the current working ...

The page you are trying to access could not be found after attempting to upload 5

I am encountering an issue with jQuery File Upload where I am able to successfully upload files for any number of files up until 5. However, when attempting to POST 5 or more files, the server returns a 404 Not Found error. Oddly enough, POSTing only 4 fil ...

hyperlink triggers spacing problem in Internet Explorer

When displaying a paragraph of text, I add a "read more" link at the end if the text exceeds a certain length. However, in Internet Explorer (IE), the line with the link appears separated from the line above, creating an awkward look. To see where this is ...

When retrieving the card in React, only the first element is affected by the .map function

There seems to be an issue with Arrays.map as it is only working for the first object in the array. Here is the main function: function App(){ return ( <div> <NavBar /> { data.map((prop) =&g ...

There was an issue with locating the module: Error: Unable to find the specified module 'vue-axios' in the directory 'C:xampphtdocsvue-laravel-api esourcesjs'

I am currently working on a CRUD project using Laravel and Vue.js. I made sure to install all the necessary devDependencies, but when I try running NPM run watch, I encounter the following error: My app.js file includes all the required dependencies: ...

Exploring the principles of object-oriented design within the context of Node

I am facing challenges with the asynchronous flow of Node.js. Let's assume we have the following class: function myClass() { var property = 'something'; var hasConnected = false; this.connect = function(params) { // Logic to conn ...

Tips for reducing the amount of repetitive code in your reducers when working with redux and a plain old JavaScript object (

When it comes to writing reducers for Redux, I often encounter challenges. My struggle usually lies in wrapping a lot of my state manipulation in functions like .map and .slice. As the structure of my state object becomes more complex, the reducers become ...

Adding custom script tags to a React application

I'm interested in integrating a StreamingVideoProvider video player into my React application but facing some challenges: I do not have direct access to the video URL I want to utilize their JS video player for its advanced features like password pro ...

The functionality of the jQuery datepicker may not function properly after an AJAX call if it was already present on the webpage

I currently have a datepicker input labeled X on my website. Upon clicking a button, an ajax call is made and displays some HTML content on the page. Within this ajax response, there is another datepicker input called Y, which typically functions properly ...

Issue with React and Mongoose: State Change Not Being Saved

I am facing an issue with changing the state of my checkbox. Initially, the default option in my Mongoose model is set to false. When a user checks the box and submits for the first time, it successfully updates their profile (changing the value to true). ...