How to get previously selected option? - javascript

Here's my code:
<select>
<option selected="selected">Actions</option>
<option>Create Subset</option>
<option>Goto</option>
<option>End</option>
</select>
I'm showing popup for whatever option user selects, and on pressing Esc or on clicking the close button, the popup will disappear.
Now, suppose user selected "Create Subset" option and filled appropriate data into that popup. Currently "Create Subset" will be there in select box.
Now if user changed the option to "Goto" (i.e. there will be "Goto" in the select box) and pressed Esc, hence the popup will disappear but there will still be "Goto" in the <select> box!
So my question is: Is there any way to change the select box option to the previously selected option when the user hits Esc or click the close button?

First you gotta give your option's some values and your select box - some id:
<select id="yourselect">
<option value="Actions" selected="selected">Actions</option>
<option value="Create Subset">Create Subset</option>
<option value="Goto">Goto</option>
<option value="End">End</option>
</select>
Then bind a change event to listen to your checkbox changes and remember the current and previous options that were selected:
$("#yourselect").on("change", function() {
if( $(this).data("selected") ) {
$(this).data( "prev-selected", $(this).data("selected") );
}
$(this).data( "selected", $(this).val() );
});
After that, when user presses Esc or click Cancel button, you need to restore the option
if( $("#yourselect").data("prev-selected") ) {
$("#yourselect")
.find( 'option[value="' + $("#yourselect").data("prev-selected") + '"]' )
.prop( "selected", true );
}
else {
$("#yourselect").find( "option:eq(0)" ).prop( "selected", true );
}

Since you have not added relevant code. Here i created reference jsfiddle . When user selects option from select box, it will display popup, and on close of popup it will update select. Not sure if this is what you need, let me know.
<div id='selectPopup'>
previous selected <input type='text' value='' id='selected'/>
<form name='test'>
<select id='inptPAN' name='inptPAN'>
<option value='1'>item 1</option>
<option value='2'>item 2</option>
<option value='3'>item 3</option>
<option value='4'>item 4</option>
<option value='5'>item 5</option>
<option value='6'>item 6</option>
</select>
</form>
</div>
$(document).ready(function () {
// this function is triggered as soon as something changes in the form
$("select[name='inptPAN']").change(function () {
//console.log('found change');
$("#selected").val($(this).val())
selectDialog('Pan', 'You had selected, Text: ' + $(':selected', this).text() + ' And Value : ' + $(this).val());
});
// Esc button event to close pop up.
$(document).keyup(function(event) {
if(event.which === 27) {
previousSelected = $("#selected").val();
$("#inptPAN").val('1');
// or enable below line to set previous selected
//$("#inptPAN").val(previousSelected);
$('<div></div>').dialog("close");
}
});
function selectDialog(title, text) {
return $('<div></div>').append(text)
.dialog({
resizable: true,
modal: true,
buttons: {
"CLOSE": function () {
previousSelected = $("#selected").val();
$("#inptPAN").val('1');
// or enable below line to set previous selected
//$("#inptPAN").val(previousSelected);
$(this).dialog("close");
}
}
});
}
});

Related

How to reset a selectmenu inside a modal dialog, using jQuery UI

I have a jQuery UI selectmenu inside a jQuery modal dialog. I would like to clear the selection of the selectmenu, when the modal dialog is closed, whether by the OK or Cancel buttons, or the close box.
I'm trying to update a web app I didn't write to eliminate the use of the jAlert/jConfirm/jPrompt library that seems to have been withdrawn. I built an example that I want to work before I rip apart this app I didn't write to replace many jPrompt calls.
I've demonstrated that I can display the selectmenu inside the model dialog, and can return the selection to the modal dialog, where I intend to store it where it is needed.
What I haven't been able to do so far is clear the selection from the selectmenu, when the user exits the modal dialog, by clicking the OK or Cancel buttons or the close box. I've tried to apply about a half-dozen suggestions I've found on this site, but none of those work in this case.
I've included my example here:
<button id="opener">Change Category</button>
<div id="popup_message" style="display: none;">
<form id="category_popup">
<select name="category" id="category">
<option>Choose a category</option>
<option value="G1">G1</option>
<option value="G3">G3</option>
<option value="C1G1">C1G1</option>
<option value="C2G1">C2G1</option>
<option value="C3G1">C3G1</option>
<option value="C4G1">C4G1</option>
<option value="C5G1">C5G1</option>
<option value="C6G1">C6G1</option>
<option value="C7G1">C7G1</option>
<option value="C8G1">C8G1</option>
<option value="C9G1">C9G1</option>
<option value="C1G3">C1G3</option>
<option value="C2G3">C2G3</option>
</select>
</form>
</div>
<script>
$('#popup_message').dialog({
autoOpen: false,
modal: true,
title: 'Choose Category',
buttons: [{
text: 'OK',
click: function() {
alert('Category= ' + $('#category').find(':selected').text());
$(this).dialog('close');
return $('#category').val();
}
},
{
text: 'Cancel',
click: function() {
$(this).dialog('close');
}
}
]
});
$('#opener').on('click', function() {
$('#popup_message').dialog('open');
});
$('#popup_message').on('dialogclose', function() {
// $('#category_popup option').attr('selected',false);
// $('#category_popup').trigger('reset');
$('#category').selectmenu('refresh');
// $(':input','#category_popup').removeAttr('selected');
// $('#category_popup').val([]);
truth = true; // to allow a breakpoint here
});
$('#category').selectmenu();
</script>
You need to change the index before like this :
$('#popup_message').on('dialogclose', function() {
// $('#category_popup option').attr('selected',false);
// $('#category_popup').trigger('reset');
var myselect = $("select#category");
myselect[0].selectedIndex = 0;
myselect.selectmenu("refresh");
// $(':input','#category_popup').removeAttr('selected');
// $('#category_popup').val([]);
truth = true; // to allow a breakpoint here
});

