Javascript array for PHP

Asked

Viewed 95 times

1

I have the following Input in my file .html

 <input type="text" class="form-control" name="option[]" id="option[]">

Whenever the user clicks on the + on the button next to it, it creates another input like this one.

I’m trying to get this value with Javascript as follows:

var inputs = document.getElementsByTagName('input');
for(var i=0;i<inputs.length;i++){
    if( (inputs[i].name).indexOf('option')>-1 && inputs[i].value!="") {
        inputs ++;
    }
}

And then I need to pass this amount by POST and go to my page .php , that there I receive in the following way:

    if(isset($_POST['option[]'])){
        $cc = array($_POST['option[]']);
}
  • 1

    You can’t have more than one field with the same id. And this here: (inputs[i].name).indexOf('option')>-1 && inputs[i].value!="";? What is the intention? You are doing nothing there, you do not assign the value to any variable. The intention is to have a conditional/if?

  • I’m sorry, I cut out the if .. in case it gets like this if( (inputs[i].name).indexOf('option')>-1 && inputs[i].value!="") {inputs ++;}

  • Okay, I included that information in the question. And I think I found the problem...

1 answer

1


When you give inputs++ within the if, That doesn’t work, because inputs is a list of fields, not a number. If you want to count how many inputs are filled, you can create another variable for this:

var optionsPreenchidas = 0;
var inputs = document.getElementsByTagName('input');
for(var i=0;i<inputs.length;i++){
    if( (inputs[i].name).indexOf('option')>-1 && inputs[i].value!="") {
        optionsPreenchidas++;
    }
}
alert(optionsPreenchidas);

This is if you only want to count the filled-in options. If you want to store their values, you will need an array:

var optionsPreenchidas = [];
var inputs = document.getElementsByTagName('input');
for(var i=0;i<inputs.length;i++){
    if( (inputs[i].name).indexOf('option')>-1 && inputs[i].value!="") {
        optionsPreenchidas.push(inputs[i].value);
    }
}
alert(optionsPreenchidas.join(','));

To pass this to PHP, simply submit the form, you don’t need any Javascript. Only the page reloads. If you want to do this without reloading the page, you need to use ajax. To make an ajax request with pure JS, see the question Ajax request with pure Javascript (no Apis), has a very full explanation there.

  • bfavaretto, I will test there tomorrow I put if it worked! Thanks for the help! D

  • Deu Certoo! Thanks for your attention!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.