moving select options up and down via jquery - javascript

so I got this code working for Firefox and Chrome...what it does is it allows you to reorder the options within an HTML select form...but then when I tested the code via IE8, it's kind of patchy...it only works for the first few clicks and after that you have to click many times on the button for it to work..
Does anybody know any other code that allows you to reorder select field items that works perfectly in IE8?
<select id="list" multiple="multiple">
<option value="wtf">bahaha</option>
<option value="meh">mwaahaha</option>
</select>
<button id="mup">Move Up</button>
<button id="mdown">Move Down</button>
Add Item
Remove item
<script>
$(document).ready(function(){
$('#mup').click(function(){
moveUpItem();
});
$('#mdown').click(function(){
moveDownItem();
});
});
function moveUpItem(){
$('#list option:selected').each(function(){
$(this).insertBefore($(this).prev());
});
}
function moveDownItem(){
$('#list option:selected').each(function(){
$(this).insertAfter($(this).next());
});
}

Your code for changing the options works fine. It seems IE8 isn't handling a "fast" second-click with the click event but rather expects a double click to be handled.
Using my test code below, you'll notice that in IE8 writes out the following when Move Down/Up is pressed "fast":
Move Down Click
Move Down Double-Click
Move Down Click
Move Down Double-Click
But with FF/Chrome the following is printed:
Move Down Click
Move Down Click
Move Down Double-Click
Move Down Click
Move Down Click
Move Down Double-Click
Here's the code I'm using to test. I haven't done any tests to see if it's jQuery's event binders that are causing the issues.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Test</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script>
</head>
<body>
<select id="list" multiple="multiple">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
</select>
<button id="mup">Move Up</button>
<button id="mdown">Move Down</button>
<script type="text/javascript">
var $DEBUG = null;
$(document).ready(function ()
{
$DEBUG = $("#debug");
$DEBUG.append("Registering Events<br />");
$("#mup").click(moveUpItem);
$("#mdown").click(moveDownItem);
$("#mup").bind("dblclick", function ()
{
$DEBUG.append("Move Up Double-Click<br />");
});
$("#mdown").bind("dblclick", function ()
{
$DEBUG.append("Move Down Double-Click<br />");
});
});
function moveUpItem()
{
$DEBUG.append("Move Up Click<br />");
}
function moveDownItem()
{
$DEBUG.append("Move Down Click<br />");
}
</script>
<div id="debug" style="border: 1px solid red">
</div>
</body>
</html>
EDIT: I can confirm it is IE8 that is the problem. Swap this IE8-specific code in the $(document).ready() handler:
// $("#mup").click(moveUpItem);
$("#mup")[0].attachEvent("onclick", moveUpItem);
// $("#mdown").click(moveDownItem);
$("#mdown")[0].attachEvent("onclick", moveUpItem);
// $("#mup").bind("dblclick", function ()
$("#mup")[0].attachEvent("ondblclick", function ()
{
$DEBUG.append("Move Up Double-Click<br />");
});
// $("#mdown").bind("dblclick", function ()
$("#mdown")[0].attachEvent("ondblclick", function ()
{
$DEBUG.append("Move Down Double-Click<br />");
});

Example:
to move 3rd option before 1st option, we can use below jquery:
$('select[name="NameOfDropDown"] option:eq(2)').insertBefore($('select[name="NameOfDropDown"] option:eq(0)'));

I think this will give some ideas of how to do it, you can dynamically place any option before one known position just by knowing the values of both, the one to move and the one of the position:
How would you dynamically order an <option select> list using JQuery?

I know this one is a bit old, but I recently made this simple jQuery plugin to be able to reorder elements in a multiple select element.
Have a look and see if it helps for you, I tested in IE8,IE9,Chrome,FireFox,Opera.
http://fedegiust.github.io/selectReorder/

Related

JS - apply global function to all select boxes

