i am creating two dropsdowns like this
var drp_nt = $('<select />', {
'id' : 'drp_' + nt,
'name' : 'drp_' + nt+'[]',
on: {
change: check_data
},
'multiple': true});
var drp_cnt = $('<select />', {
'id' : 'drp_' + cnt,
'name' : 'drp_' + cnt+'[]',
on: {
change: check_data
},
'multiple': true});
Now i am defining the check_data_function like this
function check_data()
{
if($("select option:selected").length==2)
alert('Two Dropdown Selected');
else
alert($("select option:selected").length);
}
I want to enable a button when both of the dropdown has some of the options selected.
in the above fragment of the code, the problem is, if i select 2 options from dropdown drp_nt, and select no option from drp_cnt, then also the alert 'Two Dropdown Selected' is taking place.
I want to have the alert 'Two Dropdown Selected' take place when both of the dropdowns will have some options selected. If one is having something selected while the other one don't, then the alert 'Two Dropdown Selected' won't take place
How can i achieve this?
This will do the trick:
function check_data() {
if ($('select option:selected').parent().length == 2) {
alert('Two Dropdown Selected');
}
}
The idea is that you still select selected options, but then you get their parent select elements and verify that there are exactly two of them.
Check the demo below.
$('select').change(check_data);
function check_data() {
if ($('select option:selected').parent().length == 2) {
alert('Two Dropdown Selected');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple>
<option>Text 1</option>
<option>Text 2</option>
<option>Text 3</option>
<option>Text 4</option>
</select>
<select multiple>
<option>Text 1</option>
<option>Text 2</option>
<option>Text 3</option>
<option>Text 4</option>
</select>
you are selecting both dropdown in jquery using select
**
function check_data()
{
if($("select option:selected").length==2)
alert('Two Dropdown Selected');
else
alert($("select option:selected").length);
}
**
$('select') will select both dropdown. So when you check in jquery, after you selected two in one drop down, this will give you result as two selected. So you need to check like following
function check_data()
{
if($("#id1 option:selected").length>1 && $("#id2 option:selected").length>1)
alert('Two Dropdown Selected');
else
alert('select any one of the option from both dropdown');
}
You can do this by filtering the list of selects so that you get only those with options selected and then check the length
$(function(){
$(document).on('change','select',function(){
var selectsWithOptionsSelected = $('select').filter(function(){
return $('option:selected',this).length>0;
});
alert(selectsWithOptionsSelected.length);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select rows="3" multiple>
<option>One</option>
<option>Two</option>
<option>Three</option>
</select>
<select rows=3 multiple>
<option>One</option>
<option>Two</option>
<option>Three</option>
</select>
You may want to fiddle with the selectors to only target the select instances you're interested in, for example you could give them a class and use that in both selectors (select.myClassName)
Use jQuery().each
function check_data()
{
var counter = 0;
jQuery('select').each(function() {
if(jQuery(this).find('option:selected').length == 2) {
counter++;
}
});
if(counter == jQuery('select').length)
alert('Two Dropdown Selected');
else
alert($("select option:selected").length);
}
Here's another alternative just for giggles:
function check_data() {
$('select:has(option:selected)').length > 1 && alert('Foo');
}
Related
I am trying to change a select option on click but I don't want to use the option value. My code works if I give my button a value='3' but what I want is to select the one with data-price="0" which in my case is the one with value='3'.
JS :
jQuery(document).ready(function () {
jQuery('#sample-addtocart-button').click(function(){
jQuery('.product-custom-option').val(jQuery(this).attr('value'));
});
});
Html :
<button value="0" id="sample-addtocart-button" type="button">Free</button>
<select class="product-custom-option">
<option value="">-- Please Select --</option>
<option data-price="10" value="1">£10.00</option>
<option data-price="20" value="2">£20.00</option>
<option data-price="0" value="3">FREE</option>
</select>
Any help will be appreciated
You can use attribute equals selector to get the option and then select option by setting selected property using prop() method.
jQuery(document).ready(function() {
jQuery('#sample-addtocart-button').click(function() {
jQuery('.product-custom-option option[data-price="' + jQuery(this).attr('value') + '"]').prop('selected', true);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button value="0" id="sample-addtocart-button" type="button">Free</button>
<select class="product-custom-option">
<option value="">-- Please Select --</option>
<option data-price="10" value="1">£10.00</option>
<option data-price="20" value="2">£20.00</option>
<option data-price="0" value="3">FREE</option>
</select>
You can select elements by attribute, and then set the selected property on the element.
jQuery(document).ready(function () {
jQuery('#sample-addtocart-button').click(function(){
jQuery('.product-custom-option [data-price=' + this.value + ']').prop("selected", true);
});
});
This selects the element with a data-price attribute equal to the value of this.value, which is a descendant of .product-custom-option, and sets its selected property to true.
Without jQuery, it could look like this:
document.addEventListener("DOMContentLoaded", function () {
document.querySelector('#sample-addtocart-button').addEventListener("click", function(){
document.querySelector('.product-custom-option [data-price=' + this.value + ']').selected = true;
});
});
And a handful of helper methods always helps with the verbosity:
function listen(el, typ, fn, cap) {
el && el.addEventListener(typ, fn, cap)
}
function query(el, sel) {
if (typeof el === "string") {
sel = el;
el = document;
}
return el.querySelector(sel)
}
listen(document, "DOMContentLoaded", function () {
listen(query('#sample-addtocart-button'), "click", function(){
query('.product-custom-option [data-price=' + this.value + ']').selected = true;
});
});
Try this:
jQuery('#sample-addtocart-button').click(function(){
var val= jQuery(this).attr('value');
jQuery('.product-custom-option option[data-price='+val+']').prop('selected', true); // it will find the select option with certain data-price and make it selected
});
have this code, i want to convert it to be able to allow the user to pick ANY possible select and have div [id='setprice'] show up or something to that effect. currently i have 4 options, but it could be up to 10+ depends on how many are in the database. but it shouldn't matter, i just want which ever gets selected to open the setprice div. Thanks.
$("#category").change(function () {
$("#setprice").hide();
if ($(this).val() == "cow") { $("[id='setprice']").show(); }
else if ($(this).val() == "dog") { $("[id='setprice']").show(); }
else if ($(this).val() == "monkey") { $("[id='setprice']").show(); }
else if ($(this).val() == "kungfoo") { $("[id='setprice']").show(); }
});
HTML
<select id="category">
<option value=''>Select</option>
<option value='cow'>Cow</option>
<option value='dog'>Dog</option>
<option value='monkey'>Monkey</option>
<option value='kungfoo'>kungfoo</option>
</select>
<div id='setprice'>this is hidden onload, then shows on any #category selection</div>
Seems to be alot of cofusion in what im asking, These options i've given are random names, the categories that are going to be loaded, are from a database and more could be added depending how it expands, so i want the script to not show div=setprice, but when anything gets selected in #category to open setprice.
You will need to call the function only when the value of the select box isn't empty.
$("#category").change(function () {
$("#setprice").toggle(!!this.value);
});
Here is a working fiddle.
This is the cleanest you will get this.
DEMO
$("#category").change(function () {
$("#setprice").toggle(!!this.value);
});
The $("#setprice").toggle(!!this.value); is just a way to use a boolean inside the .toggle() method,
otherwise you do it equally like:
var $setPriceEl = $("#setprice");
$("#category").change(function () {
$setPriceEl.hide(); // hide by default
if(this.value) $setPriceEl.show(); // show only if has value
});
or even:
$("#category").change(function () {
$("#setprice")[this.value ? "show" : "hide" ]();
});
Please find the answer below ...
HTML :
<select id="category">
<option value=''>Select</option>
<option value='cow'>Cow</option>
<option value='dog'>Dog</option>
<option value='monkey'>Monkey</option>
<option value='kungfoo'>kungfoo</option>
</select>
<div id='setprice' style="display:none;">this is hidden onload,
then shows on any #category selection</div>
JQUERY :
$(document).ready(function(){
$("#category").change(function() {
$("#category option:selected" ).each(function() {
var str = $( this ).text();
if(str == "Select"){
$("#setprice").hide();
}else{
$("#setprice").show();
$("#setprice").text(str);
}
});
}).trigger("change");
});
I need to select only 3 options from the multiple select. If user selects more than 3 options than the last selected element should be replaced by the new one clicked.
I have a example as follows:
<select multiple id='testbox'>
<option value='1'>First Option</option>
<option value='2'>Second Option</option>
<option value='3'>Third Option</option>
<option value='4'>Fourth Option</option>
<option value='5'>Fifth Option</option>
<option value='6'>Sixth Option</option>
<option value='7'>Seventh Option</option>
<option value='8'>Eighth Option</option>
<option value='9'>Ninth Option</option>
<option value='10'>Tenth Option</option>
</select>
When user selects
First option
Second option
Third option
Now he reaches max selection limit 3 .If he click on the another option like Tenth Option I need to remove Third option and get selected Tenth option
For that i tried this but no idea how I can achieve my goal
<script type="text/javascript">
google.load("jquery", "1");
$(document).ready(function() {
//alert("1111");
var last_valid_selection = null;
$('#testbox').change(function(event) {
if ($(this).val().length > 2) {
alert('You can only choose 2!');
$(this).val(last_valid_selection);
} else {
last_valid_selection = $(this).val();
latest_value = $("option:selected:last",this).val()
alert(latest_value);
}
});
});
</script>
Please suggest some idea or solution.
This works quite nicely:
var lastSelected;
$("#testbox").change(function() {
var countSelected = $(this).find("option:selected").length;
if (countSelected > 3) {
$(this).find("option[value='" + lastSelected + "']").removeAttr("selected");
}
});
$("#testbox option").click(function() {
lastSelected = this.value;
});
I had to set a global variable lastSelected as well as an options click event to capture the actual last option clicked (this.value in the change event was giving me the top selected option, not the actual last option).
Demo: http://jsfiddle.net/JAysB/1/
Well, I don't like jQuery, so I've developed the same (fiddle), but in pure, vanilla, easy-to-read JavaScript:
document.getElementById('testbox').selopt=new Array();
document.getElementById('testbox').onchange=function(){
for(i=0; i<this.childNodes.length; i++)
if(this.childNodes[i].tagName!='OPTION')
continue;
else{
if(this.childNodes[i].selected &&
this.selopt.indexOf(this.childNodes[i])<0)
this.selopt.push(this.childNodes[i]);
}
if(this.selopt.length==4)
this.selopt.splice(2,1)[0].selected=false;
}
P. S. No global variables! :P
var lastOpt;
$('#testbox option').click(function () {
lastOpt = $(this).index();
});
$('#testbox').change(function () {
if ($('option:selected', this).length > 3) {
$(' option:eq(' + lastOpt + ')', this).removeAttr('selected');
}
});
JSFIDDLE
I am using 24 dropdowns. I want to select a driver for a position. But when i select a driver for the first position it should be removed from the other dropdowns so i can't use a driver two times. The dropdown is:
<select name="rijderQual1">
<option value="1">S. Vettel</option>
<option value="2">M. Webber</option>
<option value="3">J. Button</option>
<option value="4">L. Hamilton</option>
<option value="5">F. Alonso</option>
<option value="6">F. Massa</option>
<option value="7">M. Schumacher</option>
<option value="8">N. Rosberg</option>
<option value="9">K. Raikkonen</option>
<option value="10">R. Grosjean</option>
<option value="11">R. 11</option>
<option value="12">R. 12</option>
<option value="14">K. Kobayashi</option>
<option value="15">S. Perez</option>
<option value="16">R. 16</option>
<option value="17">R. 17</option>
<option value="18">P. Maldonado</option>
<option value="19">R. 19</option>
<option value="20">H. Kovalainen</option>
<option value="21">J. Trulli</option>
<option value="22">P. de</option>
<option value="23">R. 23</option>
<option value="24">T. Glock</option>
<option value="25">C. Pic</option>
</select>
The names are rijderQual1 to rijderQual24. So when i select S Vettel for example in rijderQual1 it should be removed from the 23 other dropdowns.
Is there a way to do this? I think it should be done with JS or jQuery?
You can iterate thru all options everytime some selected value is changed and hide the options that are selected somewhere else:
$('select').change(function() {
var selectedValues = $('select').map(function() { return this.value; }).get();
$('option').show();
$.each($('option'), function(i, item) {
if($(this).val() != 0 && $.inArray($(this).val(), selectedValues) > -1 )
{
$(this).hide();
}
});
});
DEMO
Try populating your dropdown box through an array, and on each item selected delete that item from that array. both JS and JQuery would work.
I still believe another approach would be wiser, for example colour-coding all dropdowns that have the same value selected. Or unselect the option from the first dropdown if you select it in another. That way you wouldn't deprive users from doing what they want, but warn them if they try to do something that's not allowed. Better for UX. Something a little more like this.
// Store text labels for options
$("option")
.each(function() {
$(this).data("label", $(this).text());
});
$('select').change(function() {
// Get selected values
var selectedValues = $('select').map(function() { return this.value; }).get();
// Reset conflicting dropdowns
currentVal = $(this).val();
$(this).siblings("select")
.each(function() {
if ($(this).val() == currentVal) $(this).val(0);
});
// Mark selected options as unavailable
$("option")
.each(function() {
if( $(this).val() != 0 && $.inArray($(this).val(), selectedValues) > -1 && !$(this).is(":selected"))
$(this).text("(" + $(this).data("label") + ")");
else
$(this).text($(this).data("label"));
});
});
DEMO: http://jsfiddle.net/NAWNP/
Still, according to your requirements this would iterate through the options, disabling those that are in use by other dropdowns. This way you can still see your options, even though you can't make them.
$('select').change(function() {
var selectedValues = []
$("option:selected").each(function() { selectedValues.push($(this).val()) });
$("option")
.removeAttr("disabled")
.each(function() {
if( $(this).val() != 0 && $.inArray($(this).val(), selectedValues) > -1 && !$(this).is(":selected"))
{
$(this).attr("disabled", "true");
}
});
});
DEMO: http://jsfiddle.net/ntxmh/2/
Working demo http://jsfiddle.net/zyGH7/
another http://jsfiddle.net/fLTxj/
Much concise version. This is the source: jQuery remove options except current (Very well written)
Hope it fits the cause! B-)
Code
$('document').ready(function() {
$(".hulk").change(function() {
var val = this.options[this.selectedIndex].value;
$('select').not(this).children('option').filter(function() {
return this.value === val;
}).remove();
});
});
Been having lot's of trouble with this one. Let's say I had the following html:
<div id='step_1'>
<select name='select_1' id='choose'>
<option value='select one'>Select One</option>
<option value='yes'>Yes</option>
<option value='no'>No</option>
</select>
<select name='select_2' id='choose_again'>
<option value='select one'>Select One</option>
<option value='yes'>Yes</option>
<option value='no'>No</option>
</select>
<button id='submit'>button</button>
</div>
I have many of these, so what I'm trying to do is return false if ANY 'select' has the value of 'Select One' then alert them. The jQuery i have so far looks as so:
$('#submit').click(function() {
if ($('#step_1 select[value="select one"]').length() == 0) {
//succeed
} else {
alert('Please select yes or no!');
return false;
}
});
What am I doing wrong? Thanks in advance, I love this website! :)
$('#submit').click(function(e) {
var flag = true;
$('select').each(function(){
if($(this).val() == "select one"){
alert("please select a value in " + $(this).attr("name"));
flag = false;
}
});
if(flag){
alert('perfect');
}else{
e.preventDefault();
}
});
EXAMPLE : http://jsfiddle.net/raj_er04/3kHVY/1/
Quick note: If you want the alert to only show once rather than once per each 'select one', simply move the alert() into the else{ statement. thanks again for this answer!
You can do this with $.each():
$('#step_1').find('SELECT').each( function() {
if( $(this).val() === 'select one' ) {
alert('Please select yes or no!');
return false;
}
});
Note that returning false will prevent the loop from continuing once a missing field is found.
Your test fails because length is not a method. It is a property. Remove the (). If you look in your debugger you should see a warning about this.
Also, your selector should be checking the selected option, not the select list itself.
http://jsfiddle.net/7PPs4/
$('#submit').click(function() {
$foo = $('#step_1 select option:selected[value="select one"]');
alert($foo.length);
});