Submitting form to PHP with dynamic inputs

时间:2018-01-25 16:20:47

标签: javascript php html forms

I have a form which is empty in HTML file and I'm adding input elements to it using javascript but when I submit the form to PHP file (Controller.php) it doesn't send anything

HTML File

<form id="test" action="Controller.php" method="POST">
    <!-- QUESTIONS WILL APPEAR HERE-->
    <div id="questions"></div>
    <input type="submit" value="Finish">
</form>

JS File

var d1 = document.getElementById('questions');
        d1.insertAdjacentHTML('beforeend',
            "<div class='question'>"
            + "<h4 id='questionTitle'>Question Title goes here...</h4>"
            + '<ul>'
            + '<li id="ans1"><input type="radio" id="1st-option" name="selector">'
            + '<label for= "1st-option" >Answer 1</label>'
            + '<div class="check"></div>'
            + '</li>'


            + '<li id="ans1"><input type="radio" id="2nd-option" name="selector">'
            + '<label for= "2nd-option" >Answer 2</label>'
            + '<div class="check"></div>'
            + '</li>'


            + '<li id="ans1"><input type="radio" id="3rd-option" name="selector">'
            + '<label for= "3rd-option" >Answer 3</label>'
            + '<div class="check"></div>'
            + '</li>'


            + '<li id="ans1"><input type="radio" id="4th-option" name="selector">'
            + '<label for= "4th-option" >Answer 4</label>'
            + '<div class="check"></div>'
            + '</li>'
            + '</ul>');

PHP File

print_r($_POST);

The result of $_POST is an empty array Array ( ), I have tried to add elements to the form statically (in HTML) and it worked, but I can't do it from JS,IDK why this happens

1 个答案:

答案 0 :(得分:1)

您的输入没有值属性:

更改:

<input type="radio" id="1st-option" name="selector">

<input type="radio" id="1st-option" name="selector" value="your_value">

对于“答案1”,值可以是“answer1”例如,或者“第一选项”,例如id你已经设定,或任何你想要的东西。但你必须拥有一些东西。否则它将是空的。