javascript - select option jquery issue - javascript

In my application, I want to let user select an option from the drop down menu at anytime. But when the page reloads, it goes back to the default value (the first element in the drop down list).
My HTML looks like this:
<select class="author">
<option value="aaa">aaa</option>
<option value="bbb">bbb</option>
<option value="ccc">ccc</option>
</select>
In my javascript, i use the following for letting the user select an option:
auid = $('#tabs' .author option:selected').prop('value');
I am actually retrieving the value of author that was selected before page reloads from the localstorage by:
auid = localStorage.getItem("latestAuthor");
Can someone tell me how does this all fit together with example code snippet to let me select an option from drop down menu, and the same option stays selected when the page reloads, but the user can select another option from the drop down menu at anytime as well.

On page load, once that select box exists, and once you've retrieved auid from local storage, do this:
if (auid !== null) {
$("#tabs .author").val(auid);
}
The if is there because if you've never set the value in local storage, that's what you'll get back from getItem.
Side note: When getting the value, don't use prop('value'). Use .val:
auid = $("#tabs .author").val();
Complete example on jsFiddle (since Stack Snippets don't allow local storage ☹ ). This assumes it's in a script tag at the end of the HTML, just before the closing </body> tag (which is where you should put them unless you have a good reason not to).
// Scoping function to avoid global vars
(function() {
var auid = localStorage.getItem("latestAuthor");
if (auid !== null) {
$("#tabs .author").val(auid);
}
$("#tabs .author").on("change", function() {
auid = $(this).val();
localStorage.setItem("latestAuthor", auid);
});
})();
If for some reason you can't put the script tag at the very end, you can use jQuery's "DOM ready" callback:
jQuery(function() {
var auid = localStorage.getItem("latestAuthor");
if (auid !== null) {
$("#tabs .author").val(auid);
}
$("#tabs .author").on("change", function() {
auid = $(this).val();
localStorage.setItem("latestAuthor", auid);
});
});
(You can cache the result of $("#tabs .author") in a variable if you want to avoid doing it twice, but doing it twice on page load is nothing.)

Works fine for me.
Possible typo error
auid = $('#tabs' .author option:selected').prop('value');
^
Sample:
$(".btn").on("click", function() {
var auid = $('#tabs .author option:selected').prop('value');
console.log(auid);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="tabs">
<select class="author">
<option value="aaa">aaa</option>
<option value="bbb">bbb</option>
<option value="ccc">ccc</option>
</select>
</div>
<button class="btn">Click Me</button>
Also for sample of integrating with LocalStorage, check following code:
Note: Stackoverflow does not allows to access localStorage and you should test it on fiddle.
JSFiddle
var _lsKey = "test";
function registerEvents(){
$(".btn").on("click", function() {
var auid = $('#tabs .author option:selected').prop('value');
saveValueToLS(_lsKey, auid);
});
}
function saveValueToLS(key, value){
localStorage.setItem(key, value);
}
function getValueFromLS(key){
return localStorage.getItem(key);
}
function initializeSelect(){
var lsVal = getValueFromLS(_lsKey);
$(".author").val(lsVal);
}
function initializePage(){
registerEvents();
initializeSelect();
}
initializePage();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="tabs">
<select class="author">
<option value="aaa">aaa</option>
<option value="bbb">bbb</option>
<option value="ccc">ccc</option>
</select>
</div>
<button class="btn">Click Me</button>

Related

jQuery select link not working on Chrome

I want to have an option in select that takes a user to other page after clicking it.
Below function works on Edge and Mozilla, on Chrome not:
<select>
<option value="#Url.Action("Home")" id="some-id"> Take me somewhere
</option>
</select>
<script>
$('#some-id').click(function () {
window.location.href = this.value;
});
</script>
Please help!
I'd rewrite your code:
<select id='some-id'>
<option value="#Url.Action("Home")" > Take me somewhere
</option>
</select>
<script>
$('#some-id').on('change', function () {
window.location.href = this.value;
});
</script>
You must take a value from select Element. That way you can check if select value has changed and take user selected value.
<select id='some-id'>
<option value="#Url.Action("Home")" > Take me somewhere
</option>
</select>
<script>
$('#some-id').on('change', function (event) {
window.location = event.target.value;
});
</script>
P.s.: Better not to use this keyword but take it from event target. As using this can get You in trouble.

When registering both onchange and onclick on a select, the click event is triggered twice

Goal: Have a select whose option have nested structure when user clicks on the select, but when user selects an option the option should be displayed "normally" (ie with no leading spaces).
Attempted solution using JS and Jquery: My JS is far from sophisticated so I apologize in advance :)
I attempted to use .on("change") and .on("click") to change the selected option value (by calling .trim() since I achieve the "nested" structure with ). I'm also storing the original value of the selected option because I want to revert the select menu to its original structure in case the user selects another option.
The problem: The function registered for .on("click") is called twice, thus the select value immediately resets itself to its original value.
I suspect there is a much, much easier solution using CSS. I will be happy to accept an answer that will suggest such solution.
JSFiddle: https://jsfiddle.net/dv6kky43/9/
<form>
<select id="select">
<option value=""></option>
<option value="a"> a</option>
<option value="b"> b</option>
</select>
</form>
<textarea id="output"/>
var orig;
var output = $("#output");
output.val("");
function onDeviceSelection(event){
output.val(output.val() + "\nonDeviceSelection");
var select = event.target;
orig = select.selectedOptions[0].text;
select.selectedOptions[0].text = select.selectedOptions[0].text.trim()
}
function resetDeviceSelectionText(event) {
output.val(output.val() + "\nresetDeviceSelectionText");
var select = event.target;
if (orig !== undefined){
select.selectedOptions[0].text = orig;
}
}
$("#select").on("change", onDeviceSelection);
$("#select").on("click", resetDeviceSelectionText);
If you are already using jQuery, why not utilize data function to store the original value. This way you will also be able to specify different nest levels.
(function($){
$(document).on('change', 'select', function(event) {
$(this).find('option').each(function(index, element){
var $option = $(element);
// Storing original value in html5 friendly custom attribute.
if(!$option.data('originalValue')) {
$option.data('originalValue', $option.text());
}
if($option.is(':selected')) {
$option.html($option.data('originalValue').trim());
} else {
$option.html($option.data('originalValue'));
}
})
});
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<select id="select">
<option value=""></option>
<option value="a"> a</option>
<option value="b"> b</option>
</select>
</form>
Once caveat I see is, the selected option will appear trimmed on the list as well, if dropdown is opened after a previous selection has been made:
Will it still work for you?
Instead of keeping the state of the selected element i would simply go over all options and add the space if that option is not selected:
function onDeviceSelection(event){
// Update textarea
output.val(output.val() + "\nonDeviceSelection");
// Higlight the selected
const {options, selectedIndex} = event.target;
for(let i = 0; i < options.length; i++)
options[i].innerHTML = (i === selectedIndex ? "":" ") + options[i].text.trim();
}
$("#select").on("change", onDeviceSelection);
Note that you need to use innerHTML to set the whitespace...

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

Getting a Select Value after appending

This is for javascript and jquery.
I have in my body...
<select id="option1_select" name="courseCodeSelectName">
<option></option>
<option>Word1</option>
<option>Word2</option>
</select>
<script>
$("select").change(function () {
functionLoadOpt2() }).trigger("change" );
</script>
<select id="option2_select" name="courseNumSelectName">
<option></option>
</select>
<button onclick="changePage()">Load Textbook Page!</button>
As we see above, the web page has 2 select boxes and a button. Depending on what you select in the first select box loads what is in the second one, using the functionLoadOpt2 function locating higher up in my code.
if (result == "Word1") {
$("#option2_select").append('<option>Letter1</option>');
...
There is more but it follows the same code different values.
Result is the following, above the if statement(just a row up),
var result = (document.getElementById('option1_select').value);
now on the button click, the function changePage() runs,
and all I want is ...
var result = (document.getElementById('option1_select').value);
var result2= (document.getElementById('option2_select').value);
Assume they selected and option for both. Result2 doesnt work. I'd imagine because I'm appending it but how would I work around this. So that when I click changePage() I get the selected value of option1_select and option2_select.
functionLoadOpt2:
function functionLoadOpt2(){
var opt1Val = (document.getElementById('option1_select').value);
$("#option2_select").find('option').remove().end().append('<option></option>');
if (opt1Val == "Word1") {
$("#option2_select").append('<option>Letter1</option>');
$("#option2_select").append('<option>Letter2</option>');
$("#option2_select").append('<option>Letter3</option>');
$("#option2_select").append('<option>Letter4</option>');
$("#option2_select").append('<option>Letter5</option>');
}else if (opt1Val == "Word2") {
$("#option2_select").append('<option>Letter3</option>');//they have similar ones in some cases
$("#option2_select").append('<option>Letter6</option>');
$("#option2_select").append('<option>Letter7</option>');
$("#option2_select").append('<option>Letter8</option>');
$("#option2_select").append('<option>Letter9</option>');
$("#option2_select").append('<option>Letter10</option>');
$("#option2_select").append('<option>Letter11</option>');
$("#option2_select").append('<option>Letter12</option>');
$("#option2_select").append('<option>Letter13</option>');
$("#option2_select").append('<option>Letter14</option>');
$("#option2_select").append('<option>Letter15</option>');
$("#option2_select").append('<option>Letter16</option>');
$("#option2_select").append('<option>Letter17</option>');
//this works
}
}
use jQuery to get and set the value of <select> with .val()
Both your select elements have the same id, fix it the it should be fine
<select id="option1_select" name="courseCodeSelectName">
<option></option>
<option>Word1</option>
<option>Word2</option>
</select>
<select id="option2_select" name="courseNumSelectName">
<option></option>
</select>
<button onclick="changePage()">Load Textbook Page!</button>
Demo: Fiddle
Note: You can improve the script a lot by using proper jQuery constructs, like this

JQuery On Select change assign value to variable and reload script

Is it possible at all to be able to assign the selected value of a select and assign it to the variable of a script and re-run the script?
Here is my current code sample:
<select onchange="reload_script;">
<option value="123">Select 123</option>
<option value="456">Select 456</option>
<select>
<div id="123">
link title
<br/><br/>
Link
</div>
<script language="javascript" type="text/javascript">
var code = '123' // <-- THIS VARIABLE WOULD BE THE VALUE OF THE SELECTED DROPDOWN VALUE
</script>
See: var code = '123' .... That's what's changed when the select box is changed ... then I would need the script to re-run...
Is this possible at all?
If you use jQuery you can always bind change event:
var code = "123";
$("#mySelect").on("change", function() {
code = this.value;
reload_script();
});
Otherwise, in plain JavaScript it may look like this:
var code = "123";
document.getElementById("mySelect").onchange = function() {
code = this.value;
reload_script();
};
Try this
<select onchange="reload_script();">
<option value="123">Select 123</option>
<option value="456">Select 456</option>
<select>
<div id="123">
link title
<br/><br/>
Link
</div>
<script language="javascript" type="text/javascript">
var code = '123' // <-- THIS VARIABLE WOULD BE THE VALUE OF THE SELECTED DROPDOWN VALUE
function script_to_run()
{
//do code here
}
// Call the script one time on page load (only if you need it on page load)
script_to_run();
function reload_script()
{
script_to_run();//run again
}
</script>

Categories

Resources