user1822312
user1822312

Reputation: 13

retrieve value of input

I have this:

<?php $i=0;?>
<?php foreach($x as $y): ?>
<input type="hidden" id="theid<?php echo $i;?>" value="<?php echo $someVariable;?>"/>
<?php $i = $i + 1; ?>
<?php endforeach; ?>

I need to get the value of each "theid" like this:

<script type="text/javascript">
function somefunction(element, optionTitle) {
var num = document.getElementById('theid').value;
...
</script>

How can i do that considering the fact that "theid" has the $i added? Thanks.

Upvotes: 0

Views: 67

Answers (3)

Steve
Steve

Reputation: 8640

If you have multiple input fields and you want to do the same action on several, you could use getElementsByClassName instead of getElementById:

PHP

<input type="hidden" class="theclassname" id="theid<?php echo $i;?>" value="<?php echo $someVariable;?>"/>

JS:

<script type="text/javascript">
    function somefunction(element, optionTitle) {
        var myEles = document.getElementsByClassName('theclassname');
        // loop over myEles and act on each one
        for (var i=0; i < myEles.length; i++) {
            alert("Input with id: " + myEles[i].id + " has value: " + myEles[i].value);
        }
    }
</script>

Upvotes: 1

Bertrand
Bertrand

Reputation: 13570

If you are using jQuery would be easy like this:

$('input[id^="theid"]').each(function () {
  console.log($(this).val()); //value of each theid
});

Here is a jsBin.

Upvotes: 0

DragonZero
DragonZero

Reputation: 845

I would recommend using jQuery, jQuery selectors support wildcards:

$('input[id^=theid]')

See http://api.jquery.com/category/selectors/ for further reading on this topic.

Upvotes: 0

Related Questions