Problem with dynamically appended elements
I am creating something like a shopping-cart in yii2 .
Here is my code:
- $('body').on('click', '#materials li', function () {
- let hidden = $('[value=' + $(this).attr('data-id') + ']');
- console.log(hidden);
- if (hidden.length > 0) {
- return false;
- }
- else {
- $('#materials-form').append('<input type="hidden" name ="Materials[' + $(this).attr('data-id') + ']" class="hiddenInput" value="' + $(this).attr('data-supplier') + '"/>');
- $('#materials-form').append('<li>' + $(this).text() + '<button data-id = "' + $(this).attr('data-id') + '">Delete</button>' + '<input type ="text" id = "quantity" name="quantity[' + $(this).attr('data-id') + ']" /> ' + '<input type ="hidden" id="price" name="price[' + $(this).attr('data-id') + ']" value ="' + $(this).attr('data-price') + '"' + '</li>');
- $("#quantity").keyup(function () {
- var sVal = this.value;
- var iNum = parseInt(sVal);
- var price = $("#price").val();
- //var price_num = parseInt(price);
- //alert(price);
- var total = iNum * price;
- $('#materials-form').append('<li>' + total + '</li>');
- alert((total));
- });}
And I try to check, whether a li is clicked in order not to be appended 2 times. So I declared a let value named hidden and I pass in there the value , or better the id value.
The question is that , the length of that let var , does not increase or it remains always the same. It has a different behavior for different database records.I want the length of that value to increase by click in order not to append it again or if it is not clicked to append?
Here is the rest of the code:
- public
- function actionGetOrderMaterialsById()
- {
- \Yii::$app->response->format = 'json';
- $supplier_clicked = Yii::$app->request->get("supplier");
- $result = (new Query())
- ->select('materials.id,materials.name as material,material_supplier.materials_id,material_supplier.price,supplier.name,supplier.id as supplier_id')
- ->from('materials')
- ->innerJoin('material_supplier', 'materials.id = material_supplier.materials_id')
- ->innerJoin('supplier', 'supplier.id = material_supplier.supplier_id')
- ->where(['supplier_id'=> $supplier_clicked])
- ->all();
- //die(var_dump($result));
- $options = '';
- foreach ($result as $material) {
- $options .= '<li id ="li-value" data-supplier = "' . $material['supplier_id'] . '" data-id = "' . $material['id'] . '"data-price = "' . $material['price'] . '" >' . $material['material'] . ' from supplier->
- ' . $material['name'] . ' and it costs' . $material['price'] . 'dollars</li>';
- }
- return $options;
- }
- <?php $form = ActiveForm::begin(['id' => 'materials-form']); ?>
- <input type ="hidden" id="supplier_id" value = "<?php echo $_GET["supplier"]; ?>">
- <input type="text" id="search"/>
- <ul name="Materials" id = "materials">
- </ul>
- <!--<input type="text" name="OrderMaterial[value][]" id="quantity" style="display: none;">-->
- <input type="submit" value="Submit" id = "submit"/>
- <div class="total"></div>