【问题标题】:Document.GetElementById(VARIABLE) not working, only works with stringsDocument.GetElementById(VARIABLE) 不起作用,仅适用于字符串
【发布时间】:2019-07-31 08:21:38
【问题描述】:

我正在使用一个复选框来激活一些 javascript,这些 javascript 应该从页面中获取一个元素并对其进行更改。问题是当我使用 document.getElementID(x) 时它返回一个空值,但是当我用硬编码的 id 替换 x 时它工作正常。问题是我不希望它被硬编码,因为页面是动态的。

我已经检查了变量 x 是否被赋值,并且元素有一个 ID。

<script type="text/javascript">

    function updateInputsLabels(e){


        if(e.checked){
            //If True

            var value = 'quantity_' + e.value;

            var x = document.getElementById(value);// this is what doesnt work unless I hard-code the ID value 

            console.log(x);


        }else {
            //if false
            var cellUnchecked = document.getElementById(e.value);


        }



    }

</script>

// FULL HTML

<?php

if(isset($order)){
    $status = true;
}else $status = false;

?>

<script type="text/javascript">

    function updateInputsLabels(e){


        if(e.checked){
            //If True

            var value = 'quantity_' + e.value;

            var x = document.getElementById(value);

            console.log(x);


        }else {
            //if false
            var cellUnchecked = document.getElementById(e.value);


        }



    }

</script>


<!-- Begin Page Content -->
<div class="container-fluid">
    <!-- Main Content -->
    <div id="content">

        <div class="card o-hidden border-0 shadow-lg my-5">
            <div class="card-body p-0">
                <!-- Nested Row within Card Body -->
                <div class="row">
                    <div class="col-lg-12">

                        <div class="alert alert-warning alert-dismissible fade show"  style="display:none;"  role="alert" id="fillFields">
                            <strong>Error!</strong> Please ensure all fields are filled in.
                            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                            </button>
                        </div>


                        <div class="p-5">
                            <div class="text-center">
                                <h1 class="h4 text-gray-900 mb-4"> <?=($status) ? 'Edit Order' : 'Create an Order'?></h1>
                            </div>
                            <form class="user" action="" method="post" onsubmit="return validateCustomerForm()" name="createEditCustomer">
                                <div class="form-group row">
                                    <div class="col-sm-6 mb-3 mb-sm-0">
                                        <p><b>Customer</b></p>
                                        <select class="form-control" id="customer" onchange="customerID()" name="order[customer_id]" required>


                                            <option value="">-- Please Select a Customer ---</option>

                                            <?php foreach($customers as $customer){

                                                if($customer['customer_id'] == $order['customer_id']){


                                                    echo "  <option value=" . $customer['customer_id'] . " selected>" . $customer['customer_id'] . " " . $customer['first_name'] . ' ' . $customer['surname'] .  "</option>";



                                                }else {

                                                    echo "  <option value=" . $customer['customer_id'] . ">" . $customer['customer_id'] . " " . $customer['first_name'] . ' ' . $customer['surname'] .  "</option>";

                                                }
                                            }?>

                                        </select>
                                    </div>
                                </div>


                                <div class="form-group row">
                                    <div class="col-sm-12 mb-3 mb-sm-0">

                                        <div class="table-responsive">
                                            <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
                                                <thead>
                                                <tr>
                                                    <th></th>
                                                    <th>Product Name</th>
                                                    <th>Price (VAT)</th>
                                                    <th>Quantity Avaliable</th>
                                                    <th>Quantity</th>
                                                    <th>Total</th>
                                                </tr>
                                                </thead>
                                                <tfoot>
                                                <tr>
                                                    <th></th>
                                                    <th>Product Name</th>
                                                    <th>Price (VAT)</th>
                                                    <th>Quantity Avaliable</th>
                                                    <th>Quantity</th>
                                                    <th>Total</th>
                                                </tr>
                                                </tfoot>
                                                <tbody>


                                               <?php foreach($products as $row){?>
                                                    <tr id="row_<?=$row['product_id']?>">


                                                        <?php


                                                        if ($status && in_array($row['product_id'], $orderItems)) {

                                                            $location = array_search($row['product_id'], $orderItems);
                                                            unset($orderItems[$location]);

                                                            ?>
                                                            <td><input type="checkbox" name="product[]" value="<?=$row['product_id']?>" onchange="updateInputsLabels(this)" checked></td>

                                                            <?php

                                                        }else echo " <td><input type=\"checkbox\" name=\"product[]\" value=\" " . $row['product_id'] . "\" onchange=\"updateInputsLabels(this)\"></td>";?>



                                                        <td><?=$row['product_id'] . ' ' . $row['product_name']?></td>
                                                        <td><?=$row['product_price_vat']?></td>
                                                        <td><?=$row['quantity']?></td>
                                                        <td><input type="number" name="quantity[<?=$row['product_id']?>]" id="quantity_<?=$row['product_id']?>"  onchange="updateTotal(this)" value="0"></td>
                                                        <td>

                                                            <input type="text" class="form-control" id="total_<?=$row['product_id']?>"  name="total[<?=$row['product_id']?>]" value="0" disabled>

                                                        </td>
                                                    </tr>
                                               <?php } ?>

                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>

                                <div class="form-group row">
                                    <div class="col-sm-12 mb-3 mb-sm-0">
                                        <p><b>Additional Details</b></p>

                                        <textarea class="form-control" id="exampleFormControlTextarea3"   name="order[order_details]" rows="5" required>

                                            <?=($status) ? $order['order_details'] : ''?>

                                        </textarea>
                                    </div>
                                </div>

                                <div class="form-group row">
                                    <div class="col-sm-6 mb-3 mb-sm-0">
                                            <label for="validationDefaultUsername"><b>Discount</b></label>
                                            <div class="input-group">
                                                <div class="input-group-prepend">
                                                    <span class="input-group-text" id="inputGroupPrepend2">%</span>
                                                </div>
                                                <input type="number" class="form-control " id="validationDefaultUsername"  name="order[discount]" placeholder="Percentage" value="" min="1" max="100"  aria-describedby="inputGroupPrepend2" required>
                                            </div>
                                    </div>
                                    <div class="col-sm-6 mb-3 mb-sm-0">
                                        <label for="validationDefaultUsername"><b>Total:</b></label>
                                        <div class="input-group">
                                            <input type="text" class="form-control" id="total"  name="order[total_price]"  aria-describedby="inputGroupPrepend2" disabled>
                                        </div>
                                    </div>
                                </div>


                                <input type="hidden" class="form-control form-control-user" name="order[order_id]" placeholder="Address Line 2" value="<?=($status) ? $order['order_id'] : ''?>" required>

                                <input type="hidden" class="form-control form-control-user" name="order[staff_id]" placeholder="Address Line 2" value="<?=($status) ? $order['staff_id'] : $_SESSION['user']?>" required>

                                <button type="submit" class="btn btn-primary btn-lg btn-block" style="  border-radius: 40px;" name="submit">Save</button>
                            </form>

                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!-- /.container-fluid -->

    </div>
    <!-- End of Main Content -->

