I'm trying to find a way to check my options in different select boxes (total: 4).
The boxes include the same data in value/text.
How do I avoid that the option select is the same? (I use it for an sorting feature).
And how can i integrate it in the current jquery script. (I use ajax-post to parse data).
This is how it should not be:
Select one:
<ul>
<li class="move-img">
<select style="width:150px;"id="modul1" onchange="$.modules.options(this,1);">
<option value="0"></option>
<option value="1">name</option>
<option value="2">name2</option>
</select>
</li>
Select two
<ul>
<li class="move-img">
<select style="width:150px;"id="modul2" onchange="$.modules.options(this,2);">
<option value="0"></option>
<option value="1">name</option>
<option value="2">name2</option>
</select>
</li>
jQuery
$.modules = {
/* Get price for option-modules */
options: function(module_id,show_divid){
var modul = $(module_id).val();
if(modul != 0){
//show price
$("#showprice"+show_divid).html('<div class="ajax_loader left"></div>').fadeTo(300,0.25,function(){
var $show_price = $(this); // div tag
$.post('/ajax/modules/get_prices/',{check_data:'send_data',get_module_prices_id:modul},function(data){
$show_price.fadeTo(200,100,function(){
$show_price.html(data.module_price);
});
},'json');
});
}
}
}
I wonder whether this is what you are after: http://jsfiddle.net/william/K7nTr/.
It checks whether the value has already been selected. If it has, revert to the first value and alert the user.
$.modules = {
/* Get price for option-modules */
options: function(module_id, show_divid) {
var modul = $(module_id).val();
if (modul != 0) {
var selector = ".move-img option:selected[value=" + modul + "]";
if ($(selector).length > 1) { // see if this value has been selected elsewhere
alert('The value has been selected. Try again');
$('option:eq(0)', module_id).attr('selected', 'selected');
return;
}
//show price
$("#showprice" + show_divid).html('<div class="ajax_loader left"></div>').fadeTo(300, 0.25, function() {
var $show_price = $(this); // div tag
$.post('/ajax/modules/get_prices/', {
check_data: 'send_data',
get_module_prices_id: modul
}, function(data) {
$show_price.fadeTo(200, 100, function() {
$show_price.html(data.module_price);
});
}, 'json');
});
}
}
}
In onchange="$.modules.options('modul1',1);" you dont have to pass modul1, you can just pass this which will point to the changing select box. This applies to both the select boxes. You have few js error in your code, try this.
$.modules = {
/* Get price for option-modules */
options: function(module_id,show_divid){
var modul = $(module_id).val();
if(modul != 0){
//show price
$("#showprice"+show_divid).html('<div class="ajax_loader left"></div>').fadeTo(300,0.25,function(){
var $show_price = $(this); // div tag
$.post('/ajax/modules/get_prices/',{check_data:'send_data',get_module_prices_id:modul},function(data){
$show_price.fadeTo(200,100,function(){
$show_price.html(data.module_price);
});
},'json');
});
}
}
I'm not sure I understand. in html, replace the onChange
onchange="$.modules.options(this);"
in jquery, replace:
options: function(module){
var modul = $("option:selected", module).val();
and replace too
if(modul.length == 0);
else{
by
if( modul.length > 0) {
try this
var inputs = document.getElementsByTagName("input"); //or document.forms[0].elements;
var cbs = []; //will contain all checkboxes
var checked = []; //will contain all checked checkboxes
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == "checkbox") {
cbs.push(inputs[i]);
if (inputs[i].checked) {
checked.push(inputs[i]);
}
}
}
var nbCbs = cbs.length; //number of checkboxes
var nbChecked = checked.length; //number of checked checkboxes
for(var i=0;i<checked.length;i++)
{
if(checked[i].value=checked[i+1].value)
{
alert('Not allowed');
}
}
Not sure if i got you right here.
But my following example allows each option to be selected only once.
<script language="javascript" type="text/javascript">
var ValidateOptions = function (module) {
var selectedValue = $('option:selected', module).attr('value');
var collectionWithoutCurrent = $('.move-img select').not(module);
$('option').show();
collectionWithoutCurrent.each(function () {
$(this).children('option[value="' + selectedValue + '"]').toggle();
});
};
</script>
<ul>
<li class="move-img">
<select style="width: 150px;" id="modul1" onchange="ValidateOptions($(this))">
<option value="0"></option>
<option value="1">name</option>
<option value="2">name2</option>
</select>
</li>
</ul>
<ul>
<li class="move-img">
<select style="width: 150px;" id="modul2" onchange="ValidateOptions($(this))">
<option value="0"></option>
<option value="1">name</option>
<option value="2">name2</option>
</select>
</li>
</ul>
Related
I have different selects with the same content and i want control that the user don't put the same value in two or more selects, i make this code, but i think there are some options better than this, I put here the code for share and at the same time ask if exist some better options. because i search some solution like this and i can't found.
$(function () {
function restrict_multiple(selector) {
// Here sets the current value in your alt
$(selector).each(function () {
$(this).attr("alt", $(this).val());
})
// trigger when the select change
$(selector).change(function () {
// Remove the hidden from the <option>
$(selector + " option").removeClass("hidden");
// I use thr alt attr, like an aid to maintain the actual selected value
$(this).attr("alt", $(this).val())
// Create an array with the selected options
var selected = new Array();
// Every selected option is assigned into this array
$(selector + " option:selected").each(function () {
selected.push(this.value);
})
// Apply the hidden the other select options
for (k in selected) {
if( selected[k] != "" ){
$(selector + "[alt!=" + selected[k] + "] option[value=" + selected[k] + "]").addClass("hidden")
}
}
})
// trigger to keep updated all selects
$(selector).each(function () { $(this).trigger("change"); })
}
//calling the function again sending the class
restrict_multiple(".excluyent-select");
})
.hidden { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<select name="participantes_1" id="participantes_1" class="excluyent-select" >
<option value="">Seleccionar</option>
<option value="1">111111111111111111</option>
<option value="2">222222222222222222</option>
<option value="3">333333333333333333</option>
<option value="4">444444444444444444</option>
<option value="5">555555555555555555</option>
<option value="6">666666666666666666</option>
<option value="7">777777777777777777</option>
<option value="8">888888888888888888</option>
<option value="9">999999999999999999</option>
</select><br />
<select name="participantes_2" id="participantes_2" class="excluyent-select" >
<option value="">Seleccionar</option>
<option value="1">111111111111111111</option>
<option value="2">222222222222222222</option>
<option value="3">333333333333333333</option>
<option value="4">444444444444444444</option>
<option value="5">555555555555555555</option>
<option value="6">666666666666666666</option>
<option value="7">777777777777777777</option>
<option value="8">888888888888888888</option>
<option value="9">999999999999999999</option>
</select><br />
Here i put the link to some example running: http://jsfiddle.net/hevercking/xdmd87se/
I changed the js code to do it this way:
$(function () {
function restrict_multiple(selector) {
$(selector).each(function () {$(this).attr("alt", $(this).val());});
$(selector).on('change', function () {
var ind = $(this).index();
var val = $(this).val();
var alt = $(this).attr('alt');
$(selector).each(function () {
$(this).find("option[value="+alt+"]").removeClass("hidden");
if($(this).index() != ind && val != "") {
$(this).find("option[value="+val+"]").addClass("hidden");
}
});
$(this).attr('alt', val);
});
}
restrict_multiple(".excluyent-select");
})
Let me know if it works correctly: http://jsfiddle.net/48zmLm7x/5/
Great! i like more your option, but the two options i discover have one problem and i don't know how to solve, if i generate the selects with one for.
for ( var i=0; i < 2; i++ ) {
$('<p><select name="grup_'+i+'" id="grup_'+i+'" class="excluyent-select")"><option value="">Seleccionar</option><option value="1">111111111111111111</option><option value="2">222222222222222222</option><option value="3">333333333333333333</option><option value="4">444444444444444444</option><option value="5">555555555555555555</option><option value="6">666666666666666666</option><option value="7">777777777777777777</option><option value="8">888888888888888888</option><option value="9">999999999999999999</option></select></p>').appendTo('#selecs');
}
$(function () {
function restrict_multiple(selector) {
$(selector).each(function () {$(this).attr("alt", $(this).val());});
$(selector).on('change', function () {
var ind = $(this).index();
var val = $(this).val();
var alt = $(this).attr('alt');
$(selector).each(function () {
$(this).find("option[value="+alt+"]").removeClass("hidden");
if($(this).index() != ind && val != "") {
$(this).find("option[value="+val+"]").addClass("hidden");
}
});
$(this).attr('alt', val);
});
}
restrict_multiple(".excluyent-select");
})
.hidden { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div id="selecs">
</div>
in this case don't run http://jsfiddle.net/hevercking/t3qg45v3/
I try make with onChange but only start to remove when i change one select the second time and if i change don't apear again until remove all options in the other select, i put here the example: http://jsfiddle.net/hevercking/e4scbtre/3/
What I'm trying to do: I have multiple select dropdowns, if an option is selected in one of the select dropdowns and the value exists in any of the other dropdowns the value should be disabled/unselectable, it again can become enabled/selectable if the selection is changed.
What happens with current code: it works about 50%, I can't pinpoint the issue, but I think because I'm applying a for loop some values get skipped and not disabled and sometimes the "Select" default option becomes disabled?!
Approach: The way I wrote my code was when a selection from the dropdown box occurs, enable all options, get the first dropdown's current selected value, if it's not the default "Select" then go through every dropdown box and disable any matching values, then repeat this process for the second dropdown's current selected value and so on.
Fiddle: http://jsfiddle.net/haakym/r2y73ndt/
Code:
HTML:
<div id="nomineeInfo">
<div>
<label>Manager</label>
<select class="positionTypes" id="pos_manager">
<option value="0">Select</option>
<option value="1">John Smith</option>
<option value="2">Jane Smith</option>
<option value="4">John Smoe</option>
</select>
</div>
<div>
<label>Deputy</label>
<select class="positionTypes" id="pos_deputy_manager">
<option value="0">Select</option>
<option value="1">John Smith</option>
<option value="2">Jane Smith</option>
<option value="3">John Doe</option>
</select>
</div>
<div>
<label>Finance</label>
<select class="positionTypes" id="pos_finance">
<option value="0">Select</option>
<option value="1">John Smith</option>
<option value="3">John Doe</option>
<option value="4">John Smoe</option>
</select>
</div>
Javascript:
$('#nomineeInfo').on('change', '.positionTypes', function () {
var selectedValue = $(this).val();
var dropdownOnChangeId = $(this).prop('id');
var positionTypesEn = ['manager', 'deputy_manager', 'finance'];
// set all enabled
for (var i = 0; i < 7; i++) {
$('#pos_'+positionTypesEn[i]).each(function(){
$("option", this).removeAttr('disabled');
});
};
for (var i = 0; i < 7; i++) {
// if position type selected value is not 0, i.e. if it's not "Select"
if( $('#pos_' + positionTypesEn[i]).val() != 0 ){
// go through each option in every dropdown
for (var j = 0; j < 7; j++) {
console.log( positionTypesEn[j] ); // show current dropdown
$('#pos_' + positionTypesEn[j] + ' option').each(function(k){
if( !$(this).is(':selected') ){
if( $(this).val() == selectedValue && $(this).val() != 0 ){
$(this).prop('disabled', 'true');
console.log('disabled: ' + $(this).val() );
}
}
});
}
}
}
});
Any help is much appreciated!
After enabling all the options, you need to go through all the menus, get their selected values, and re-disable all of them in the other menus, not just the one you just changed.
$(document).ready(function () {
$('#nomineeInfo').on('change', '.positionTypes', function () {
// Get the selected options of all positions
var allSelected = $(".positionTypes").map(function () {
return $(this).val();
}).get();
// set all enabled
$(".positionTypes option").removeAttr("disabled");
// Disable selected options in other positions
$(".positionTypes option:not(:selected):not([value='0'])").each(function () {
if ($.inArray($(this).val(), allSelected) != -1) {
$(this).attr('disabled', true);
}
});
});
});
DEMO
try
$("select.positionTypes").change(function () {
$("select.positionTypes option").prop('disabled', false);
$("select.positionTypes option:selected:not([value='0'])").each(function (i) {
$("select.positionTypes option:nth-child(" + ((+this.value) + 1) + ")").prop('disabled', true)
});
});
DEMO
Try this too, an optimized version
$("select.positionTypes").change(function () {
$("select.positionTypes option[value='" + $(this).data('index') + "']").prop('disabled', false);
$(this).data('index', this.value);
$("select.positionTypes option[value='" + this.value + "']:not([value='0'])").prop('disabled', true);
});
DEMO
Your html structure, classes and attempt is not bad but if you are using jQuery you should use its full advantages like .each function to make your live alot easier.
I would make an attempt like this:
$('.positionTypes').on('change', function () { //When any select changes...
var changedID = $(this).attr("id"); //Save id of select that was changed...
var selectedValue = $(this).val(); //Save value of select was changed...
if($(this).val() != "0") { //If we did not select a 0 value at all...
$('.positionTypes option').prop("disabled", false); //Enable all disabled options of all selects...
$('.positionTypes').each(function() { //Loop all existing selects
if($(this).attr("id") != changedID) { //If the select id is not our own select
$("#" + $(this).attr("id") + " option").each(function() { //loop all options of all selects except the one excluded by previous if clause
if($(this).attr("value") == selectedValue) { //if the value matches to saved value
$(this).prop("disabled", true); //Disable this one
}
});
}
});
};
});
I am not sure if this is 100% complete atleast it can disable options of other selects with identical value with a little bit more structured code.
How can I cancel a select menu choice using a confirm dialog?
The idea is that when a user changes a select menu, they're prompted to confirm their choice. if they choose "cancel", the select menu goes back to its previously selected value. If they choose "OK", the select menu behaves as expected.
Here is the code I'm working on:
HTML:
<select class="selector" name="selector1">
<option value="yes">Yes</option>
<option value="no" selected="">No</option>
<option value="maybe">Maybe</option>
</select>
<select class="selector" name="selector2" >
<option value="yes">Yes</option>
<option value="no" selected="">No</option>
<option value="maybe">Maybe</option>
</select>
JavaScript
var selects = document.querySelectorAll('.selector');
var lastSelected = {};
for (i = 0; i < selects.length; i++) {
var select = selects[i];
lastSelected[select.name] = select.options[select.selectedIndex];
select.addEventListener('change', function (e) {
lastSelected = select.options[select.selectedIndex];
if (confirm("Are you want to choose this?") == true) {
return;
} else {
select.value = lastSelected[select.name];
}
});
}
I'm not entirely sure why this isn't working, any help is much appreciated.
Here is the fiddle I'm working on http://jsfiddle.net/je36eu78/2/
n.b I'd like to do this in native JavaScript (no jquery)
you overwrite lastSelected here:
lastSelected = select.options[select.selectedIndex];
you must also store the new value when the user hits OK
Another approach(stores the previous value as a property of the select)
var selects = document.querySelectorAll('.selector');
for (i = 0; i < selects.length; i++) {
var select = selects[i];
select.defaultValue=select.value;
select.addEventListener('change', function (e) {
if (confirm("Are you want to choose this?") == true) {
this.defaultValue=this.value;
} else {
this.value=this.defaultValue;
}
});
}
Try the snippet below
var select = document.querySelectorAll('.selector');
for (i = 0; i < select.length; i++) {
select[i]['last'] = select[i].options[select[i].selectedIndex].value;
(function(i){
select[i].onchange = function(){
if(confirm("Sure?")){
select[i]['last'] = this.value;
}else{
this.value = select[i]['last'];
}
};
})(i);
}
Working jsBin
I have tried to select option based on the textbox text.
Below is my html
<select id="select1">
<option value="">-- Please Select --</option>
<option value="277">12 +$2.99</option>
<option value="278">25 +$2.75</option>
<option value="279">50 +$2.50</option>
<option value="280">100 +$2.00</option>
<option value="281">250 +$1.90</option>
<option value="282">500 +$1.70</option>
<option value="283">1000 +$1.60</option>
<option value="284">2500 +$1.50</option>
<option value="285">5000 +$1.20</option>
<option value="286">10000 +$1.00</option>
<option value="287">25000 +$0.80</option>
</select>
<input type="text" id="pqr" />
And my js like bellow
$(function(){
$('#pqr').change(function(){
$txt = $( "#select1 option:contains('"+$(this).val()+"')" ).text();
$arr = $txt.split(" +");
$( "#select1").val($txt);
alert($arr[0])
$( "#select1" ).filter(function() {
alert($( this ).text > $arr[0]);
})
});
});
so if user enter text 12 or greater than 12 and bellow 25 than i want to select option second 12 +$2.99 and if user enter 1500 than option 1000 +$1.60 get selected. Basically i have try to compare option text before (+) sign and try to select based on that.
Please give me hint or any good help so solve this problem
At every change, iterate over all option elements and compare based on parseInt():
jQuery(function($) {
$('#pqr').on('change', function() {
var value = parseInt(this.value, 10),
dd = document.getElementById('select1'),
index = 0;
$.each(dd.options, function(i) {
if (parseInt(this.text, 10) <= value) {
index = i;
}
});
dd.selectedIndex = index; // set selected option
});
});
Demo
Loop through each option to compare the value. You can use something like this,
$(function () {
$('#pqr').change(function () {
var txtvalue = parseFloat($(this).val());
$("#select1 option").each(function () {
var splitText = $(this).next().text().split("+");
if (splitText.length > 1) {
if (txtvalue < parseFloat(splitText[0].trim())) {
$(this).prop("selected", true);
return false;
}
}
});
});
});
Fiddle
Try this :
$(function(){
$('#pqr').change(function(){
var inputVal = parseInt($(this).val());
$('#select1 option').each(function(){
var firstVal = $(this).text().split('+')[0];
var nextVal = inputVal;
if(!$(this).is(':last'))
$(this).next().text().split('+')[0];
if(parseInt(firstVal) <= inputVal && parseInt(nextVal) >=inputVal)
{
$(this).prop('selected',true);
}
});
});
});
Demo
The $arr[0] in the change callback function will be containing a text value which is not yet parsed to integer so the statement alert($( this ).text > $arr[0]); would not give desired output.
For checking the value lying between a range of select lists option you can use data attributes as followed:
<select id="select1">
<option value="" data-min="-" data-max="-"> Please Select </option>
<option value="277" data-min="12" data-max="25">12 +$2.99</option>
<option value="278" data-min="25" data-max="50">25 +$2.75</option>
This way you will not have to Parse the text of option into integer.
These data values can be retrieved for using jquery data function http://api.jquery.com/data/.
Also all the times you will not be getting the $('#pqr').val() as the text in the option's text so you will have to collect the value of text box and compare it with the range of each option(value >= data-max || value <= data-min).
$(function(){
$('#pqr').on("input", function(){
var text = this.value;
var options = $("#select1 > option");
var elementToSelect = options.eq(0);
if (text.match(/[0-9]+/)) {
elementToSelect = options.filter(function(){
return Number(this.innerText.split("+")[0]) <= text;
})
.eq(-1);
}
elementToSelect.attr("selected",true);
});
});
I have an HTML page in which I have 2 selects.
<select id="field" name="field" onchange="checkValidOption();">
<option />
<option value="Plugin ID">Plugin ID</option>
<option value="Name">Name</option>
</select>
<select id="operator" name="operator" onchange="checkValidOption();">
<option />
<option value="EQUALS">EQUALS</option>
<option value="CONTAINS">CONTAINS</option>
<option value="NOT CONTAINS">NOT CONTAINS</option>
<option value="REGEX">REGEX</option>
</select>
What I'd like to happen is that checkValidOption() could make it so that if "Plugin ID" is selected in field that the only option is EQUALS (and it's selected) and otherwise all the other options are available. Any idea on how to approach this?
I tried changing the innerHTML of the operator select in JS:
document.getElementById("operator").innerHTML =
"<option value='EQUALS'>EQUALS</option>";
However this results in an empty select (this would also include manually setting the many options for going back to having all the ones listed above).
I can't think of another solution, any help would be greatly appreciated.
Try this:
Demo here
var field = document.getElementById('field');
var operator = document.getElementById('operator');
field.onchange = function () { fieldcheck(); }
operator.onchange = function () { fieldcheck(); }
fieldcheck();
function fieldcheck() {
if (field.value == 'Plugin ID') {
for (i = 0; i < operator.options.length; ++i) {
if (operator.options[i].value != 'EQUALS') {
operator.options[i].disabled = true;
}
};
operator.value = 'EQUALS';
} else {
for (i = 0; i < operator.options.length; ++i) {
operator.options[i].disabled = false;
};
}
}
To manipulate options when Plugin ID was selected:
function checkValidOption(){
var x=document.getElementById("field");
var y=document.getElementById("operator");
if (x.options[1].selected === true){
document.getElementById("operator").options[1].selected = true;
for(var i=0; i<y.length; i++){
if (i !== 1){
//disabling the other options
document.getElementById("operator").options[i].disabled = true;
}
}
}
else{
for(var i=0; i<y.length; i++){
//enabling the other options
document.getElementById("operator").options[i].disabled = false;
}
}
}
Here's a link to fiddle
A select field doesn't use the innerHTML method, you need to use value.
document.getElementById("operator").value = "...";
heres a jquery solution.
every time the first select changes, it produces new options from an array for the 2nd select. issue here is i had to change the option values of the first select to 0 and 1 to select which value in the array, you can manipulate those later if you are storing this info somewhere
http://jsfiddle.net/2TZJh/
$(document).ready(function() {
$("#field").change(function() {
var val = $(this).val();
$("#operator").html(options[val]);
});
var options = [
'<option value="EQUALS">EQUALS</option>',
'<option></option><option value="EQUALS">EQUALS</option><option value="CONTAINS">CONTAINS</option> <option value="NOT CONTAINS">NOT CONTAINS</option> <option value="REGEX">REGEX</option>'
];
});