i have a selection field and when the button #btnaddtocart is selected i want to be able to check if the selection (name=quantity) isnt null, if it is then an alert is shown to the user. otherwise not to show anything. the script works but the problem is that if the selection does contain a value the alert still shows. why is this?
here is the html
<select class="select" id="quantity" name="quantity">
<option selected="selected" value="">select one</option>
<option value="data1">data1</option>
<option value="data2">data2</option>
<option value="data3">data3</option>
</select>
here is the js
$(document).ready(function() {
$("#btnaddcart").click(function()
{
if($("input[name=quantity]").val() == null)
{
var data = $(this).val();
alert(data);
}
开发者_开发百科 });
});
You're checking the wrong thing, this:
if($("input[name=quantity]").val() == null)
should be this:
if($('#quantity').val() == '')
A selector like input[name=...
looks for <input>
tags with the specified name
attribute but you want a <select>
element; since your <select>
has an id
attribute, you can just use an ID selector.
u can do it like
# not selected
if (!$("#quantity option:selected").length) {
}
You don't need to use jQuery for this. In your example, try this code:
$(document).ready(function() {
$("#btnaddcart").click(function(){
var box=document.getElementById('quantity');
var index=box.selectedIndex;
// any one selected apart from the first option
if(index!=0){
var data=box.options[index].value;
alert(data);
}
});
});
I'd actually advise against using jQuery if you actually need the index.
some of the above operations can be written simpled, just wanted to show you how to get the various properties of a select box.
$("#btnaddcart").click(function()
{
if($("#quantity").val() == '')
{
alert("cannot be null");
}
else{
alert($(this).val());
}
});
On jsfiddle.
精彩评论