</div>
<!-- End of Main Content -->

【问题讨论】:

  • var value 的最终值是多少?这个元素存在吗?
  • 能否也分享一下标记,让我们看看值是什么以及对应的元素是什么?
  • 你能分享你的复选框代码
  • 请分享你的html
  • value 不包含您认为它包含的内容。这也必须是您自己的结论,那么您为什么不尝试记录e.value 呢?请创建一个minimal reproducible example(强调“最小”)。

标签: javascript php


【解决方案1】:

您应该分配一个更通用的事件侦听器,而不是像这里那样使用内联处理程序。如果您使用querySelectorAll,则不需要使用getElementById,这在许多情况下非常不方便。由于上面的 javascript 函数似乎还没有做太多,也许你可以尝试这样的方法

document.querySelectorAll('input[type="checkbox"]').forEach( chk=>{
    chk.addEventListener( 'click', function(e){
        if( this.checked ){
            alert( this.value )
        }
    })
});

【讨论】:

    【解决方案2】:

    e.value 中有什么内容?

    它不包含复选框的直接值。 这很好用

    
      console.log(e.value)
      var value = 'quant_' + 1;
      var x = document.getElementById(value);
      console.log(x, 'hello');
    

    https://jsfiddle.net/5dom7wx8/16/

    【讨论】:

    • 嗯,e.value 是复选框的值,在我的情况下,它与我试图获取的元素的 ID 相同。
    【解决方案3】:

    尽管有代码本身,但为了说明您所解释的内容,您应该将要更改的输入(我假设)的 id 传递给方法 updateInputsLabels:

    <td><input type="checkbox" name="product[]" value="<?=$row['product_id']?>" onchange="updateInputsLabels('<?=$row['product_id']?>')" checked></td>
    

    改变你的方法:

    function updateInputsLabels(inputId){
    
    
        if(typeof inputId='string' && inputId.length > 0){
            let fullId = 'quantity_' + inputId;
            let element = document.getElementById(fullId );
            console.log(fullId );
    
    
        }else {
            console.error("not a string or empty");
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-18
      • 1970-01-01
      • 1970-01-01
      • 2014-10-09
      • 2017-01-06
      • 2021-08-29
      相关资源
      最近更新 更多