Jonas Dulay February 2016

Change select value to null if there is no data found on it

Guys I want to change the selected value into null if there is no data-quantity not found in the select field. For example I enter 10 on the quantity field There is no data-quantity = "10" in my select option tag so it should be null and the total price should be equal to 0 .
enter image description here

Price of the item:

 <input type="hidden" name="price" id="price"class="price" value="<?php if($price!=""){echo $price;}else{echo $shop_item_orig_price;}?>">

Quantity:

<input type="number" name="quant" id="quant" /> // for example I enter 2

Shipping details:

<select name="shipment" disable>
 <option value="100"  data-quantity="1"> 100 per 1 item </option>
 <option value="150"  data-quantity="2"> 150 per 2 item </option> //this must be selected
</select>

<script>
function myFunction(quantInput)
{
  var price = document.getElementById("price");
  var quantity = document.getElementById("quant");
  var shipment = document.getElementById("shipmentSelect");
  var total = document.getElementById("total");
    $("#shipmentSelect").find("option[data-quantity=" + quantInput + "]").attr('selected', 'selected').siblings().removeAttr('selected');
  var shipmentValue = shipment.value;
  salePrice = price.value;
  var totalPrice = (salePrice*quantInput) + parseInt(shipmentValue);
  total.value = totalPrice;
}
</script>

Total Price:

<input id="total" name="answer" style="margin-top:10px;margin-left:5px;"readonly />

Answers


urfusion February 2016

I think you are looking for something like

<input type="number" name="quant" value="" id="quant" />
<select name="shipment" class="select_custom" disable>
    <option value="100"  data-quantity="1"> 100 per 1 item </option>
    <option value="150"  data-quantity="2"> 150 per 2 item </option> //this must be selected
</select>

<input type="hidden" name="price" id="price"class="price" value="<?php if($price!=""){echo $price;}else{echo $shop_item_orig_price;}?>">

<script>
    $(document).ready(function () {
        $("#quant").focusout(function () {
            var qty = $(this).val();
            var price = $("#price").val();
            $(".select_custom option").each(function () {
                console.log($(this).attr('data-quantity'));
                if ($(this).attr('data-quantity') == qty) {
                    $("#quant").val(qty);
                    $("#price").val(price);
                    return false;
                } else {
                    $("#quant").val(0);
                    $("#price").val(0);
                    $(".select_custom").append('<option value=null selected>Null</option>').selectmenu('refresh');
                }
            });
        });
    });
</script>

check working jsfiddle

Post Status

Asked in February 2016
Viewed 2,620 times
Voted 12
Answered 1 times

Search




Leave an answer