JavaScript Array for PHP

1

I have the following Input in my file .html

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

Whenever the user clicks the + field on the next button, it creates another input equal to that.

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 value through POST and move to my .php page, which I get there as follows:

    if(isset($_POST['option[]'])){
        $cc = array($_POST['option[]']);
}
    
asked by anonymous 30.09.2014 / 23:25

1 answer

1

When you give inputs++ within if , this does not work, because inputs is a list of fields, not a number. If you want to count how many inputs are filled in, 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);

That's if you just want to count the completed options. If you want to save 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, just submit the form, you do not need any JavaScript. Only the page reloads. If you intend to do this without reloading the page, you must use ajax. To make an ajax request with pure JS, see the question Ajax request with pure Javascript (without APIs) , has a very complete explanation there.

    
30.09.2014 / 23:43