JavaScript - Identifying elements and assigning attributes based on specific text in the element's ID

I am dealing with several field names that follow the pattern: 'Field1_ro', 'Field2_ro', 'Field3_ro'...

Is there a more efficient way for me to make all fields containing 'ro' read-only without having to manually set each one like in the code snippet below?

document.getElementById('Field1_ro').readOnly = true;
document.getElementById('Field2_ro').readOnly = true;
document.getElementById('Field3_ro').readOnly = true;

Answer №1

If you want to make elements read-only based on the id attribute ending with a certain value, you can use the attribute-ends-with selector like this: [id$=_ro]. Simply use querySelectorAll and loop through the results:

document.querySelectorAll("[id$=_ro]").forEach(function(element) {
    element.readOnly = true;
});

In general, it's more common to assign a common class to these elements and select them by their class. Alternatively, consider setting the readonly attribute when defining the elements initially rather than afterward. :-)


Please note that the NodeList returned by querySelectorAll only recently gained support for forEach. If you need to support older browsers, you can polyfill this feature easily. Check out this example for a guide on how to do so.

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 row of aligned vertical sliders using jQuery UI

I'm having trouble aligning multiple vertical UI sliders on the same line. Here's what I'm looking to achieve: 1. Have 4 vertical sliders displayed in a row. 2. Show numerical values as the user moves each slider. The code I'm currentl ...

Tallying the Number of Accordion Toggle Clicks

Let me present a scenario where I have some accordions and would like to keep track of how many times the user expands each one. Could you guide me on how to implement this particular feature? Appreciate your support, Kevin ...

Can you explain the process of serving static files with both Express and React?

Need help integrating my create-react-app project with Express to add backend functionality. My server currently displays a blank page when running. Here is the code: const express = require('express'); const path = require('path') ...

Creating dynamic dropdown menus within a Rails 3 form using Prototype and incorporating database queries

Recently, I've been on the hunt for a seamless method to create dynamic dropdown menus within a form that can be populated with data from a database based on the selection of a previous dropdown. Unfortunately, my search for a suitable Rails 3/prototy ...

As I go through the database, I notice that my div model functions correctly for the initial record but does not work for any subsequent ones

I came across a model on w3 schools that fits my requirements, but I am facing an issue where the model only works for the first result when looping through my database. It's likely related to the JavaScript code, but I lack experience in this area. C ...

Exploring the Force-Directed Graph Demo on bl.ocks.org

I don't have much expertise in javascript, jquery, or json. My objective is to create a graph using the force-directed graph example from bl.ock.us. 1) I wrote a python script to generate the necessary json data. 2) I noticed others were us ...

What is the best way to achieve the effect of "overflow: hidden" in three.js or WebGL?

I'm diving into the world of designing a WebGL GUI for my games and I'm keen to explore GPU graphics in more depth, as it offers a smoother experience compared to WebKit CSS rendering. Is there a way to create a scrollview where the internal mes ...

Issues with Skrollr JS on mobile device causing scrolling problem

Currently facing an issue with Skrollr js. It is functioning perfectly in web browsers and mobile devices. However, there seems to be a problem when tapping on a menu or scrolling down arrow as it does not initiate scrolling. Assistance would be greatly ...

How to prevent mousewheel scrolling on an HTML page with the exception of a specific div using jQuery

Is there a way to prevent mousewheel scrolling on an HTML page while still allowing it on a specific element? I've tried using the code below: $('html').bind("mousewheel, touchmove", function(e) { e.stopPropagation(); return false; ...

Specify the upper limit for a numeric input using Vuejs

My Vue.js script looks like the following: <template> <div> <div v-if='cart.length > 0'> <h1>Your Cart</h1> <template> <fieldset v-for='produc ...

Loading content dynamically with AJAX and enabling smooth page scrolling

Looking for a solution to this issue. I have a button on my webpage that, when clicked, uses AJAX to load content into a "div" element below the button. Everything functions properly except for one problem - every time the button is pressed, the page scrol ...

Adjust the positioning of a class element

I have an eye icon that changes position when clicked. Initially, it is set to left: 10%;, but if there is a DOM element with the ID login-section, it should be repositioned to left: 50%;. I attempted to use document.getElementsByClassName('fa-eye-sl ...

Angular - attach event listener to Bootstrap dropdown menu

Looking to add an overlay on the screen behind a menu when it's expanded, but unsure of how to do this with Bootstrap. Any suggestions on listening for when the menu expands? Here is my current menu code: <link rel="stylesheet" href="https://st ...

Utilizing Regular Expressions in AngularJS to validate name, a 10-digit mobile number, and a 12-digit number through the ng-blur event and match

I am struggling to validate the three inputs mentioned above and having trouble using the right functions. Can someone please assist me with this? Here is the HTML code for the 3 inputs: <input id="name" ng-model="user.name" ng-blur="checkIfNameIsVali ...

Unable to access some object properties leads to a return value of undefined (Meteor)

Can anyone help me understand why I am getting an Undefined response when trying to retrieve latitude and longitude values from an object? I decided to use the .find() method after reading about it here: var LatLngs = Shops.find({_id:template.data._id}, ...

What is the best way to determine the height of an element after new content has been added through AJAX?

I have been working with a Jquery Mobile page and I am facing an issue when loading a form via AJAX. The plugin I am using to set the page dimensions calculates them after the AJAX call has completed and the layout has been updated. However, the height of ...

Created a custom function that includes a specific target href parameter

I have a website that implements role-based authentication, where the application displayed is dependent on the user's role. The code for this functionality is as follows: <asp:Repeater ID="ui_rprApp" runat="server" DataSourceID="odsApp"> ...

Sorting by two fields with varying value types in AngularJS

Need help sorting json data by two fields, prioritizing field value and then date. Check out this demo Json input [{ "title" : "Title 2", "pin" : false, "date" : 20130411204207 },{ "title" : "Title 3", "date" : 20140411204207 },{ "title" : "Title 4", ...

Changing the Order of Elements Inside a <div> Tag

Issue at Hand: Greetings everyone. I have a question about reordering elements in HTML using JavaScript. My goal is to move the items in the list down each time a specific button is clicked. Initially, the elements are arranged like this: <div class=& ...

How can one create parameter information in JavaScript?

Is it possible to automatically generate parameter information in JSDoc style based on function implementation? /**  * Assigns the project to a list of employees.  * @param {Object[]} employees - The employees responsible for the project.  * @param {st ...