1

My problem maybe is basic, i just lack the skills. How can i turn the following code into javascript? :

    <?php
    for($i=1; $i<10; $i++){
        echo "<input type='text' placeholder='Word' name='word$i' /><br />";
    }
    ?>

I want to add an input everytime the user presses a button (already built) but i need every new input to have the following number than the one before. For instance:

input 1 (... name='word1') press again the button input 2 (... name='word2') press again the button input 3 (... name='word3')

Thanks! Happy 2013!

2
  • 1
    Do you want pure javascript, or jquery ? You should read up a bit on api.jquery.com/jQuery Commented Jan 11, 2013 at 7:33
  • 1
    Please be noted that PHP is executed at server side, while JavaScript is executed at client side. Your end result seems very doable (and actually basic) with JavaScript, but the output order will not be the same. Commented Jan 11, 2013 at 7:37

4 Answers 4

1

Ok you have one button created please write a onclick event on it whick fires a function like this and also create one main div in which your elements can be added

<input type="button" onclick="getElement();"/>
<di id="main"></div>

In the function getElement please write this code:

var i=1;
function getElement(){
var str = "<input type='text' placeholder='Word' name='word"+i+"' />";
i++;
document.getElementById('main').innerHTML = str;
}
Sign up to request clarification or add additional context in comments.

Comments

1
for (var i = 0; i < 10; i++) {
  var input = document.createElement('input');
  input.setAttribute('type', 'text');
  input.setAttribute('placeholder', 'Word');
  input.setAttribute('name', 'word' + i);
}

Something like this?

Comments

1

Tested in Chrome

<input type="button" value="Magical pony time!" onclick="clickhandler()" />

<div id="container"></div>

<script type="text/javascript">
    // contains the counter for elements added
    window.__buttonClickCounter = 0; 

    // Keep reference to container
   var c = document.getElementById('container');

    // Click handler that appends to the contents of the container
    var clickhandler = function() {
        c.innerHTML = c.innerHTML + "<input type='text' placeholder='Word' name='word"+window.__buttonClickCounter+"' value="+window.__buttonClickCounter+" /><br />";
        window.__buttonClickCounter++;
    }
</script>

Comments

0

Try

<?php
for($i=1; $i<10; $i++){
?>
<input type='text' placeholder='Word' name='word'<?php echo $i;?>/>
<?php
}
?>

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.