I am trying jquery .val(vaue) function to set value of an attribute using the following code.
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".qty-btn").click(function(){
var $qtyBox = $(".qty-btn").parent().find(".qty-box");
var $qtyBoxQty = $qtyBox.text();
var newVal = $qtyBoxQty;
var form = $(".qty-btn").closest("form");
if($qtyBoxQty > 0){
newVal = eval(parseInt($qtyBoxQty) - 1);
$qtyBox.text(newVal);
}
alert( newVal );
$(".qty-btn").parent().find(".quantity").val(newVal);
alert( "value = " + $(".qty-btn").parent().find(".quantity").val() );
});
$("button").click(function(){
$("input:text").val("Glenn Quagmire");
});
});
</script>
</head>
<body>
<table class="table table-shopping-cart">
<form action="" method="post" >
<div class="control-group quantity">
<div class="controls">
<a href="#" class="qty-btn qty-btn-minus">-</a>
<div class="qty-box">7</div>
<a href="#" class='qty-btn qty-btn-plus blur'>+</a>
<span style="display:none;" class="maxQty">1</span>
<select name="quantity" style="width: 60px" class="quantity" scliid="261021" id="quantity" >
<option value="3" selected="selected" >4</option>
</select>
</div>
</div>
</form>
</table>
</body>
</html>
Now this code is not producing the desired result as the code line:
$(".qty-btn").parent().find(".quantity").val(newVal);
is not working. whereas following works:
alert( "value = " + $(".qty-btn").parent().find(".quantity").val() );
What is that I am doing wrong here?
Actually .quantity
is a select
and when you set value for select it means that an option
with that value must be present in select
but here you have only one option in select and its value is 3
and when you set value of select to newVal
it is not in select.
<select name="quantity" id="quantity" style="width: 60px" class="quantity" scliid="261021" id="quantity" >
<option value="3" selected="selected" >4</option>
<option value="4" selected="selected" >5</option>
</select>
This will select the option with value 4
$("#quantity").val("4");
And this will not do anything
$("#quantity").val("10");
$("select.quantity option:selected").val();
为了确保您得到选定的数量。
I reduced your code to this:
<div class="controls">
<a href="#" class="qty-btn-minus">-</a>
<a href="#" class='qty-btn-plus'>+</a>
<select id="quantity" style="width:60px" qt="0"></select>
</div>
and did the plus and minus functions... I'm not sure if it will help, but I hope yes
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.