I need some help with my jquery script.
I have two select boxes. When I select one options from firs select box the second box should show 3 items from all available options. The script doing it, but also showing me "additional" value at the top of the second select box.
Can someone tell me why?
Here is my HMTL code:
<select id="viewSelector" style="float: left;">
<option value="0">-- Select a View --</option>
<option value="view1">W</option>
<option value="view2">X</option>
<option value="view3">Y</option>
<option value="view4">Z</option>
</select>
<select id="viewSelect1">
<option id="view1a">W1</option>
<option id="view1b">W2</option>
<option id="view1c">W3</option>
<option id="view2a">X1</option>
<option id="view2b">X2</option>
<option id="view2c">X3</option>
<option id="view3a">Y1</option>
<option id="view3b">Y2</option>
<option id="view3c">Y3</option>
<option id="view4a">Z1</option>
<option id="view4b">Z2</option>
<option id="view4c">Z3</option>
</select>
Here is my jQuery/JavaScript:
$(document).ready(function() {
$.viewMap = {
'0' : $([]),
'view1' : $('#view1a, #view1b, #view1c'),
'view2' : $('#view2a, #view2b, #view2c'),
'view3' : $('#view3a, #view3b, #view3c'),
'view4' : $('#view4a, #view4b, #view4c'),
};
$.each($.viewMap, function() { this.hide(); });
$('#viewSelect1').hide();
$('#viewSelector').change(function() {
// hide all
$.each($.viewMap, function() { this.hide(); });
$('#viewSelect1').hide();
// show current
$.viewMap[$(this).val()].show();
$('#viewSelect1').show();
});
});
The working example you can find here: http://jsfiddle.net/amarcinkowski/Sg8Xf/9/
Simple get id of selected value and add attribute selected .
var id = $.viewMap[$(this).val()].attr("id");
$('#'+id).attr('selected', 'selected');
$(document).ready(function() {
$.viewMap = {
'0' : $([]),
'view1' : $('#view1a, #view1b, #view1c'),
'view2' : $('#view2a, #view2b, #view2c'),
'view3' : $('#view3a, #view3b, #view3c'),
'view4' : $('#view4a, #view4b, #view4c'),
};
$.each($.viewMap, function() { this.hide(); });
$('#viewSelect1').hide();
$('#viewSelector').change(function() {
// hide all
$.each($.viewMap, function() { this.hide(); });
$('#viewSelect1').hide();
// show current
$.viewMap[$(this).val()].show();
$('#viewSelect1').show();
var id = $.viewMap[$(this).val()].attr("id");
$('#'+id).attr('selected', 'selected');
});
});
Edited here is a working jsFiddle example
added
<option id="view0">Select</option>
to
<select id="viewSelect1">
....
</select>
modified your object
$.viewMap = {
'0' : $([]),
'view1' : $('#view1a, #view1b, #view1c'),
'view2' : $('#view2a, #view2b, #view2c'),
'view3' : $('#view3a, #view3b, #view3c'),
'view4' : $('#view4a, #view4b, #view4c'),
'viewBlank' : $("#view0")
};
and added a line
// show current
$.viewMap[$(this).val()].show();
$.viewMap['viewBlank'].show();
$('#viewSelect1').show();
Change
$('#viewSelect1').show()
to
$('#viewSelect1')
.show()
.find('option:visible:first') // get the first visible option
.attr('selected', 'selected'); // set that option as selected
Demo
According to comment
$('#viewSelector').change(function() {
var str = $('#viewSelect1 option:selected').attr('id').replace(/view\d/,'');
// hide all
$.each($.viewMap, function() {
this.hide();
});
$('#viewSelect1').hide();
// show current
$.viewMap[$(this).val()].show();
$('#viewSelect1')
.show()
.find('option:visible[id*='+ str+']')
.attr('selected', 'selected');
});
DEMO
Related
I am new in jquery.
I am using multiple select plugin jquery.
I want that the user can't select more than 3 options.
Here I have also disabled the selectall option.
Here is my code:
<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>
</select>
Jquery code:
$("select").multipleSelect({
selectAll: false
});
Please help me. Thanks in advance :)
EDIT :
There working jsFiddle example with multi-select plugin
var limit = 3;
var $multiSel = $("select").multipleSelect({
placeholder: "Here is the placeholder",
width: 200,
filter: true,
selectAll: false,
onClick: function(view) {
var $checkboxes = $multiSel.next().find("input[type='checkbox']").not(":checked");
var selectedLen = $multiSel.multipleSelect('getSelects').length;
if (selectedLen >= limit) {
$checkboxes.prop("disabled", true);
} else {
$checkboxes.prop("disabled", false);
}
}
});
add change event for select and check for length of selected options
$("select").change(function () {
if($("select option:selected").length > 3) {
// you can disable rest of the things here
}
});
You could do
if($("select").multipleSelect("getSelects").length > 3)
{
alert('Not allowed');
}
I have a number of HTML selects like follows on one page:
<div>
<h3>Ethnicity</h3>
<select>
<option value="select">Select</option>
<option value="african">African</option>
<option value="africanamerican">African American</option>
<option value="asian">Asian</option>
</select>
</div>
I want to use Jquery to check each select to ensure the initial value "select" has been changed - eg: another options has been selected. If it hasn't changed I want to change the selects color.
I've tried the following Jquery but it's not fully functional:
if($('select').val() == 'select') {
alert('got one...');
$(this).css({'color' : 'red'});
}
Note: the page has around 25 selects and I'm try to get one piece of jquery to cover all.
You can use change event handler and check for selected value: Check the snippet below
$('select').on('change', function() {
if ($(this).val() == 'select') {
alert('got one...');
$(this).css({
'color': 'red'
});
} else {
$(this).css({
'color': 'initial'
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<h3>Ethnicity</h3>
<select>
<option value="select">Select</option>
<option value="african">African</option>
<option value="africanamerican">African American</option>
<option value="asian">Asian</option>
</select>
</div>
check out this: .val()
$("select").each(function(){
if($(this).val() == "YourDefaulValue"){
$(this).css({'color' : 'red'});
}
});
You have to iterate the elements yourself. Luckily, it's quite simple and a very small change to your code:
$('select').each(function() {
var $this = $(this);
if($this.val() == 'select') {
// probably shouldn't alert here...
// alert('got one...');
$this.css({'color' : 'red'});
}
}
If you need to check all selects you have to test if one or more is "unselected". To achieve this you may do:
$(function () {
$('#resetBtn').on('click', function(e) {
$('select').each(function(index, element) {
$(this).css({'color' : 'black'});
});
});
$('#checkBtn').on('click', function(e) {
$('select').each(function(index, element) {
if (element.selectedIndex == 0) {
alert('got one...');
$(this).css({'color' : 'red'});
}
});
});
});
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<button id="checkBtn">Check select</button>
<button id="resetBtn">Reset select</button>
<div>
<h3>Ethnicity</h3>
<select>
<option value="select">Select</option>
<option value="african">African</option>
<option value="africanamerican">African American</option>
<option value="asian">Asian</option>
</select>
</div>
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');
}
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 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();
});
});