how to detect if select2 has been loaded upon clicking the input field in jquery?

Hi is there a way to check if the select2 options has been loaded upon clicking the input field ? because what happening now is, when I click the input box, nothing happen even if the box got loaded, i had to click it the second time before something happens like e.g
$('form#myform .selection').click(function(){
//how to detect if select2 option are loaded ?
});
You can check for the length property of the option selector for select2, you can use it the same way within the click event :
$(document).ready(function(){
console.log(" KAD : " + $("#kad").find('option').length);
console.log(" KAD2 : " + $("#kad2").find('option').length);
if($("#kad").find('option').length > 0)
{
// has options
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="kad"></select>
<select id="kad2">
<option > 1 </option><option > a </option><option > b </option>
</select>

jQuery Mobile: applying method selectmenu on multiple select fields

On my jQuery Mobile page I would like to implement multiple filter select menus. It works totally fine with only one select menu and an id, but not with multiple.
JSFiddle with my problem:
http://jsfiddle.net/asvyY/40/
(By contrast, my fiddle with ONLY ONE select menu and a select menu id works: http://jsfiddle.net/asvyY/41/)
Error message:
Uncaught Error: cannot call methods on selectmenu prior to initialization; attempted to call method 'refresh'
My code:
HTML:
<div data-role="page" id="page1">
<div data-role="header">
<h1>My page</h1>
</div>
<div role="main" class="ui-content">
<form>
<select class="filter-menu" data-native-menu="false">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select class="filter-menu" data-native-menu="false">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select class="filter-menu" data-native-menu="false">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</form>
</div>
</div>
JS:
$(document).on("pagecreate", "#page1", function(){
$(".filter-menu").selectmenu( "refresh", true );
});
$.mobile.document
.on("listviewcreate", "#filter-menu-menu", function (e) {
var input,
listbox = $("#filter-menu-listbox"),
form = listbox.jqmData("filter-form"),
listview = $(e.target);
if (!form) {
input = $("<input data-type='search'></input>");
form = $("<form></form>").append(input);
input.textinput();
$("#filter-menu-listbox")
.prepend(form)
.jqmData("filter-form", form);
}
listview.filterable({
input: input
});
})
// The custom select list may show up as either a popup or a dialog,
// depending how much vertical room there is on the screen. If it shows up
// as a dialog, then the form containing the filter input field must be
// transferred to the dialog so that the user can continue to use it for
// filtering list items.
//
// After the dialog is closed, the form containing the filter input is
// transferred back into the popup.
.on("pagebeforeshow pagehide", "#filter-menu-dialog", function (e) {
var form = $("#filter-menu-listbox").jqmData("filter-form"),
placeInDialog = (e.type === "pagebeforeshow"),
destination = placeInDialog ? $(e.target).find(".ui-content") : $("#filter-menu-listbox");
form.find("input")
// Turn off the "inset" option when the filter input is inside a dialog
// and turn it back on when it is placed back inside the popup, because
// it looks better that way.
.textinput("option", "inset", !placeInDialog)
.end()
.prependTo(destination);
});
Here is my working JSFiddle: http://jsfiddle.net/asvyY/46/
I deleted the following lines, because jqm automatically transforms the select-tag into a select-menu
$(document).on("pagecreate", "#page1", function(){
$(".filter-menu").selectmenu( "refresh", true );
});
The correct syntax for the listviewcreate event is:
$( ".selector" ).on( "listviewcreate", function( event ) {} );
In the listviewcreate event i changed the id's to classes and initiated the listbox
listbox = $("<ul class='.filter-menu-listbox'></ul>");
I hope i could help you and sry for my bad english :)
You are running into problems because with multiple selectmenus you are using class names and no ids.
Give your selectmenus unique ids as well as the common class name. For the listviewcreate you can use the classnames and find other dom elements using closest()/find().etc.
$.mobile.document.on("listviewcreate", ".ui-selectmenu-list", function (e) {
var input,
listbox = $(this).closest(".ui-selectmenu"),
form = listbox.jqmData("filter-form"),
listview = $(this);
if (!form) {
input = $("<input data-type='search'></input>");
form = $("<form></form>").append(input);
input.textinput();
listbox
.prepend(form)
.jqmData("filter-form", form);
}
listview.filterable({
input: input
});
})
In the case of a long list showing as a dialog. I am retrieving the base ID of the selectmenu and then using it to build selectors as needed:
.on("pagebeforeshow pagehide", ".ui-selectmenu.ui-dialog", function (e) {
var id=$(this).prop("id").replace("-dialog","");
var form = $("#" + id + "-listbox").jqmData("filter-form"),
placeInDialog = (e.type === "pagebeforeshow"),
destination = placeInDialog ? $(this).find(".ui-content") : $("#" + id + "-listbox");
form.find("input")
// Turn off the "inset" option when the filter input is inside a dialog
// and turn it back on when it is placed back inside the popup, because
// it looks better that way.
.textinput("option", "inset", !placeInDialog)
.end()
.prependTo(destination);
});
Updated FIDDLE

Get previously selected value or prevent default on select

Is it possible on <select> get previously selected value or prevent default somehow? For example i have
<select id="select_site" name="sites" selectedindex="0">
<option value="">Please select site</option>
<option value="4">first</option>
<option value="5" selected="selected">second</option>
<option value="8">third</option>
</select>
So if selected option with null value i need to restore previously selected second value.
You can bind a change event handler to the element and store the new value in a variable. If the value is an empty string, set it to whatever is in the variable:
$('#select_site').change(function() {
if (this.value === '') {
this.value = $(this).data('previous_value');
}
else {
$(this).data('previous_value', this.value);
}
}).triggerHandler('change'); // <- trigger change event to get initial value
DEMO
no js needed:
<select id="select_site" name="sites" selectedindex="0">
<optgroup label="Please select site">
<option value="4">first</option>
<option value="5" selected="selected">second</option>
<option value="8">third</option>
</optgroup>
</select>
demo: http://jsbin.com/obeker/1/
ref: https://developer.mozilla.org/docs/HTML/Element/optgroup
No you cannot do that because the change event is fired after the select is focused out, not before the selection is changed. There is no native "onbeforechange" event but you can remove the empty value once the selection is changed so it is no longer available.
Code to do this:
$('select').change(function (event) {
$this = $(this);
if ($this.val() !== '') {
$this.children('option:first').remove();
}
});

jQuery cookies setting select drop down value after page refresh

In all honesty my brain is rather fried after getting this far today.
I am trying to save the state of multiple select drop downs on page using this plugin:
http://plugins.jquery.com/project/cookies
I am using this jQuery to set cookies for the different title drop downs based on their ID:
$(document).ready(function() {
// hide 'Other' inputs to start
$('.jOther').hide();
// event listener on all select drop downs with class of jTitle
$(".jTitle").change(function(){
//set the select value
var val = $(this).val();
if(val != "Other") {
//$(this).nextAll('.jOther').hide();
$(this).parent().find(".jOther").hide();
} else {
//$(this).nextAll('.jOther').show();
$(this).parent().find(".jOther").show();
}
// Sets a cookie with named after the title field's ID attribute
$(this).cookify();
});
$(".jTitle").each(function(){
// get the id of each Title select drop down
var $titleId = $(this).attr('id');
// get the value of the cookie for each cookie created above in $(this).cookify()
var $cookieValue = $.cookies.get($titleId);
// if value is 'Other' make sure it is shown on page refresh
if ($cookieValue == 'Other') {
// Show the other input
$(this).parent().find(".jOther").show();
// set select value to 'Other'
$(this).val('Other');
} else {
// set to whatever is in the cookie
$(this).val($cookieValue);
}
});
});
What is happening is that when no cookies are set the select drop down is displaying a blank option when i want it to default to 'Please select'.
Sample HTML that i am using:
<td>
<select id="titleDepend1" class="inlineSpace jTitle">
<option value="Please select">Please select...</option>
<option value="Mr">Mr</option>
<option value="Mrs">Mrs</option>
<option value="Ms">Ms</option>
<option value="Miss">Miss</option>
<option value="Dr">Dr</option>
<option value="Other">Other</option>
</select>
<label for="otherDepend1" class="inlineSpace jOther">Other</label>
<input type="text" class="text jOther" name="otherDepend1" id="otherDepend1" maxlength="6" />
So if it is the first time the user is on page and they have not clicked any drop downs the first value will be null rather than 'Please select'.
I'd change this portion, if the cookie isn't there, just don't mess with the dropdown:
$(".jTitle").each(function(){
var $titleId = $(this).attr('id');
var $cookieValue = $.cookies.get($titleId);
if ($cookieValue == 'Other') {
$(this).parent().find(".jOther").show();
$(this).val('Other');
} else if($cookieValue) {
$(this).val($cookieValue);
}
});
The only change is to add an if check on the end, see if there is a cookie...if not the default position of 0 in the dropdown (browser default) will be left alone.

Categories

Resources