What is the best way to pass the value of the index 'i' from a for loop to the id attribute in

Here are some input fields with different IDs:

<tr>

    <td><input type="number" id="cell1" ></td>
    <td><input type="number" id="cell2" ></td>
    <td><input type="number" id="cell3" ></td>



    <td><input type="number" id="cell4"></td>
    <td><input type="number" id="cell5"></td>
    <td><input type="number" id="cell6"></td>



    <td><input type="number" id="cell7" ></td>
    <td><input type="number" id="cell8" ></td>
    <td><input type="number" id="cell9" ></td>

</tr>

I am looking to restrict the user from entering certain numbers by using jQuery. Here is an example of what I have tried:

for(var i = 0 ; i <= 81 ; i++) {


    $(document).ready(function () {
        $("#cell" , i).change(function () {

            var n = $("#cell",i).val();
            console.log($("#cell", i));
            if (n < 1)
                $("#cell", i).val(1);
            if (n > 9)
                $("#cell" , i).val(9);
        });
    });

}

However, this code does not recognize the IDs. How can I pass the variable i to "#cell"?

Answer №1

When working with elements that have IDs starting with "cell," you can use the following selector

$(function() {
  $("[id^=cell]").on("input",function() {
    const val = this.value
    if (val < 0) this.value = 1
    if (val > 0) this.value = 9
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tbody>
    <tr>

      <td><input type="number" id="cell1"></td>
      <td><input type="number" id="cell2"></td>
      <td><input type="number" id="cell3"></td>



      <td><input type="number" id="cell4"></td>
      <td><input type="number" id="cell5"></td>
      <td><input type="number" id="cell6"></td>



      <td><input type="number" id="cell7"></td>
      <td><input type="number" id="cell8"></td>
      <td><input type="number" id="cell9"></td>

    </tr>

  </tbody>
</table>

For the HTML version, the input fields can also specify a minimum and maximum value of 1 to 9

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tbody>
    <tr>

      <td><input type="number" id="cell1" min=1 max=9></td>
      <td><input type="number" id="cell2" min=1 max=9></td>
      <td><input type="number" id="cell3" min=1 max=9></td>
      <td><input type="number" id="cell4" min=1 max=9></td>
      <td><input type="number" id="cell5" min=1 max=9></td>
      <td><input type="number" id="cell6" min=1 max=9></td>
      <td><input type="number" id="cell7" min=1 max=9></td>
      <td><input type="number" id="cell8" min=1 max=9></td>
      <td><input type="number" id="cell9" min=1 max=9></td>

    </tr>

  </tbody>
</table>

Answer №2

To start, ensure that your loop is placed inside the $document.ready function.

Next, you can add i to the id prefix in order to correctly target the cell using the querySelector.

While this may not directly address your inquiry, another option is utilizing the min and max attributes to achieve your goal.

Below is a functional demonstration of incorporating the loop counter i:

// Demonstrating the creation of 81 input elements for illustration purposes
$(document).ready(function () {
  var row= $('#myrow');
  for(var i = 0 ; i <= 81 ; i++)
  {
    row.append($('<td/>').append('<input type="number" />').attr("id", "cell" + i));
  }
});

$(document).ready(function () {
  for(var i = 0 ; i <= 81 ; i++) {
$("#cell"+ i).change(function (e) {
  var input= $(e.target);
  var n = input.val();
  if (n < 1)
    input.val(1);
  else if (n > 9)
    input.val(9);               
  });
 }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<table>
<tr id='myrow'>
</tr>
</table>

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

How can I use jQuery to navigate through list items using the up and down keys while maintaining the cursor position?

Hello everyone, I need help with a specific scenario: http://jsfiddle.net/cKf5b/ When you focus on the text field and use the UP and DOWN arrow keys, you can navigate through the list items below. This is the code snippet in question: //set cursor posit ...

Adjust the height of taller images to match the size of other images within a flexbox grid

On my Wordpress category page, I have a flexbox grid showcasing posts with titles and excerpts. Most images have the same proportions, but a few are significantly taller. I'm looking to responsively set the max-height of the tall images to match the h ...

Is there a way to hide an image once my scrollable div has reached a specific height?

I'm currently working on a project that involves a scrollable div with arrows above and below. My goal is to have the arrow above only appear after the div has reached a certain height. Below is the code I've been using... $("#scrolldivup").hid ...

Finding the Closest Element with jQuery's .closest() Method

I'm facing an issue while trying to select an element that is positioned above another element. Specifically, I want to target the nearest occurrence of the .discount-dropdown class that appears above the .discount-type class. Can anyone help me figur ...

Obtaining the identifier of a selected checkbox upon page initialization

I've been exploring different examples and possibilities, but I have run into a roadblock. Can anyone lend me a hand? I have extracted several rows from a table, each containing a radio button with a dynamic id that determines whether the row should ...

Is it possible to transmit messages from a Chrome extension to a Java server?

My question is, if I want to create a Chrome extension that sends messages to a Java server, should I use the XmlHttpRequest API in the extension and have the Java server as an HTTP server? ...

"Unlock the secrets to commanding respect in the web form layout by mastering the art

I have a fieldset that includes a legend with potentially long text content. I need the legend to only take up 50% of the width of the fieldset. Currently, when the legend is too lengthy, it still occupies 50% of the space but causes the entire fieldset ...

Improving and Expanding the jQuery Accordion Menu

After delving into jQuery programming recently, I encountered a hurdle with a custom jQuery accordion. Despite my best efforts, I haven't been able to successfully expand the accordion for the current link. This has left me feeling quite perplexed and ...

CSS - Maximizing One Column's Width While Allocating Percentage Space for Two Columns?

It's been quite some time since I delved into the world of web development and I seem to have forgotten how to tackle this particular issue. Despite hours spent searching online, I've gained knowledge about flex-boxes and other useful tools, but ...

What are the implications of dynamically setting or changing event handlers in web development?

Looking to streamline the process of replacing standard confirm() boxes with Bootstrap modals for saving and deleting on a page. Each operation has its own button (referred to as the action button) which triggers the corresponding modal. Upon clicking the ...

There seems to be an unidentified issue causing my carousel to malfunction

I'm currently experiencing an issue with the carousel on my Angular web application that is not functioning as expected. I am unable to determine the root cause of this problem -- here's my code <div id="section1" class="carousel slide" ...

What steps are needed to successfully integrate bootstrap.js, jquery, and popper.js into a project by using NPM to add Bootstrap?

I've successfully set up a project and incorporated Bootstrap via npm. However, I'm facing challenges in loading the necessary javascript files for Bootstrap components. It's important to note that I am utilizing a Vagrant Box (virtual machi ...

What is the best way to compress a set of string data in AngularJS?

My coding attempt resulted in an error. Here is the code snippet: var UglifyJS = require("uglify-js"); var result = UglifyJS.minify("Hello world @123;", { fromString: true }); console.log(result.code); When using UglifyJs in the above code, I encountered ...

Exploring Django and JQuery Autocomplete: A Guide to Handling Numerous Foreign Keys in Form Submissions (Django Snippet 233)

I stumbled upon a great code snippet that offers an excellent and versatile way to implement autocomplete functionality for widgets using jQuery Autocomplete: link Unfortunately, I couldn't find a complete example demonstrating the usage of this snip ...

The GLTFLoader does not support the replacement of its default materials

I am currently working on a scene that includes: AmbientLight color: light blue PointLight color: pink a gltf object loaded with textures Using the GLTFLoader, I successfully loaded a gltf object with texture map. The model is displayed correctly with ...

Creating a hover effect in CSS that applies to neighboring elements with similar attributes

My table is created using a struts2 iterator and has variable length and content. It looks something like this: <table> <tr class="odd" machineId="1" parameterId="1"><td></td></tr> <tr class="even" machineId="1" pa ...

Rails 6 does not have support for matching multiple route parameters

routes.rb: get '/get_text_by_tablenum/:filename_id/:tablenum_id', to: 'dashboard#get_text_by_tablenum' ajax: $.ajax({ dataType: "json", cache: false, url: '/get_text_by_tablenum/' + filename + &apo ...

Changing the onclick value with jQuery

I am in the process of developing a function that can identify all anchor tags containing both http and _gaq (as many links have event tracking). Afterwards, I want to incorporate Google Analytics cross-domain tracking linker method into the onclick event: ...

Removing HTML elements and accounting for new lines in a text box

I am currently utilizing CodeIgniter for my personal website, which includes multiple textareas. I am looking for a solution to prevent HTML tags from being stored in the database. Is there a tool available that can strip out any unwanted tags? Additional ...

Browsing through a jQuery JSON object in Chrome reveals a dynamic reshuffling of its order

Jquery + rails 4 Within the json_data instance, there is data with key-value pairs. The key is an integer ID and the value is an object containing data. However, when attempting to iterate over this data using the jQuery $.each function, the results are s ...