简体   繁体   中英

Pass to javascript variable attribute from html input id=“attribute”

Input

<input type="text" value="" id="row1">
<input type="text" value="" id="row2">

Need to get last character from row and pass it to javascript variable. Here is row1 and row2, need to get variables 1 and 2

I try to use this, but does not work

$('[id^="row"]').each(function (index, row) {
var row = row.id.substring(3);
alert (row);//this is only to check if value exists (alert or not)
});

No alert at all. But need: on first iteration (.each) var row is 1, on second, - 2, etc.

Used this as example. The example works, but my code not

$.each([52, 97], function(index, value) {
alert(index + ': ' + value);
});

Your code works fine, provided that:

  1. You are actually including jQuery at some point (you didn't mention it in your question, but you appear to be using it)

  2. You run the code after the elements exist.

Here's your code with jQuery included and where we ensure that the code doesn't run until after the elements exist: Live Copy | Live Source

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
  <input type="text" value="" id="row1">
  <input type="text" value="" id="row2">
  <script>
    (function($) {
        $('[id^="row"]').each(function (index, row) {
        var row = row.id.substring(3);
        alert (row);//this is only to check if value exists (alert or not)
        });
    })(jQuery);
  </script>
</body>
</html>

Note how the script tag is after the elements it operates on, so they exist when that script runs.

This would not work:

  <script>
    (function($) {
        $('[id^="row"]').each(function (index, row) {
        var row = row.id.substring(3);
        alert (row);//this is only to check if value exists (alert or not)
        });
    })(jQuery);
  </script>
  <input type="text" value="" id="row1">
  <input type="text" value="" id="row2">

...because when the script runs, the elements don't exist yet.

If for some reason you're not in control of where the script element goes, you can use jQuery's ready function to wait to run your code until the DOM has been loaded. But there's no need to do that if you control where the script tags go, just put them at the end of the document, just before the closing </body> tag.

More:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM