检索输入值

时间:2013-03-26 20:35:57

标签: javascript forms function dom

我有这个:

<?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; ?>

我需要像这样得到每个“theid”的值:

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

考虑到“theid”增加了$ i的事实,我怎么能这样做呢? 感谢。

3 个答案:

答案 0 :(得分:1)

如果您有多个输入字段,并且想要对多个输入字段执行相同操作,则可以使用getElementsByClassName代替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>

答案 1 :(得分:0)

我建议使用jQuery,jQuery选择器支持通配符:

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

有关此主题的进一步阅读,请参阅http://api.jquery.com/category/selectors/

答案 2 :(得分:0)

如果你使用jQuery就像这样容易:

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

这是jsBin

相关问题