Reputation: 13
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
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
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
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