Document.GetElementById(VARIABLE)不起作用,仅适用于字符串

时间:2019-07-31 08:21:38

标签: javascript php

我正在使用一个复选框激活一些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 -->

3 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

e.value中包含什么?

它不包含复选框的直接值。 效果很好


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

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

答案 2 :(得分:0)

尽管有代码本身,但为了使它符合您的解释,您应该将要更改的输入(我认为)的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");
    }
}