jQuery: вычисление и переменная не отображаются при установленном флажке

#javascript #php #jquery #html

#javascript #php #jquery #HTML

Вопрос:

Все еще изучаю jQuery. На самом деле все еще новичок в jQuery. Попытка закодировать:

Когда установлен флажок элементы, он вычисляет плату за обслуживание в годах. затем добавьте к нему плату за лицензию. Наконец, он принимает общее и умножает количество, которое затем создает item_cost.

Если установлено более одного элемента, он также вычислит item_cost и добавит стоимость каждого отмеченного элемента, создавая total_item_cost . И это добавит часы обучения каждого отмеченного элемента, создавая total_training_hours .

После завершения вычисления элемента в нем отобразятся имя элемента, годы, количество, часы обучения и общая стоимость каждого элемента, отмеченного внизу таблицы. Также будет отображена другая таблица с общим количеством часов обучения и общей стоимостью всех товаров.

Я закодировал ниже, но, похоже, не могу получить элементы для отображения в таблице.

  <script>
$(document).ready(function(){
    //First obtaining indexes for each checkbox that is checked
    $('input[id^=item_add]').change(function(){

        // get checkbox index
        var index = $(this).attr('id').replace('item_add','');

        //hide tables until box is checked
        $('table[id^=add_item_here]').hide();
        $('table[id^=add_totals_here]').hide();

        //If checkbox is checked, show tables, calculate item cost, get variables, calculate total cost, amp; calculate total training hours
        $('input:checkbox').change(function(){ 

            //If check box is check do...
            if($(this).is(':checked')){

                // Show totals tables
                $('#add_item_here').show();
                $('#add_totals_here').show();

                // start at 0 for item_cost
                var item_cost = 0;
                var total_cost = 0;
                $('input:checkbox:checked').each(function(){

                    // Calculating item cost for just that one checkbox
                    item_cost =parseInt($('#servicefee' index).val());
                    item_cost*=parseInt($('#yrs' index).val()); 
                    item_cost =parseInt($('#licensefee' index).val());
                    item_cost*=parseInt($('#qty' index).val()); 

                    // Get hidden variables to use for calculation and tables.
                    var item = $('#item' index).val();
                    var traininghrs = parseInt($('#traininghrs' index).val());
                    var qty = parseInt($('#qty' index).val());
                    var yrs = parseInt($('#yrs' index).val());
                } else {

                    //if not checked keep tables hidden
                    $('#add_item_here').hide();
                    $('#add_totals_here').hide();                                           
                }

                // start at 0 for total_costs
                var total_cost = item_cost;
                //Add item_cost with other item_costs to calculate total_cost
                $('input:checkbox:checked').each(function(){
                    total_cost = item_cost;
                }

                // start at 0 for total training hours
                var total_training = 0;
                //Add trianing hours with other training hours to calculate total_training
                $('input:checkbox:checked').each(function(){
                    total_training =parseInt($('#traininghrs' index).val());
                }
            });

                //Display each item that is checked into a table
                $('#add_item_here tr:last').append('<td>'   item  '</td><td>'   yrs  '</td><td>'   qty  '</td><td>'   traininghrs   '</td><td>'  item_cost   '</td></tr><tr>');

                //Display totals into table row into a table
                $('#add_totals_here tr:last').append('<td colspan=3 ></td><td>'   total_training   '</td><td>'  total_cost   '</td></tr><tr>');

        });                                         

        // Quantity change, if someone changes the quantity
        $('#qty' index).change(function(){
            $('input:checkbox').trigger('change');
        });

        // Years change, if someone changes the years           
        $('#yrs' index).change(function(){
            $('input:checkbox').trigger('change');
        });                                         
    }           
}
 </script> 
  

Необходимо, чтобы каждый элемент и его сведения отображались в таблице, а затем необходимо создать итоговую таблицу. Пока формат таблицы для отображения выглядит следующим образом:

  <table  id="add_item_here" style="width:98%;">
     <tr><td></td></tr>                                     
 </table>
 <table  id="add_totals_here" style="width:98%;">
     <tr><td></td></tr>                                     
 </table>
  

Как и было запрошено, ниже приведена сама HTML-форма.

  <form id="myForm" method="post" class="price-quote-form" action="#" >                          

<div class="tx-row" style="width:100%; float:left; clear:right;">
    <div class="tx-column tx-column-size-2-3" style="float:left; margin-top:-20px; ">                               
        <label>
            <strong>Jurisdiction / Organization:</strong> <span style="font-size:10px; color:#ff0000;">(required)</span><br />
            <input style= "width:90%; height:35px; font-size:18px; border: 1px #396ba5 solid;" type="text" name="jurisdiction" required>
        </label> 
    </div>                                          
    <div class="tx-column tx-column-size-1-3" style="float:left; margin-top:-20px; ">                               
        <label>
            <strong style="font-size:14px;">State:</strong> <span style="font-size:10px; color:#ff0000;">(required)</span><br />
                <select style= "width:90%; height:35px; font-size:18px; border: 1px #396ba5 solid;"  id="state" name="state" required>
                    <option  value=""  >Select State</option>
                    <option value="IlIaNd"  >Iowa</option>
                    <option  value="IlIaNd" >Illinois</option>
                    <option  value="Minnesota" >Minnesota</option>
                    <option  value="Missouri" >Missouri</option>
                    <option  value="Nebraska" >Nebraska</option>
                    <option  value="IlIaNd" >North Dakota</option>
                    <option  value="SouthDakota" >South Dakota</option>                                                     
                </select>
        </label>
    </div>
</div>  
<script>
    $(document).ready(function(){
        $("#state").change(function(){
            $(this).on('change', function() {
                if(this.value =="IlIaNd"){
                    $(".box").not(".IlIaNd").hide();
                    $(".IlIaNd").show();
                }else if(this.value =="Minnesota"){
                    $(".box").not(".Minnesota").hide();
                    $(".Minnesota").show();
                }else if(this.value =="Missouri"){
                    $(".box").not(".Missouri").hide();
                    $(".Missouri").show();
                }else if(this.value =="Nebraska"){
                    $(".box").not(".Nebraska").hide();
                    $(".Nebraska").show();
                }else if(this.value =="SouthDakota"){
                    $(".box").not(".SouthDakota").hide();
                    $(".SouthDakota").show();
                }else{
                    $(".box").hide();
                }
            });
        }).change();
    });
</script>
<div style="width: 100%; float:left; clear:both; height:25px;" > </div>
<div style="border-bottom: 1px solid #cccccc; width: 100%; float:left; clear:both;" > </div>
<div style="width: 100%; float:left; clear:both; height:25px;" > </div>
<div style="width: 100%; float:left; clear:both;" class="IlIaNd box">
    <?php IlIaNd_Price_Quote_Form() ?>
</div>
<div style="width: 100%; float:left; clear:both;" class="Minnesota box" >
    <p>test 2</p>
</div>
<div style="width: 100%; float:left; clear:both;" class="Missouri box">
    <p>test 3</p>
</div>
<div style="width: 100%; float:left; clear:both;" class="Nebraska box" >
    <p>test 4</p>
</div>
<div style="width: 100%; float:left; clear:both;" class="SouthDakota box">
    <p>test 5</p>
</div>

<center>
    <table  id="add_item_here" style="width:98%;">
        <tbody>
            <tr><td>Item</td><td>Years</td><td>Quantity</td><td>Training Hours</td><td>Total Item Cost</td></tr>    
        </tbody>
    </table>
</center>
<center>
    <table  id="add_totals_here" style="width:98%;">
        <tbody>
            <tr><td cospan=3></td><td>Total Cost</td></tr>  
        </tbody>
    </table>
</center>

 </form>
  

Вот PHP-часть формы, в которой я беру элементы и цены из базы данных, а затем создаю флажки с именем элемента, затем у меня есть цены на обе платы ниже. И у меня также есть выпадающий список того, сколько лет и / или количество.

 if (pg_num_rows($result) > 0){
    echo "<div class="tx-row" style=width:100%; clear:both; " > <div style="width: 100%; float:left; clear:both; height:25px;" > </div>";
    while ($row = pg_fetch_object($result)){
        $contractid = $row->id;
        $item = $row->descr;
        $license_fee = $row->license;
        $service_fee = $row->service;
        $hours = $row->training;
        echo "<div class="tx-column tx-column-size-1-3" >
                <div id='item".$row->contractid."' style='width:100%;'>
                    <div style='width:10%; float:left;'>
                        <input style='height:25px; width:25px;' type='checkbox' id='item_add".$row->id."' name='item_add' value='add' /> 
                    </div>
                    <div style='width:90%; float:left;'>
                        <p style='width:115%;'><strong>$item</strong> <br /><span style='font-size:10px;'>Service Fee: amp;#36;$service_fee | License Fee: amp;#36;$license_fee</span></p>";
                        if ($contractid == "8" || $contractid == "10" ){
                            echo "<div style='width:100%; margin-top:-20px;'>
                                    <div style='width:50%; float:left;'>
                                        <span style='font-size:12px;'>Years: </span><select style='height:18px;' name='yrs' id='yrs".$row->id."'>
                                            <option value="1">1</option>
                                            <option value="2">2</option>
                                            <option value="3">3</option>
                                            <option value="4">4</option>
                                            <option value="5">5</option>
                                        </select>
                                    </div>
                                    <div style='width:50%; float:left;'>
                                        <span style='font-size:12px;'>Quantity: </span><select name='qty' id='qty".$row->id."' style='height:18px;'>
                                            <option value="1">1</option>
                                            <option value="2">2</option>
                                            <option value="3">3</option>
                                            <option value="4">4</option>
                                            <option value="5">5</option>
                                        </select>
                                    </div>
                                    <input type='hidden' name='item' id='item".$row->id."' value='".$row->descr."'>
                                    <input type='hidden' name='servicefee' id='servicefee".$row->id."' value='$service_fee'>
                                    <input type='hidden' name='licensefee' id='licensefee".$row->id."' value='$license_fee'>
                                    <input type='hidden' name='traininghrs' id='traininghrs".$row->id."' value='$hours'>
                                </div>
                                <div style='width:100%; height:25px; clear:both; float:left;'></div>";
                        } else {
                            echo "<div style='width:100%; margin-top:-20px;'>
                                        <span style='font-size:12px;'>Years: </span><select name='yrs' id='yrs".$row->id."' style='height:18px;'>
                                            <option value="1">1</option>
                                            <option value="2">2</option>
                                            <option value="3">3</option>
                                            <option value="4">4</option>
                                            <option value="5">5</option>
                                        </select>
                                        <input type='hidden' name='Qty' id='qty".$row->id."' value='1' >
                                        <input type='hidden' name='item' id='item".$row->id."' value='".$row->descr."'>
                                        <input type='hidden' name='servicefee'  id='servicefee'  value='".$row->service."'>
                                        <input type='hidden' name='licensefee' id='licensefee".$row->id."' value='".$row->license."'>
                                        <input type='hidden' name='traininghrs' id='traininghrs".$row->id."' value='".$row->training."'>
                                    </div>
                                    <div style='width:100%; height:25px; clear:both; float:left;'></div>";
                        }
                        echo "</div>";
                    echo "</div> ";

            echo "</div>";
    }
    echo "</div>";
}
  

Надеюсь, добавление php и html-формы поможет всем, кто может решить эту проблему.

Вот скрипка

https://jsfiddle.net/e9mmn55k/5/

Комментарии:

1. Когда вы добавляете сгенерированный html-код, вы добавляете что-то вроде <td></td><td></td>...<td></td></tr><tr> . Это неправильно сформированный HTML. Это должно быть что-то вроде <tr><td></td>...<td></td></tr> .

2. Я обновил их … // Отобразите каждый элемент, который отмечен, в таблице $(‘#add_item_here > tbody:last-child’).append(‘<tr><td>’ item ‘</td><td>’ yrs ‘</td><td>’ кол-во ‘</td><td>’ обучающие часы ‘</td><td>’ item_cost ‘</td></tr><tr>’); // Отображать итоговые значения в строке таблицы в таблице $(‘#add_totals_here > tbody: последний дочерний элемент’).append(‘<tr><td colspan=3 ></td><td>’ total_training ‘</td><td>’ total_cost ‘</td></ tr><tr>’);По-прежнему работает некорректно

Ответ №1:

 $(document).ready(function(){
		$('table[id^=add_item_here]').hide();
		$('table[id^=add_totals_here]').hide();

        //First obtaining indexes for each checkbox that is checked
        $('input[name=item_add]').change(function(){
			var index = this.id.replace('item_chk','');
			if($(this).is(':checked')){
				AddNewItem(index);
			}
			else{
				RemoveItem(index);
			}
			CalculateTotals();                                         
        });

		function AddNewItem(index){
            // Get hidden variables to use for calculation and tables.
            var item = $('#item_chk' index).parent().text().trim();
            var traininghrs = parseInt($('#traininghrs' index).val());
            var qty = parseInt($('#qty' index).val());
            var yrs = parseInt($('#yrs' index).val());

            var item_cost = 0;
            // Calculating item cost for just that one checkbox
            item_cost =parseInt($('#servicefee' index).val());
            item_cost*=parseInt($('#yrs' index).val()); 
            item_cost =parseInt($('#licensefee' index).val());
            item_cost*=parseInt($('#qty' index).val()); 
            var traininghrs = parseInt($('#traininghrs' index).val());          
            //Display each item that is checked into a table
            $('#add_item_here tr:last').after('<tr id="row_id' index   '"><td>'   item  '</td><td>'   yrs  '</td><td>'   qty  '</td><td>'   traininghrs   '</td><td>'  item_cost   '</td></tr>');		
		}
		
		function RemoveItem(index){
			$('table#add_item_here tr#row_id' index).remove();
		}
		
		function CalculateTotals(){
            var total_cost = 0;
            var total_training = 0;
            $('input:checkbox:checked').each(function(){
                var index = this.id.replace('item_chk','');
                var item_cost = 0;
                // Calculating item cost for just that one checkbox
                item_cost =parseInt($('#servicefee' index).val());
                item_cost*=parseInt($('#yrs' index).val()); 
                item_cost =parseInt($('#licensefee' index).val());
                item_cost*=parseInt($('#qty' index).val()); 
                var traininghrs = parseInt($('#traininghrs' index).val());

                total_cost  =item_cost;
                total_training  =traininghrs;
            });	

            if(total_cost > 0 || total_training > 0) {
				$('#add_totals_here tr:has(td)').remove();
                $('#add_totals_here tr:has(th)').after('<tr><td colspan="3">'   total_training   '</td><td>'  total_cost   '</td></tr>');
                $('#add_item_here').show();
                $('#add_totals_here').show();
            }
            else{
                $('table[id^=add_item_here]').hide();
                $('table[id^=add_totals_here]').hide();
            }			
		}
		
		// Quantity change, if someone changes the quantity
		$('select[name=qty]').change(function(){
			var index = this.id.replace('qty','');
			if($("#item_chk" index).is(':checked')){
				RemoveItem(index);
				AddNewItem(index);
				CalculateTotals();
			}
		});

		// Years change, if someone changes the years           
		$('select[name=yrs]').change(function(){
			var index = this.id.replace('yrs','');
			if($("#item_chk" index).is(':checked')){
				RemoveItem(index);
				AddNewItem(index);
				CalculateTotals();
			}			
		});		
    })  
 td {
  text-align: left;
}  
 <html>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
	<script src="Calculate.js"></script>
	<body>
<div style="width: 100%; float:left; clear:both;" class="IlIaNd box">
	<div id="item11" style="width:50%;">
        <div style="width:50%; float:left;">
			<input style="height:25px; width:25px;" type="checkbox" id="item_chk11" name="item_add" value="add" /> Adance Search HTML
		</div>
        <div style="width:50%; float:left;">
            <div style="width:50%; float:left;">
				<span style="font-size:12px;">Years: </span><select style="height:18px;" name="yrs" id="yrs11">
					<option value="1">1</option>
					<option value="2">2</option>
					<option value="3">3</option>
					<option value="4">4</option>
					<option value="5">5</option>
				</select>
			</div>
			<div style="width:50%; float:left;">
				<span style="font-size:12px;">Quantity: </span><select name="qty" id="qty11" style='height:18px;'>
					<option value="1">1</option>
					<option value="2">2</option>
					<option value="3">3</option>
					<option value="4">4</option>
					<option value="5">5</option>
				</select>
			</div>
			<input type="hidden" name="itemdescr" id="itemdescr11" value="Adance Search HTML">
			<input type="hidden" name="servicefee" id="servicefee11" value="1000">
			<input type="hidden" name="licensefee" id="licensefee11" value="3000">
			<input type="hidden" name="traininghrs" id="traininghrs11" value="8">
		</div>
		<div style="width:100%; height:25px; clear:both; float:left;"></div>
    </div>
	<div id="item12" style="width:50%;">
        <div style="width:50%; float:left;">
			<input style="height:25px; width:25px;" type="checkbox" id="item_chk12" name="item_add" value="add" /> Adance Search PHP
		</div>
        <div style="width:50%; float:left;">
            <div style="width:50%; float:left;">
				<span style="font-size:12px;">Years: </span><select style="height:18px;" name="yrs" id="yrs12">
					<option value="1">1</option>
					<option value="2">2</option>
					<option value="3">3</option>
					<option value="4">4</option>
					<option value="5">5</option>
				</select>
			</div>
			<div style="width:50%; float:left;">
				<span style="font-size:12px;">Quantity: </span><select name="qty" id="qty12" style='height:18px;'>
					<option value="1">1</option>
					<option value="2">2</option>
					<option value="3">3</option>
					<option value="4">4</option>
					<option value="5">5</option>
				</select>
			</div>
			<input type="hidden" name="itemdescr" id="item_descr12" value="Adance Search PHP">
			<input type="hidden" name="servicefee" id="servicefee12" value="1500">
			<input type="hidden" name="licensefee" id="licensefee12" value="1000">
			<input type="hidden" name="traininghrs" id="traininghrs12" value="2">
		</div>
		<div style="width:100%; height:25px; clear:both; float:left;"></div>
    </div>
	<div id="item14" style="width:50%;">
        <div style="width:50%; float:left;">
			<input style="height:25px; width:25px;" type="checkbox" id="item_chk14" name="item_add" value="add" /> Adance Search WWW
		</div>
        <div style="width:50%; float:left;">
            <div style="width:50%; float:left;">
				<span style="font-size:12px;">Years: </span><select style="height:18px;" name="yrs" id="yrs14">
					<option value="1">1</option>
					<option value="2">2</option>
					<option value="3">3</option>
					<option value="4">4</option>
					<option value="5">5</option>
				</select>
			</div>
			<div style="width:50%; float:left;">
				<span style="font-size:12px;">Quantity: </span><select name="qty" id="qty14" style='height:18px;'>
					<option value="1">1</option>
					<option value="2">2</option>
					<option value="3">3</option>
					<option value="4">4</option>
					<option value="5">5</option>
				</select>
			</div>
			<input type="hidden" name="itemdescr" id="item_descr14" value="Adance Search WWW">
			<input type="hidden" name="servicefee" id="servicefee14" value="0">
			<input type="hidden" name="licensefee" id="licensefee14" value="250">
			<input type="hidden" name="traininghrs" id="traininghrs14" value="0">
		</div>
		<div style="width:100%; height:25px; clear:both; float:left;"></div>
    </div>
	<div id="item15" style="width:50%;">
        <div style="width:50%; float:left;">
			<input style="height:25px; width:25px;" type="checkbox" id="item_chk15" name="item_add" value="add" /> Adance Search HTTP
		</div>
        <div style="width:50%; float:left;">
            <div style="width:50%; float:left;">
				<span style="font-size:12px;">Years: </span><select style="height:18px;" name="yrs" id="yrs15">
					<option value="1">1</option>
					<option value="2">2</option>
					<option value="3">3</option>
					<option value="4">4</option>
					<option value="5">5</option>
				</select>
			</div>
			<div style="width:50%; float:left;">
				<span style="font-size:12px;">Quantity: </span><select name="qty" id="qty15" style='height:18px;'>
					<option value="1">1</option>
					<option value="2">2</option>
					<option value="3">3</option>
					<option value="4">4</option>
					<option value="5">5</option>
				</select>
			</div>
			<input type="hidden" name="itemdescr" id="item_descr15" value="Adance Search HTTP" >
      <input type="hidden" name="servicefee" id="servicefee15" value="1000">
			<input type="hidden" name="licensefee" id="licensefee15" value="0">
			<input type="hidden" name="traininghrs" id="traininghrs15" value="10">
		</div>
		<div style="width:100%; height:25px; clear:both; float:left;"></div>
    </div>
</div>
<center>
	<table  id="add_item_here" style="width:98%;"  border="1">
		<tbody>
			<tr><th>Item</th><th>Years</th><th>Quantity</th><th>Training Hours</th><th>Total Item Cost</th></tr>	
		</tbody>
	</table>
</center>
<center>
	<table  id="add_totals_here" style="width:98%;" border="1">
		<tbody>
			<tr><th colspan="3">Training Hours</th><th>Total Cost</th></tr>	
		</tbody>
	</table>
</center>
	</body>
</html>  

Комментарии:

1. @ShadyNicNack пожалуйста, проверьте код и дайте мне знать, работает ли он для вас?

2. Я вижу верхнюю и нижнюю границы таблицы, но внутри них по-прежнему не отображаются итоговые значения стоимости товара и итоговые значения общей стоимости.

3. Каким-то образом он либо не считывает мои вычисления, либо не считывает отображаемую часть.

4. Можете ли вы добавить полный HTML-код или создать для него скрипку, чтобы проверить, почему не отображается вычисление

5. Я добавил часть кода HTML-формы и часть кода PHP, которая подключается к базе данных и извлекает информацию о ценах.

Ответ №2:

ОК… Наконец-то получил общее количество часов и стоимость работы в моем калькуляторе ценовых предложений…

  function CalculateTotals(){
        var total_cost = 0;
        var total_training = 0;
        $('input:checkbox:checked').each(function(){
            var index = this.id.replace('item_chk','');
            var item_cost = 0;
            // Calculating item cost for just that one checkbox
            item_cost =parseInt($('#servicefee' index).val());
            item_cost*=parseInt($('#yrs' index).val()); 
            item_cost =parseInt($('#licensefee' index).val());
            item_cost*=parseInt($('#qty' index).val()); 
            var traininghrs = parseInt($('#traininghrs' index).val());

            total_cost  =item_cost;
            total_training  =traininghrs;


        }); 

        if(total_cost > 0 || total_training > 0) {
            $('#add_totals_here tr:last').children().remove();
            $('#add_totals_here tr:last').after('<tr ><td colspan="3" style="width:66%;">TOTALS:</td><td style="width:18%;">'   total_training   '</td><td style="width:16%;">$'  total_cost   '</td></tr>');
            $('#add_item_here').show();
            $('#add_totals_here').show();
        }
        else{
            $('table[id^=add_item_here]').hide();
            $('table[id^=add_totals_here]').hide();
        }   
  

Чтобы получить полный ответ, не стесняйтесь, напишите мне… Но хочу крикнуть mbadeveloper. Он мне очень помог и помог мне немного лучше понять jquery. Спасибо mbadeveloper.