0

I would like to get select form with variable amount of fields. To achive this first I connect to db and converting data from php to javascript. Then i got array (wynik) with values, but when i try to print it i get empty select form and all values shown next to it. There is my javascript function:

<script language="javascript">
function addInput() {
document.getElementById('text').innerHTML += "<select name='add' /><br />";
for (i=0;i<wynik.length;i++)
{
document.getElementById('text').innerHTML += "<option value=" + "wynik[i]" + " />" + wynik[i] + "</option />";
}
document.getElementById('text').innerHTML += "</select />";
}
</script>

And HTML code:

<form name="add" action="add_form.php" method="post">
<div id="text">
</div>
<br>
<input type="submit" value="Submit" />
</form>
<input type="button" onclick="addInput()" name="add" value="Add value" />

Please help me to put that into form.

3
  • 5
    <script language="javascript">? This is not 1997, please don't write HTML 3.2. Commented Jul 15, 2013 at 14:06
  • @Quentin wow, you could tell that this is 3.2 just by that? Commented Jul 15, 2013 at 14:08
  • 2
    @pattyd — HTML 2 didn't have script elements. HTML 4 made the type attribute mandatory. I'm being somewhat facetious, the big pile of rogue /s mean that it is horrible tag soup rather than HTML 3.2. The real message is Write proper HTML. Commented Jul 15, 2013 at 14:11

3 Answers 3

2

The browser will attempt to fix the DOM each time you write HTML to it, consequently you cannot write just a start tag to innerHTML.

Build all your HTML up in a string and then insert it in one go.

Better yet, use createElement, appendChild and friends instead.

Sign up to request clarification or add additional context in comments.

Comments

0

Perhaps you need to remove <br /> after <select name='add' /> . Also </select /> does not need a / in the end (it has it in the begining) - </select>.

Comments

-1

Another approach you can try with ajax:

<!-- Script -->
<script type="text/javascript">
$(function(){
    $("#add").on('click', function(){
       $.ajax({
            url     : 'ajax.php',
            type    : 'POST',
            success : function(resp){
                $("#backend").html(resp);
            },
            error   : function(resp){

            }
       }); 
    });
});
</script>
<!-- HTML -->
<div id="text"><select id="backend" name=""></select></div>
<input type="button" id="add" value="Add value" />

<!-- Backend ajax.php -->
<?php
#your query here to fetch $wynik
$str    = "";
foreach($wynik as $value){
    $str    .= '<option value="'.$value.'">'.$value.'</option>';
}
return $str;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.