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
Related
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.
Below is what I currently have. I am now looking to be able to: When they click on artist one it will then take them to another drop down menu where there will be more options about Artist One. And the same if they chose Artist Two etc. Instead of just having an alert.
How would I go about that?
Thank you :)
<form>
<select id="mySelect">
<option value="void">Choose your answer</option>
<option value="artistOne">One</option>
<option value="artistTwo">Two</option>
<option value="artistThree">Three</option>
</select>
</form>
<button id="button" onclick="artist();" type="button">Confirm</button>
Javascript:
function artist() {
var select = document.getElementById("mySelect");
var artist = select.options[select.selectedIndex].value;
if(artist == "artistOne"){
alert("You have chosen Artist One!");
}
else if (artist == "artistTwo"){
alert("You have chosen Artist Two!");
}
}
function artist() {
var select = document.getElementById("mySelect");
var artist = select.options[select.selectedIndex].value;
var newSelectContainer = document.getElementById("artistDetails");
if(artist == "artistOne"){
createArtistSelect(newSelectContainer, ["Artist Detail 1", "Artist Detail 2", "Artist Detail 3"]);
}
else if (artist == "artistTwo"){
createArtistSelect(newSelectContainer, ["Artist2 Detail 1", "Artist2 Detail 2"]);
}
}
function createArtistSelect(elem, options){
//Create and append select list
var dynamicSelect = document.getElementById("dynamicSelect");
if(dynamicSelect)
dynamicSelect.outerHTML = "";
var selectList = document.createElement("select");
selectList.id = "dynamicSelect";
elem.appendChild(selectList);
//Create and append the options
for (var i = 0; i < options.length; i++) {
var option = document.createElement("option");
option.value = options[i];
option.text = options[i];
selectList.appendChild(option);
}
}
If you change your javascript code to this you will generate a drop down menu with the passed options.
You need to change a bit your html:
<form>
<div id="artistDetails">
<select id="mySelect">
<option value="void">Choose your answer</option>
<option value="artistOne">One</option>
<option value="artistTwo">Two</option>
<option value="artistThree">Three</option>
</select>
</div>
</form>
<button id="button" onclick="artist();" type="button">Confirm</button>
I created a function that is called on the onChange of the select (you can change it to be on the onClick of the input)
var details1 = ["1-1", "1-2", "1-3"];
var details2 = ["2-1", "2-2", "2-3", "2-4"];
var details3 = ["3-1", "3-2"];
function CreateCmb(artist) {
var cmbDetails = document.getElementById('cmbDetails');
if (cmbDetails !== null) {
while (cmbDetails.options.length > 0)
cmbDetails.remove(0);
} else {
cmbDetails = document.createElement("select");
cmbDetails.id = "cmbDetails";
body.appendChild(cmbDetails);
}
var currentDetails = [];
if (artist === "artistOne") currentDetails = details1;
else if (artist === "artistTwo") currentDetails = details2;
else if (artist === "artistThree") currentDetails = details3;
for (var i = 0; i < currentDetails.length; i++) {
var option = document.createElement("option");
option.text = currentDetails[i];
option.value = currentDetails[i];
cmbDetails.appendChild(option);
}
}
How it works:
First it get the dynamic select, then check if he is NOT null (is created). If this is the case, it delete all the option. If the select is null (not yet created), it create it and place it in the body.
Then it check wich details he need to show (the if else if block).
To finish, I looped the details and create the new options.
The nice part about this is that you will always have only one dynamic select because if he already exist, he reuse it ! That allow you to manually create and place it somewhere and he will use it if he have the correct id (in this case 'cmbDetails')
See this FIDDLE for an example !
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>'
];
});
I am totally confused how to make it.. Here is my problem.
I have n number of customized combo boxes (Which creates dynamically from the server side). Now i want to store the values of each combo box and need to validate by client side. If any one of the combo box val() == 0(i mean no option selected), then i need to show an error message. If all the combo box values are selected, then i need to show a a div in a popup. All these actions have to be happened if i click the save button.
Since these combo boxes are rendering dynamically, i cannot use its ID. My idea is to give a class name called combo and need to validate. Here is my code,
HTML (dynamicaaly generated)
<select class="combo">
<option selected="selected" value="0"></option>
<option value="1">Employee First Name (HR)</option>
<option value="2">Employee last Name (HR)</option>
<option value="3">Employee number (HR)</option>
<option value="4">NINO (HR)</option>
</select>
jQuery
$(document).ready(function(){
$('#save').click(function(){
var myLength = $('.combo option:selected').length;
alert(myLength);
if(myLength > 0){
alert('popups here');
count=count+1;
alert(count);
var maskHeight = $(document).height();
var maskWidth = $(window).width();
$('#mask').css({'width':maskWidth,'height':maskHeight});
$('#mask').fadeTo("fast",0.8);
var winH = $(window).height();
var winW = $(window).width();
$('.popups').css('top',winH/2-$('.popups').height()/2);
$('.popups').css('left',winW/2-$('.popups').width()/2);
$('.popups').show();
}
else
{
alert('No popups');
}
return false;
});
});
The idea is not working. Please suggest how to proceed... Many thanks :)
var trace = false;
$('#save').on('click', function() {
$('select.combo').each(function() {
if(this.value == 0){
trace = true;
return;
}
});
if(trace) {
// all combo not selected
alert('Please select all combo');
trace = false;
} else {
// all selected
alert('Thanks..');
}
});
How about this approach:
$('#save').click(function(){
var comboLength = $('.combo').length;
var selectedLength = $('.combo option:selected[value!=0]').length;
if (comboLength == selectedLength) { /* code for valid case*/}
else { /*code for invalid case*/; return false;}
})
TRY
HTML
<select class="combo" multiple="multiple">
<option selected="selected" value="0" >--SELECT ONE--</option>
<option value="1">Employee First Name (HR)</option>
<option value="2">Employee last Name (HR)</option>
<option value="3">Employee number (HR)</option>
<option value="4">NINO (HR)</option>
jQuery
var foo = {};
$('#submit').live('click', function() {
$('select.combo').each(function(i) {
var selected = $(this).val();
foo[i] = selected;
});
//this will remove first value ( blank having value=0)
var finalOutput = jQuery.grep(foo[0], function(value) {
//this will unselect the blank value
$('.combo option:eq(0)').prop('selected', false);
return value != "0";
});
if ($.isEmptyObject(finalOutput)) {
alert('please select atlest one')
}
else {
alert('Output:' + finalOutput)
}
})
Working DEMO
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>