Woocommerce | Plus Minus remove negative numbers (min_value) - javascript

I ask you for help please, I haven't come out of it for hours.
I set the quantity selector on the Woocommerce shop page,
which automatically puts the item in the cart and / or removes it.
I have a big problem, when I am on zero and I press - the numbers go negative, I would make sure that it cannot go below zero.
Thanks so much!!
Function.php
// Remove Add To cart Button
remove_action('woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10);
// Add our Quanity Input
add_action('woocommerce_after_shop_loop_item', 'QTY');
function QTY()
{
global $product;
?>
<div class="shopAddToCart">
<button value="-" class="minus2" >-</button>
<input type="text"
disabled="disabled"
size="2"
value="<?php echo (Check_if_product_in_cart($product->get_id())) ? Check_if_product_in_cart($product->get_id())['QTY'] : 0;
?>"
id="count"
data-product-id= "<?php echo $product->get_id() ?>"
data-in-cart="<?php echo (Check_if_product_in_cart($product->get_id())) ? Check_if_product_in_cart($product->get_id())['in_cart'] : 0;
?>"
data-in-cart-qty="<?php echo (Check_if_product_in_cart($product->get_id())) ? Check_if_product_in_cart($product->get_id())['QTY'] : 0;
?>"
class="quantity qty qty-botton"
max_value = "<?php echo ($product->get_max_purchase_quantity() == -1) ? 1000 : $product->get_max_purchase_quantity(); ?>"
min_value = <?php echo $product->get_min_purchase_quantity(); ?>
>
<button type="button" value="+" class="plus2" >+</button>
</div>
<?php
}
//Check if Product in Cart Already
function Check_if_product_in_cart($product_ids)
{
foreach (WC()->cart->get_cart() as $cart_item):
$items_id = $cart_item['product_id'];
$QTY = $cart_item['quantity'];
// for a unique product ID (integer or string value)
if ($product_ids == $items_id):
return ['in_cart' => true, 'QTY' => $QTY];
endif;
endforeach;
}
//Add Event Handler To update QTY
add_action('wc_ajax_update_qty', 'update_qty');
function update_qty()
{
ob_start();
$product_id = absint($_POST['product_id']);
$product = wc_get_product($product_id);
$quantity = $_POST['quantity'];
foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item):
if ($cart_item['product_id'] == $product_id) {
WC()->cart->set_quantity($cart_item_key, $quantity, true);
}
endforeach;
wp_send_json('done');
}
*.js jQuery on Footer
jQuery(document).ready(function ($) {
"use strict";
// Add Event Listner on the Plush button
$('.plus2').click(function () {
if (parseInt($(this).prev().val()) < parseInt($(this).prev().attr('max_value'))) {
$(this).prev().val(+$(this).prev().val() + 1);
var currentqty = parseInt($(this).prev().attr('data-in-cart-qty')) + 1;
var id = $(this).prev().attr('data-product-id');
var data = {
product_id: id,
quantity: 1
};
$(this).prev().attr('data-in-cart-qty', currentqty);
$(this).parent().addClass('loading');
$.post(wc_add_to_cart_params.wc_ajax_url.toString().replace('%%endpoint%%', 'add_to_cart'), data, function (response) {
if (!response) {
return;
}
if (response) {
var url = woocommerce_params.wc_ajax_url;
url = url.replace("%%endpoint%%", "get_refreshed_fragments");
$.post(url, function (data, status) {
$(".woocommerce.widget_shopping_cart").html(data.fragments["div.widget_shopping_cart_content"]);
if (data.fragments) {
jQuery.each(data.fragments, function (key, value) {
jQuery(key).replaceWith(value);
});
}
jQuery("body").trigger("wc_fragments_refreshed");
});
$('.plus2').parent().removeClass('loading');
}
});
}
});
$('.minus2').click(function () {
$(this).next().val(+$(this).next().val() - 1);
var currentqty = parseInt($(this).next().val());
var id = $(this).next().attr('data-product-id');
var data = {
product_id: id,
quantity: currentqty
};
$(this).parent().addClass('loading');
$.post(wc_add_to_cart_params.wc_ajax_url.toString().replace('%%endpoint%%', 'update_qty'), data, function (response) {
if (!response) {
return;
}
if (response) {
var url = woocommerce_params.wc_ajax_url;
url = url.replace("%%endpoint%%", "get_refreshed_fragments");
$.post(url, function (data, status) {
$(".woocommerce.widget_shopping_cart").html(data.fragments["div.widget_shopping_cart_content"]);
if (data.fragments) {
jQuery.each(data.fragments, function (key, value) {
jQuery(key).replaceWith(value);
});
}
jQuery("body").trigger("wc_fragments_refreshed");
});
$('.plus2').parent().removeClass('loading');
}
});
});
});