I have 200+ select boxes, each individually named and with Yes / No / NA as answer options, and now would like to have the background of the <option value="No> option highlighted in red once it is selected.
This works fine via the onchange attribute when adding it to the specific select box, however since I have 200 of those, I do not want to apply this code one by one, but rather apply a global JS function to all <select> boxes, which is where I am stuck. How can I address all select boxes with one JS function?
Javascript:
$('select').on('change', function () {
$(this).focus();
$(this).select();
$(this).className = this.options[this.selectedIndex].className;
});
CSS:
.green{ background-color:green; }
.red{ background-color:red; }
HTML:
<select id="boh_corridor" name="boh_corridor">
<option value=""></option>
<option value="Yes" class="green">Yes</option>
<option value="No" class="red">No</option>
</select>
EDIT: to be exact, the problem is that the option is not highlighted in either red or green at the moment, hence I am suspecting that the function is not being applied. The goal is to have the option highlighted in red/green when selected and while being selected from the dropdown menu.
Two things:
jQuery objects don't have a className property; DOM elements do. Instead of
$(this).className = ...
use
this.className = ...
Your code hooks the change event on select elements that exist as of when that code runs. So you need to be sure they exist prior to running that code. You can do that by ensuring your script tag is at the end of the document, just prior to the closing </body> tag; or by using jQuery's ready callback. Alternately, you can use event delegation (covered later).
Example expecting that the script tag will be at the end of the document (which is where Stack Snippets put it), which is best practice:
$('select').on('change', function() {
$(this).focus();
$(this).select();
this.className = this.options[this.selectedIndex].className;
});
.green {
background-color: green;
}
.red {
background-color: red;
}
<select id="boh_corridor" name="boh_corridor">
<option value=""></option>
<option value="Yes" class="green">Yes</option>
<option value="No" class="red">No</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
If you don't control where your script tags go or prefer to do something else, using jQuery's ready:
$(document).ready(function() {
// ...the code here...
});
Another option is event delegation. Although change doesn't natively bubble, jQuery makes it bubble, and so you can do this:
$(document).on("change", "select", function() {
$(this).focus();
$(this).select();
this.className = this.options[this.selectedIndex].className;
});
Then it doesn't matter whether the select elements exist or not when you run that code; the event handler is on document, not the individual selects. So it doesn't matter where the script tag is, and you don't need ready.
Example:
$(document).on('change', 'select', function() {
$(this).focus();
$(this).select();
this.className = this.options[this.selectedIndex].className;
});
.green {
background-color: green;
}
.red {
background-color: red;
}
<select id="boh_corridor" name="boh_corridor">
<option value=""></option>
<option value="Yes" class="green">Yes</option>
<option value="No" class="red">No</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Side note: You can use chaining with jQuery objects, rather than repeatedly calling $(): $(this).focus().select();
Do you have a common class for those select boxes? If you do, you can select them doing this:
$(".your_class").on("change", function(){
$(this).addClass("border_red"); //add border to select
$("option",this).removeClass("red"); //clear classes
$("option:selected", this).addClass("red"); //add .red class
});
Check out the fiddle: https://jsfiddle.net/m5mzwyt2/
The code below works for me, both in the sense of highlighting the option value in green / red, and to keep the background color once the option has been selected
JS:
$(document).ready(function() {
$('select').on('change', function () {
$(this).focus();
$(this).select();
this.className = this.options[this.selectedIndex].className;
});
});
I'm not sure what exactly you want to achieve.
I changed your code to:
$('select').on('change', function () {
$(this).focus();
$(this).select();
$(this).css("background-color",$(this).find(":selected").attr("class"));
});
It sets the background color after select based on class name.
Tested on Firefox

jquery Event Listener on DropDown Open

