Multiple Inputs with Similar Names

So, I have several inputs with a name session, and they increase .... session0 session1 session2. If I want to run them through a loop, how would I do it. I am using jquery.

eg..

for(i=0,i<10,i++)
{
var num = (session + i).value + i;
}

So, I want the loop to go through all the inputs with a prefix session and output their values ​​to a variable. This output may fall into an array. if the array will obviously be more like.

num[i] = stuff+i;

thank.

Ok, I'm done with JavaScript. Thanks for all the help, it works great. here was the final code.

function get()
{
var alldata;
var values = [];
      $("input[name^='media']").each(function(i, anInput) {
        var check = values[i] = $(anInput).attr('checked');
        if(check == true)
        {
        var ID = "session" + i;
        var type = $(anInput).attr('value');
        if(i > 9)
        {
        var cont = "#ex"+ i;
        }
        else{
        var cont = "select[name='" + ID + "']";
        }
        var scope = $(cont).attr('value');
        if(!alldata)
        {
        alldata = type + ': ' + scope + ' ';
        }
        else
        alldata =  alldata + ' ' + type + ': ' +  scope + ' ';
        };

      })
$('#sessions').attr('value',alldata);
}
+3
source share
2 answers

Use a starts withselector ^and each, for example:

var arr = new array();
$('input[name^="session"]').each(function(){
   alert($(this).val());
   // arr[] = $(this).val();
});
+4
source

How about this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
    <head>
      <script type="text/javascript" charset="utf-8" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
      <script type="text/javascript" charset="utf-8">
        $(document).ready(function() {
          var values = [];
          $("input[name^='session']").each(function(i, anInput) {
            values[i] = $(anInput).val();
          })
        })
      </script>
    </head>
    <body>
        <input type="text" value="5" name="session0" />
        <input type="text" value="7" name="session1" />
        <input type="text" value="2" name="session2" />
        <input type="text" value="1" name="session3" />
    </body>
</html>
+4

Source: https://habr.com/ru/post/1758051/


All Articles