Just add a check before running the line:
$(this).next().val(+$(this).next().val() - 1);
that will become:
if ( $(this).next().val() > 0 ) {
$(this).next().val(+$(this).next().val() - 1);
}
Also note that you are using an identical id for each quantity input of each product. The id attribute value should be unique on the page.
Here you can find some methods of adding plus and minus buttons in the quantity field of the add to cart form (which you could take inspiration from):
Custom plus and minus quantity buttons in Woocommerce 3
WooCommerce plus and minus buttons
WooCommerce: Add to Cart Plus & Minus Buttons

Thanks Vincenzo Di Gaetano.
I solved it like this:
$('.minus2').click(function () {
var $minus2 = $(this);
var oldValue = $minus2.parent().find("input").val();
if (oldValue > 0) {
$(this).next().val(+$(this).next().val() - 1);
.....

Related

Have two variables in one foreach bad insert

Hello i have a trouble with my code.
I have HTML with JS:
$(document).ready(function () {
// allowed maximum input fields
var max_input = 5;
// initialize the counter for textbox
var x = 1;
// handle click event on Add More button
$('.add-btn').click(function (e) {
e.preventDefault();
if (x < max_input) { // validate the condition
x++; // increment the counter
$('.wrapper').append(`
<div class="input-box">
<input type="text" name="input_name[]"/>
<input type="text" name="input_price[]">
Remove
</div>
`); // add input field
}
});
// handle click event of the remove link
$('.wrapper').on("click", ".remove-lnk", function (e) {
e.preventDefault();
$(this).parent('div').remove(); // remove input field
x--; // decrement the counter
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
<div class="input-box">
<input type="text" name="input_name[]">
<input type="text" name="input_price[]">
<button class="btn add-btn">+</button>
</div>
</div>
and i need insert in DB all inputs (name and price)
Now if i trying insert only first line.
php script:
This is a function and $id_produkt is GET from url.
if (isset($_POST["input_name"]) && is_array($_POST["input_name"])){
$input_name = $_POST["input_name"];
$input_price = $_POST["input_price"];
foreach (array_combine($input_name, $input_price) as $field_name => $field_price){
$sql = "INSERT INTO variant_product ( id_product, name, price ) VALUES(?,?,?)";
$data = array("isi", $id_produkt, $field_name, $field_price);
$result = db_query($sql, $data);
return $result;
}
}
Can help me please ? I am tired
I make function like that and working.
function insertVariantsProduct($id_produkt){
$userData = count($_POST["input_name"]);
if ($userData > 0) {
for ($i=0; $i < $userData; $i++) {
if (trim($_POST['input_name'] != '') && trim($_POST['input_price'] != '')) {
$var_id = $_POST["input_id"][$i];
$name = $_POST["input_name"][$i];
$price = $_POST["input_price"][$i];
if(empty($var_id) && !isset($var_id)){
$sql = "INSERT INTO variant_product ( id_product, name, price ) VALUES(?,?,?)";
$data = array("isi", $id_produkt, $name, $price);
}else {
$sql = "UPDATE variant_product SET name='$name',price='$price' WHERE id='$var_id' ";
$data = null;
}
$result = db_query($sql, $data);
}
}
return $result; // This should be out of loop because it's will break the loop
}
}

Refresh part of page when user navigated back to it

In my shop page, for each product I have cart quantities that the user can change without add to cart button (it's with display none and activated by js).
my problem is that if a user changed item quantity in single product page and navigated back into shop page it show the wrong quantity from cache.
Right now i'm reloadin the whole page using this code:
jQuery( document ).ready(function( $ ) {
$(document).ready(function () {
if(performance.navigation.type == 2 || performance.navigation.type == 0){
var isquanpage = document.getElementsByClassName('store-quantity');
if (isquanpage.length > 0) {
console.log(isquanpage);
$("#a2cloader").show();
location.reload(true);
document.addEventListener('DOMContentLoaded', function() {
$("#a2cloader").hide();
}, false);
}
}
});
});
I want to refresh just the quantities and not the whole page:
<div class="quantity-div" >
<i class="fas fa-plus sumsum-quantity-b" value="+" onclick="store_quantity_b('+', this.parentNode.querySelector('input[type=number]').id);"></i>
<input class="sumsum-quantity store-quantity" form="<?php echo $product->id; ?>" inputmode="decimal" style="padding:0;border-radius:5px;" type="number" min="0" value="<?php echo $cartquan ?>"
name="<?php echo $varid; ?>" onclick="this.select()" id="quantity-<?php echo $varid ?>" data-cartquan="<?php echo $cartquan ?>" data-varititle="<?php echo get_the_title( $attribute_value['variation_id']); ?>">
<i class="fas fa-minus sumsum-quantity-b" value="-" onclick="store_quantity_b('-', this.parentNode.querySelector('input[type=number]').id);"></i>
</div>
And what i tried to do is this:
quanfield = document.getElementsByClassName("store-quantity");
cartquantities =<?php echo json_encode(WC()->cart->get_cart_item_quantities();); ?>;
console.log(cartquantities);
But it gets the cached version of the cart and not the updated one.
OK, i found a solution, I'm using hook on woocommerce add to cart fragments like this:
// cart quantities
add_filter( 'woocommerce_add_to_cart_fragments', woocommerce_cartquant_fragment' );
function woocommerce_cartquant_fragment( $fragments ) {
global $woocommerce;
ob_start();
?>
<p id="cartquantities" style="display:none"><?php echo json_encode(WC()->cart->get_cart_item_quantities()); ?></p>
<?php
$fragments['p#cartquantities'] = ob_get_clean();
return $fragments;
}
and then using this script:
//refresh page from history
jQuery( document ).ready(function( $ ) {
$(document).ready(function () {
if(performance.navigation.type == 2 || performance.navigation.type == 0){
let quanfield, quanname,cartquantities,store,obj;
let findname =[];
$("#a2cloader").show();
timeout = setTimeout(function() {
cartquantities = document.getElementById("cartquantities").innerText;
cartquantities = cartquantities.replace("{","");
cartquantities = cartquantities.replace("}","");
cartquantities = cartquantities.replace(/['"]+/g, '');
cartquantities = cartquantities.split(",");
for (i = 0; i < cartquantities.length; i++) {
cartquantities[i] = cartquantities[i].split(":");
findname[i] = cartquantities[i][0];
}
//console.log(findname);
quanfield = document.getElementsByClassName("store-quantity");
//console.log(quanfield.length);
for (i = 0; i < quanfield.length; i++) {
quanname = quanfield[i].name;
obj = findname.findIndex(o => o==quanname);
//console.log(obj);
if (obj !=-1){
quanfield[i].value=cartquantities[obj][1];
quanfield[i].setAttribute("data-cartquan", cartquantities[obj][1]);
}else{
quanfield[i].value=0;
quanfield[i].setAttribute("data-cartquan", 0);
}
$("#a2cloader").hide();
}
}, 1500 );
}
});
});
Is there a possibility to make javascript wait for the fragments instead of setting timeout?
SOLVED! used interval to check when fragments are updated
<script>
//refresh page from history
jQuery( document ).ready(function( $ ) {
$(document).ready(function () {
if(performance.navigation.type == 2 || performance.navigation.type == 0){
let quanfield, quanname,cartquantities,store,obj,timer;
let findname =[];
$("#a2cloader").show();
//var t=0;
timer = setInterval(checkfrags, 5);
function checkfrags(){
//t+=5;
if(document.getElementById("cartquantities").innerText=="null") {
//console.log(t);
}else{
cartquantities = document.getElementById("cartquantities").innerText;
cartquantities = cartquantities.replace("{","");
cartquantities = cartquantities.replace("}","");
cartquantities = cartquantities.replace(/['"]+/g, '');
cartquantities = cartquantities.split(",");
for (i = 0; i < cartquantities.length; i++) {
cartquantities[i] = cartquantities[i].split(":");
findname[i] = cartquantities[i][0];
}
//console.log(findname);
quanfield = document.getElementsByClassName("store-quantity");
//console.log(quanfield.length);
for (i = 0; i < quanfield.length; i++) {
quanname = quanfield[i].name;
obj = findname.findIndex(o => o==quanname);
//console.log(obj);
if (obj !=-1){
quanfield[i].value=cartquantities[obj][1];
quanfield[i].setAttribute("data-cartquan", cartquantities[obj][1]);
}else{
quanfield[i].value=0;
quanfield[i].setAttribute("data-cartquan", 0);
}
$("#a2cloader").hide();
}
//console.log(document.getElementById("cartquantities").innerText+"done "+t);
document.getElementById("cartquantities").innerText="null";
clearInterval(timer);
}
}
}
});
});
</script>
<p id="cartquantities" style="display:none">null</p>

Submit span content to a database

Just for fun, I'm trying to build a simple time tracker; the page grabs a stored duration from a database, and you can then add more time to that value, and then store it back to the database.
The value is displayed in h:i:s format, but there's also a hidden span with the same time but just in seconds.
My problem:
I cannot figure out how to submit the contents of the span to the database.
If I instead put the hidden span contents inside a form input, then the content doesn't change; it just submits the original value back to the database.
I really feel like I'm making a bit of a meal out of this.
Here's the current code...
<?php
/*
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table (t TIME NOT NULL DEFAULT 0);
INSERT INTO my_table VALUES ('00:01:50');
*/
require('path/to/connection/stateme.nts');
//wip - for later - and remember to remove the injection!!!
if(sizeof($_POST) != 0){
$query = "UPDATE my_table SET t=SEC_TO_TIME({$_GET['tts']}) LIMIT 1";
$pdo->query($query);
}
//Grab the stored value from the database
$query = "
select t
, time_to_sec(t) tts
, LPAD(HOUR(t),2,0) h
, LPAD(MINUTE(t),2,0) i
, LPAD(SECOND(t),2,0) s
from my_table
limit 1
";
if ($data = $pdo->query($query)->fetch()) {
$t = $data['t'];
$tts = $data['tts'];
$h = $data['h'];
$i = $data['i'];
$s = $data['s'];
} else {
$t = 0;
$tts = 0;
$h = '00';
$i = '00';
$s = '00';
}
?>
#relevant code starts here, I guess
<div>
<div>
<span hidden id="tts"><?php echo $tts; ?></span>
<span id="hour"><?php echo $h; ?></span>:
<span id="min"><?php echo $i; ?></span>:
<span id="sec"><?php echo $s; ?></span>
<input id="startButton" type="button" value="Start/Resume">
<input id="pauseButton" type="button" value="Pause">
<button id="submit" onclick="myFunction()" >Save</button>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
var Clock = {
totalSeconds: <?php echo $tts ?>,
start: function () {
if (!this.interval) {
var self = this;
function pad(val) { return val > 9 ? val : "0" + val; }
this.interval = setInterval(function () {
self.totalSeconds += 1;
$("#hour").text(pad(Math.floor(self.totalSeconds / 3600 % 60)));
$("#min").text(pad(Math.floor(self.totalSeconds / 60 % 60)));
$("#sec").text(pad(parseInt(self.totalSeconds % 60)));
$("#tts").text(pad(parseInt(self.totalSeconds)));
}, 1000);
}
},
pause: function () {
clearInterval(this.interval);
delete this.interval;
},
resume: function () {
this.start();
}
};
$('#startButton').click(function () { Clock.start(); });
$('#pauseButton').click(function () { Clock.pause(); });
</script>
<script>
function myFunction() {
document.querySelectorAll('div').forEach(div => {
div.querySelectorAll('span')
.forEach(span => console.log(span.textContent));
});
}
</script>
With CBroe's useful hint, the following works... although my attempts at preparing and binding $_GET are failing at the moment, so the query itself remains insecure...
<?php
/*
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table (t TIME NOT NULL DEFAULT 0);
INSERT INTO my_table VALUES ('00:01:50');
*/
require('path/to/connection/stateme.nts');
if(sizeof($_GET) != 0){
$query = "UPDATE my_table SET t = SEC_TO_TIME({$_GET['tts']}) LIMIT 1";
$stmt = $pdo->prepare($query);
$stmt->execute();
}
//Grab the stored value from the database
$query = "
select t
, time_to_sec(t) tts
, LPAD(HOUR(t),2,0) h
, LPAD(MINUTE(t),2,0) i
, LPAD(SECOND(t),2,0) s
from my_table
limit 1
";
if ($data = $pdo->query($query)->fetch()) {
$t = $data['t'];
$tts = $data['tts'];
$h = $data['h'];
$i = $data['i'];
$s = $data['s'];
} else {
$t = 0;
$tts = 0;
$h = '00';
$i = '00';
$s = '00';
}
?>
#relevant code starts here, I guess
<form id="myForm">
<input name="tts" type= "hidden" id="tts" value="tts">
<span id="hour"><?php echo $h; ?></span>:
<span id="min"><?php echo $i; ?></span>:
<span id="sec"><?php echo $s; ?></span>
<input id="startButton" type="button" value="Start/Resume">
<input id="pauseButton" type="button" value="Pause">
<button id="submit" onclick="myFunction()" >Save</button>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
var Clock = {
totalSeconds: <?php echo $tts ?>,
start: function () {
if (!this.interval) {
var self = this;
function pad(val) { return val > 9 ? val : "0" + val; }
this.interval = setInterval(function () {
self.totalSeconds += 1;
$("#hour").text(pad(Math.floor(self.totalSeconds / 3600 % 60)));
$("#min").text(pad(Math.floor(self.totalSeconds / 60 % 60)));
$("#sec").text(pad(parseInt(self.totalSeconds % 60)));
$("#tts").val(pad(parseInt(self.totalSeconds)));
}, 1000);
}
},
pause: function () {
clearInterval(this.interval);
delete this.interval;
},
resume: function () {
this.start();
}
};
$('#startButton').click(function () { Clock.start(); });
$('#pauseButton').click(function () { Clock.pause(); });
</script>
<script>
function myFunction() {
document.getElementById("myForm").submit();
}
}
</script>

Check value with checkbox click

The problem in question is not to allow me to click on a checkbox if the atendimento number (atendimento.value) is different from a previously entered number.
When I first click on 1 checkbox I store this value and a push to an array.
If I click on another checkbox and the atendimento.value is different, it will display the error message with toast.
I would like to know what I'm forgetting / missing in my code.
ng.checkAtendimento = function(id) {
var atendimento = document.getElementById('atendimento-' + id);
var checkOs = document.getElementById('checkOs-' + id);
var array = [];
if(checkOs.checked){
array.push(atendimento.value);
console.log(array);
}else{
var index = array.indexOf(atendimento.value);
array.splice(index, 1);
console.log(array);
}
if(array[0] != atendimento.value){
console.log(array[0]);
toastr.error(
'error',
'service', {
closeButton: true,
progressBar: true,
timeOut: 7000
});
checkOs.checked = false;
}
}
HTML/PHP
<input id="checkOs-<?php echo $entity->getId(); ?>"
ng-click="checkAtendimento('<?php echo $entity->getId(); ?>');"
type="checkbox"
class="array-ordemservico"
name="[]array-ordemservico"
value="<?php echo $entity->getId();?>" />
<input id="atendimento-<?php echo $entity->getId(); ?>"
class="array-atendimento"
style="display:none" type="checkbox"
value="<?php echo $entity->getAtendimento(); ?>" />
ng.checkAtendimento = function(id){
var atendimento = document.getElementById('atendimento-' + id);
$("#checkOs-" + id).on("change", function (){
index = $.inArray(atendimento.value, ArrayCheckbox);
if ($("#checkOs-" + id).prop('checked')){
if (ArrayCheckbox.length > 0 && index === -1 && atendimento.value != ""){
toastr.error(
'error',
'OS',{
closeButton: true,
progressBar: true,
timeOut: 7000
});
$("#checkOs-" + id).prop("checked", false);
} else if(ArrayCheckbox.length == 0 && atendimento.value != ""){
ArrayCheckbox.push(atendimento.value);
}
} else if((ArrayCheckbox[0] == atendimento.value)){
ArrayCheckbox.splice(index, 1);
}
});
}

Show the price in a textbox after selecting the id from a selected menu

I have two selected menu the 1st one we chose the type so the next will filter the mysql database to show the depertments numbers, and i need to show the depertment price in a textfiled after i select the depertment number from the second selectedmenu.
1st selected menu
<select name="gender" id="gender" class="update">
<option value="">Select one</option>
<?php if (!empty($list)) { ?>
<?php foreach($list as $row) { ?>
<option value="<?php echo $row['id']; ?>"> <?php echo $row['name']; ?>
<?php } ?>
</option>
<?php } ?>
</select>
2nd selected menu
<select name="category"
disabled="disabled" class="update" id="category" onChange="precio()" onClick="show()" >
<option value="">----</option>
</select>
this is how i get the value for the 2nd selected value
update.php
<?php
if (!empty($_GET['id']) && !empty($_GET['value'])) {
$id = $_GET['id'];
$value = $_GET['value'];
try {
$objDb = new PDO('mysql:host=localhost;dbname=name', 'root', '1234');
$objDb->exec('SET CHARACTER SET utf8');
$sql = "SELECT *
FROM `depertamientos`
WHERE `master` = ?";
$statement = $objDb->prepare($sql);
$statement->execute(array($value));
$list = $statement->fetchAll(PDO::FETCH_ASSOC);
if (!empty($list)) {
$out = array('<option value="">Select one</option>');
foreach($list as $row) {
if ($row['visible'] == 0) {
$out[] = '<option value="'.$row['name'].'" id="'.$row['precio'].'">'.$row['name'].'</option>';
}
}
echo json_encode(array('error' => false, 'list' => implode('', $out)));
} else {
echo json_encode(array('error' => true));
}
} catch(PDOException $e) {
echo json_encode(array('error' => true));
}
} else {
echo json_encode(array('error' => true));
}
core.js
var formObject = {
run : function(obj) {
if (obj.val() === '') {
obj.nextAll('.update').html('<option value="">----</option>').attr('disabled', true);
} else {
var id = obj.attr('id');
var v = obj.val();
jQuery.getJSON('mod/update.php', { id : id, value : v}, function(data) {
if (!data.error) {
obj.next('.update').html(data.list).removeAttr('disabled');
} else {
obj.nextAll('.update').html('<option value="">----</option>').attr('disabled', true);
}
});
}
}
};
$(function() {
$('.update').live('change', function() {
formObject.run($(this));
});
});
js function
> <script src="javascripts/jquery-1.6.4.min.js" type="text/javascript"></script>
<script type="text/javascript">
function show() {
var select = document.getElementById('category');
var input = document.getElementById('ds');
var change = document.getElementById('dpto');
var deptprecio = document.getElementById('11');
select.onchange = function() {
input.value = select.value;
deptprecio.value = "I don't know what to do here ???? ";
change.value = select.value;
}
}
</script>
my data base :
id master name visible precio
-------------------------------------------------
1 0 Type a 0 0
2 0 type b 0 0
3 1 101 1 20000
4 1 201 1 10000
5 2 103 1 30000
why putting the price as the id of your options tag ? Why not putting it in the value propertie as in #WebDevRon example?
$out[] = '<option value="'.$row['name'].'">'.$row['name'].'</option>';
remove javascript event in your your HTML tag:
<select name="category"
disabled="disabled" class="update" id="category" >
<option value="">----</option>
</select>
and if i understand your request you could just replace your javascript function "show" by something like this:
$("#category").change(function () {
var price = $(this).val();
$('#price-input').val(price); // where "price-input" is the id of your input.
});
Edit:
use data-attibute to store the price:
$out[] = '<option value="'.$row['name'].'" data-price="'.$row['precio'].'">'.$row['name'].'</option>';
JS:
$(function() {
$('.update').live('change', function() {
formObject.run($(this));
});
$("#category").change(function () {
var dept_number = $(this).val();
var price = $(this).find(':selected').data('price');
$('#dept-input').val(dept_number);
$('#price-input').val(price);
});
});
FIDDLE DEMO
Here is your complete solution - Demo
var $select2 = $('#select2');
var $text = $('#price');
$("#select1").change(function () {
var id = $(this).val();
if ($select2.data('options') == undefined) {
$select2.data('options', $select2.find('option').clone());
}
var options = $select2.data('options').filter('[value=' + id + ']');
$select2.html(options);
$text.val(id);
});

Categories