Having this simple dropdown menu:
<select id="foo">
<option>bar</option>
</select>
And an jQuery listener initialization like this:
$("#foo").on("click", function() {
console.log("stuff");
});
The event is only fired when the user closes the drop down, either by selecting an option or by clicking outside of the box. Is there any way to get the event, when he opens the box?
The right event for this purpose is change click together and will get fire every time that select input changed or clicked.
$("#foo").on("click change", function(e) {
$("#output").html("Event type: " + e.target.nodeName);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="foo">
<option value="1">foooo</option>
<option value="2">bar</option>
</select>
<div id="output"></div>
Try events:
show.bs.dropdown
shown.bs.dropdown
https://getbootstrap.com/docs/4.0/components/dropdowns/#events
$(document).on('focus', '#foo', function () {
console.log('Dropdown Open');
});
Works for me !!

Show a div on option selection

I have a selection menu (drop down list).
<select>
<option id="one" value="something">Car</option>
<option id="two" value="anything">Plane</option>
</select>
& the following div which located in somewhere in my page.
<div id="somediv">This is a string.</div>
I want to display the above div upon selecting the second item of the menu (id="two").
I have 2 questions: (1) What is the best way to keep this div hidden by default? I will just add display:none; to its styling, but maybe there is a better solution? (2) How can I make the div show up when the option of id="two" is selected? Any answer would be greatly appreciated.
So I wrote a simple jquery script that does what you described. Let me know if it fixes your problem. You can also do this with javascript, but I think jquery works for this just fine.
http://codepen.io/Francisco104/pen/vEPRgp
$('select').change(function(){
decide($(this));
});
var decide = function (elem) {
var touch = elem;
if (touch.val() === 'anything') {
return $('#somediv').css('display', 'block');
}
};
For hiding it by default, using style="display: none"is the easiest. You could do it using jquery $('div#somediv').hide(); but I don't see any benefit to that other than you possibly wanting to keep the show/hide logic together.
Here are two simple solutions using a change() event.
If div#somediv should be shown permanently when option#two has been selected:
$("select").change(function() {
if ($(this).val() == 'anything') $('div#somediv').show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option id="one" value="something">Car</option>
<option id="two" value="anything">Plane</option>
</select>
<div id="somediv" style="display: none">This is a string.</div>
If div#somediv should be shown while option#two is selected and disappear if the user selects another option:
$("select").change(function() {
$('div#somediv').toggle($(this).val() == 'anything');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option id="one" value="something">Car</option>
<option id="two" value="anything">Plane</option>
</select>
<div id="somediv" style="display: none">This is a string.</div>
You should probably give an id to the select as well, to make the jQuery selector less brittle.
So, I'd have a class for the div, let's say, is-hidden and my CSS will have .is-hidden { display: none; }. Then, do the following.
HTML:
<div id="somediv" class="is-hidden">This is a string.</div>
JS:
$div = $("#somediv");
$("select").on("change", function() {
$div.is(".is-hidden") || $div.addClass("is-hidden");
//Option 1
if ($(this).find(":selected")[0].id === "two") {
$div.removeClass("is-hidden");
}
//Option 2 (same as above, but a bit shorter)
$(this).find(":selected")[0].id === "two" && $div.removeClass("is-hidden");
});
Here is what you can do:
in your html file:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<select>
<option id="one" value="something">Car</option>
<option id="two" value="anything">Plane</option>
</select>
You'll need to import the JQuery library (which I show you there right above the <select> element) so that you can execute your script.
In your css file:
#somediv {
display: none;
}
and finally here is the script that will show the dive when "plane" is selected
$('select').change(function(){
$('#somediv').css('display','block');
});
Take a look at this JSFIDDLE I made for you.
1) You can hide the div initially giving the css property display:none; or by setting its display property using javascript which will run in initial load.
2) You can listen to the onchange event of the selectfield and check if value is 'anything' then show the div by changing its display style property to block and hidden in other cases.
document.getElementById("somediv").style.display='none';
var showHideDiv=function(selectField){
var divElement=document.getElementById("somediv");
if (selectField.value=='anything')
divElement.style.display='block';
else
divElement.style.display='none';
}
<select onchange='showHideDiv(this)'>
<option id="one" value="something">Car</option>
<option id="two" value="anything">Plane</option>
</select>
<div id="somediv">This is a string.</div>
The simplest way to hide within HTML
<div hidden>content</div>
To display an hidden div
$(document).ready(function(){
$("select").change(function () {
$( "select option:selected").each(function(){
if($(this).attr("value")=="anything"){
$("#somediv").show();
}
});.
});
Display none works.
Have you tried keying into the onchange event? http://www.w3schools.com/jsref/event_onchange.asp?

jQuery change event on dropdown

I just added the query lib to my web app and tested with simple alert:
<script src="<c:url value="/resources/jquery-1.10.2.min.js" />"></script>
<script type="text/javascript">
$(function(){
alert('jquery is working');
});
</script>
And works fine. However when i want to implement an "change" event on my dropdown
<script src="<c:url value="/resources/jquery-1.10.2.min.js" />"></script>
<script type="text/javascript">
$("#projectKey").change(function() {
alert($('option:selected', $(this)).text());
});
</script>
it displays me no alert, basically nothing is happening. My drop down is the following:
<select id="projectKey" name="projectKey">
<option value="AM">AM</option>
<option value="AIL">AIL</option>
<option value="NEB">NEB</option>
<option value="SSP">SSP</option>
</select>
Of course i tried to simplify the javascript, just o have
$("#projectKey").change(function() {
alert("test");
});
but still no joy. It will be something with the selector or the drop down. Tried also "select#projectKey" but the result was of course the same. Any idea what i am doing wrong?
You should've kept that DOM ready function
$(function() {
$("#projectKey").change(function() {
alert( $('option:selected', this).text() );
});
});
The document isn't ready if you added the javascript before the elements in the DOM, you have to either use a DOM ready function or add the javascript after the elements, the usual place is right before the </body> tag
Please change your javascript function as like below....
$(function () {
$("#projectKey").change(function () {
alert($('option:selected').text());
});
});
You do not need to use $(this) in alert.
Or you can use this javascript
$(function () {
$("#projectKey").change(function () {
alert($('#projectKey option:selected').text());
});
});
The html
<select id="drop" name="company" class="company btn btn-outline dropdown-toggle" >
<option value="demo1">Group Medical</option>
<option value="demo">Motor Insurance</option>
</select>
Script.js
$("#drop").change(function () {
var category= $('select[name=company]').val() // Here we can get the value of selected item
alert(category);
});

How to update select options before showing them in Jquery?

Look at this example code:
<html>
<head>
<script type="text/javascript" src="jquery-1.8.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("body").on('click', "#teste",function(){
$('#teste').append('<option id="pera">pera</option>')
$('#teste').show();
});
});
</script>
</head>
<body>
<select id="teste">
<option value="banana">banana</option>
<option value="laranja">laranja</option>
</select>
</body>
My problem here is that the click event show the select box and only after it updates it with the new value ("pera"). What I need to do is first update the select with the new value and only after show it. Is there anyway to do that using jQuery? Thanks in advance, guys!
EDIT:
Ok, let me try to explain a little bit clear: Whenever you click in a select to show the options it show it automatically (it's obvious!). My problem is that I need to intercept the click event, update the select and only after it show the select. But it's showing the select (it's the default behaviour) before updating. Here is what happening:
1) Select with initial values: banana, laranja
2) User click it. What I want: Show banana, laranja and pera as options. What happens: It shows banana, laranja in the list, show it and only after update the select (If I inspect the html code with fiebug, the pera option is there!). If I click again inthe select, the pera options appears normally and as the code above says, it appends another pera option in the select that only appears in the next click and so on.
I'm a little bit confused.. do you just want to update the select when the page loads? If so you can do:
CSS:
#teste {
display: none;
}
JS:
$(function(){
$('#teste').append('<option id="pera">pera</option>').val("pera").show();
});
I think this might be what you are searching for:
Using the value:
$('[name=options]').val( 3 );//To select Blue
To reset it use:
$('[name=options]').val( '' );
Using the text:
$('[name=options] option').filter(function() {
return ($(this).text() == 'Blue'); //To select Blue
}).prop('selected', true);
Link: http://forum.jquery.com/topic/how-to-dynamically-select-option-in-dropdown-menu
i think you want to prevent showing multiple times the teste option.
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<style>
#teste{
display: none;
}
</style>
<script type="text/javascript">
$(document).ready(function(){
$(document).click(
function(){
if(!$('#teste').is(':visible')){
$('<option/>',{
'id' : 'pera',
'html' : 'pera',
'selected' : 'selected'
}).appendTo('#teste');
$('#teste').show('slow');
}
})
});
</script>
</head>
<body>
<select id="teste">
<option value="banana">banana</option>
<option value="laranja">laranja</option>
</select>
</body>

Categories

Resources