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

The alignment of bullets in CSS property list-style-position is off

I'm encountering an issue with aligning the list items. I've been using the CSS property list-style-position: inside; Typically, the bullet points appear outside of the text, like this: https://i.stack.imgur.com/LcVB0.png This doesn't seem ...

Guide on adding a post type via the command line: Issue encountered - Anticipated POST console HTML error

Facing Error: EXPECTED POST in JQuery Ajax Call Encountering the same issue as mentioned in the provided link. The need is to switch from GET to POST, but direct alteration of ajax code is not feasible. It must be done dynamically using JavaScript through ...

Testing the units of a system ensures that the flow and data storage are reliable

Currently, I'm facing an interesting challenge when it comes to unit testing and the flux data stores. Because the data stores are singletons that are only instantiated once (upon module import), any changes made during unit tests remain persistent. ...

Providing Node-server with Vue.js Server Side Rendering

I've been attempting to deploy the Hackernews 2.0 demo on my Digital Ocean droplet but have hit a roadblock. npm run start starts the server on port :8080. npm run build is used for production builds. The specific build tasks can be found below: ...

PHP jQuery buttons for popovers

With a simple click of a button, I can generate 8 presentations and then edit each one individually by clicking on its respective name. Within this editing process, there is another form where I would like to include additional buttons that allow me to cus ...

The variable X has been defined, but it's never actually utilized. Despite declaring it, I have not accessed its

I have encountered warnings in VSCode while using certain properties in my Angular component. The warnings state: '_id' is declared but its value is never read.ts(6133) (property) ItemEditComponent._id: number | undefined '_isModeEdit' ...

What is the reason behind this Uncaught TypeError that is happening?

After converting my questionnaire to a PHP file and adding a validation script, I encountered an error: Uncaught TypeError: Cannot set property 'onClick' of null The error is pointing me to line 163 in my JavaScript file, where the function f ...

Experiencing Chrome freezing issues due to a setInterval function in combination with React

Can anyone assist me with a countdown issue using React? I am trying to set the minutes and seconds by clicking on + and - buttons, then passing the seconds to a new variable called tottime. However, when the user clicks on Go!, the countdown should start ...

Is there a way to align these buttons in the middle?

I am currently designing a webpage at The challenge I'm facing is: How can I center those buttons on the page? They need to remain centered and responsive even when the page is resized. Additionally, the spacing between the buttons is inconsistent. ...

Challenge with uploading Minio presigned URLs

I am encountering a problem with the Minio presigned URL. While I have successfully obtained the URL and used the PUT method to insert my file into my Minio bucket, I am unable to open certain file types such as jpg, png, or pdf. This is due to Minio autom ...

Bringing in a script and invoking a function on a specific variable

As a newcomer to Typescript, I've been experimenting with some code I came across online to enhance the appearance of links on my website. <script src="https://wow.zamimg.com/widgets/power.js"></script> <script>var wowhead_tooltips ...

What are the steps for skipping, sorting, and limiting with dynamoose?

After being familiar with MongoDB and mongoose, I am now exploring dynamoose for my app. In order to replicate the below-shown mongoose query using dynamoose, how can I write it? Specifically, I want to achieve the same functionality as the following mong ...

Euler 13: Surprising outcome when attempting to combine several String variables

I'm currently working on a challenging problem found on euler: here Large sum Problem 13 In this problem, the task is to determine the first ten digits of the total sum when adding up one-hundred 50-digit numbers. 37107287533902102798797998220837590 ...

How to automatically open JQuery Accordion panels when the page loads

My Accordion loads with the 1st panel open upon page load, but I am looking for a way to have the entire Accordion closed by default. Any help or suggestions on how to achieve this would be highly appreciated. Thank you for your assistance. FIDDLE http:// ...

Adding Material-UI icons dynamically in a React TypeScript project requires understanding the integration of imported icons

I have a collection of menu buttons with icons, stored in an array of objects. The icon names are saved as strings that correspond to Material UI icons: interface MenuButton { text: string, onClickFunction: Function icon: string } export defau ...

Preventing Redropping: A jQuery Drag and Drop Feature to Ensure Dropped Elements Stay Put

After implementing Drag & Drop functionality using jQuery, I have encountered a specific issue. The problem: When the dropped element (drag 1) is removed from the droppable container, it reverts back to the draggable container. Subsequently, attempting to ...

Securing Communication with HTTPS in Express JS

After purchasing an AlphaSSL from a hosting provider, I received the following files: domain.csr.crt domain.interCert.crt domain.PKCS7Cert.crt domain.rootCert.crt domain.X509Cert.crt However, in order to enable HTTPS on Node.JS using Express, I am aware ...

Display only the labels of percentages that exceed 5% on the pie chart using Chart JS

I'm currently diving into web development along with learning Chart.js and pie charts. In my project, the pie chart I've created displays smaller percentage values that are hardly visible, resulting in a poor user experience on our website. How c ...

Tips for sending an Ajax request to a separate URL on the same server

When making an ajax request to my server, I use the following code: var data = ''; $.ajax({ type: 'GET', url: 'api/getnews/home/post/'+title, data: data, datatype: 'json', success: f ...

Deactivate Link Using CSS while Allowing Title to be Functional

Is there a way to enable the link in CSS while still showing the title? Take a look at my code: CSS and HTML Code: .disabledLink { pointer-events: none; opacity: 0.6; cursor: default; } <a href="www.google.com" class="disableLink" title="M ...