Select box option not show selected - javascript

I'm trying to copy or move one select box item to another select box. The problem is that when one or more items are moved from the first box to the second, it should be selected. But it's not working.
My Code
function SelectMoveRows(SS1,SS2)
{
var SelID='';
var SelText='';
var SelText2='';
// Move rows from SS1 to SS2 from bottom to top
for (i=SS1.options.length - 1; i>=0; i--)
{
if (SS1.options[i].selected == true)
{
SelID=SS1.options[i].value;
SelText=SS1.options[i].text;
SelText2=SS1.options[i].attr("selected");
var newRow = new Option(SelText,SelID,SelText2);
SS2.options[SS2.length]=newRow;
SS1.options[i]=null;
}
}
SelectSort(SS2);
}
Then I use
SelText2=SS1.options[i].attr("selected");
But it's not working. If I use:
SelText2=SS1.options[i].select=true;
then option looks like:
<option value="3" selected="">Delivery</option>
But it should be:
<option value="3" selected="selected">Delivery</option>

In the option tag, the attribute selected doesn't need a value:
<option value="3" selected>Delivery</option>
is the same as
<option value="3" selected="selected">Delivery</option>
check it here:
http://jsfiddle.net/n99L2xhv/1/

you should use .prop not .attr
e.g.
SelText2=SS1.options[i].prop("selected", true);
for reference: .prop() vs .attr()
Update I would go about doing this as follows;
<select id="select1">
<option value="1">Option1</option>
<option value="2">Option2</option>
</select>
<select id="select2">
<option value="3">Option3</option>
</select>
$("#select1").change(function(){
$("#select1 option:selected").each(function() {
var option = $(this);
$("#select2").append(option);
$("#select1").remove(option);
});
});
This will shift the selected option from Select 1 to Select 2 when it is chosen.

As pointed out by David Thomas in the comments, .attr() is not a valid method on a select element; It is a method on a jQuery object, which you don't have.
You could just pass true as the parameter to the Option constructor, and the third parameter is really the defaultSelected property, while the fourth paramter is the selected property.
for (var i = SS1.options.length - 1; i >= 0; i--) {
var option = SS1.options[i];
if (option.selected) {
SS2.add(new Option(option.text, option.value, false, true));
SS1.remove(i);
}
}
You could use option.selected instead of true, but because of the if-statement, you know option.selected will always be true.
jsfiddle

Related

How to change HTML select name based on option value

How can I get option value. I want to change the name="<value>" based on selected option value.
So that I can send name value to the spring controller along with onChange="".
I want to change select name="report/leavereport/weeklysummery" based on option selected value.
<select name="" onChange="document.getReportAll.submit()">
<option value="">Select Report Type</option>
<option value="report">TIME REPORT</option>
<option value="leavereport">LEAVE REPORT</option>
<option value="weeklysummery">TIME SUMMARY</option>
</select>
Thank you,
The shortest change, given that code and modern browsers, would be:
onChange="this.name = this.value; document.getReportAll.submit()"
...since within the attribute event handler, this refers to the select element and modern browsers reflect the option value as value in single-selects.
Set a id to the select.
<select id="select"...>...</select>
Then set the onchange event of the select element. It fires when a option is selected.
If the selector value is undefined, then the browser doesn't support it, so it's possible to get the selected element iterating the options and checking if the attribute selected is included. I'd not use querySelector because older browsers may not support it.
var selector = document.getElementById('select');
selector.onchange = function() {
var value = this.value;
if(!value) {
for(var i = 0, op; op = selector.children[i]; i ++) {
// Check if the attribute selected is valid
if(op.getAttribute('selected')) {
value = op.value;
break;
}
}
}
this.name = value;
};
Here is one possible (unobtrusive) solution using getAttribute and setAttribute.
The script listens for a click on any of the options and then updates the value of the name attribute of select, based on the value of the value attribute of the option.
var options = document.getElementsByTagName('option');
function changeName() {
var value = this.getAttribute('value');
window.alert('name = "' + value + '"');
this.parentNode.setAttribute('name',value);
}
for (var i = 0; i < options.length; i++) {
options[i].addEventListener('click',changeName,false);
}
<select name="">
<option value="">Select Report Type</option>
<option value="report">TIME REPORT</option>
<option value="leavereport">LEAVE REPORT</option>
<option value="weeklysummary">TIME SUMMARY</option>
</select>

How would I validate my Scrolling List with my current code?

So I am trying to create a function that will validate if an option is selected in my Scrolling List. If nothing is selected, and alert will go off, if one is selected, then it passes validation. This is the code I am using:
<select id="topList" name="toppings" size="8" multiple>
<option value="opCream">Whipped Cream</option>
<option value="opFudge">Hot Fudge</option>
<option value="opMarsh">Marshmallow</option>
<option value="opCherry">Cherries</option>
<option value="opChocSprinkles">Chocolate Sprinkles</option>
<option value="opRainSprinkles">Rainbow Sprinkles</option>
<option value="opCheese">Cheesecake</option>
<option value="opOreo">Oreo Crumbles</option>
</select>
function checkScrollList() {
var ddl = document.getElementById("topList");
var selectedValue = ddl.options[ddl.selectedIndex].value;
if (selectedValue == false)
{
alert("Please select a sundae topping.");
}
}
Thanks for the suggestions!
You could use the selectedIndex property of the select object, like this:
function checkScrollList() {
var ddl = document.getElementById("topList");
if (ddl.selectedIndex === -1) {
alert("Please select a sundae topping.");
}
}
The selectedIndex property will give the zero-based index of the first selected option, so it is not useful for actually retrieving all the selected options. But it is guaranteed to be -1 when no options are selected.

Get element with a certain value, make it selected

I have a form with this disabled select element (I have disabled it with jquery)
<select class="select form-control" id="ifacility" name="facility">
<option value="" selected="selected">------</option>
<option value="1">Room 1</option>
<option value="2">Room 1</option>
<option value="3">Room 2</option>
<option value="4">Room 3</option>
</select>
I want to use Jquery to find an option with a name eg Room 2 and make it selected.
$(document).on('click', '.select-option', function() {
var room = $(this).attr('value') //This is what gives the 'Room 2'
//I want to select this room from the options and make it selected
});
You don't really need jQuery for this, so here's a plain-old JavaScript solution.
Declare this function:
function setOptionByValue(select, value){
var options = select.options;
for(var i = 0, len = options.length; i < len; i++){
if(options[i].textContent === value){
select.selectedIndex = i;
return true; //Return so it breaks the loop and also lets you know if the function found an option by that value
}
}
return false; //Just to let you know it didn't find any option with that value.
}
Use it like this:
setOptionByValue(document.getElementById('ifacility'), 'Room 2');
Demo
A jQuery solution using filter():
var room2 = $('#ifacility option').filter(function() {
return $(this).text() == 'Room 2';
});
// room2.val() = '3'
$('#ifacility').val(room2.val());
Fiddle
If you want to user jQuery to accomplish task, try this
$('#ifacility').find('option:contains("Room 2")').prop('selected', true);
It finds option by text and sets its selected attribute.

option is still visible in select after remove()

Hi all I have two select fields, on select field first if user select option value one or two then in select field of second all options are visible but if it select option two in first then option two want to remove from select id second. Following is my code:
<script type="text/javascript">
var index3,str;
</script>
<select id="first" onchange="chk();">
<option value = "one">one</option>
<option value = "two">two</option>
<option value = "three">three</option>
</select>
<select id="second">
<option value = "one">one</option>
<option value = "two">two</option>
<option value = "three">three</option>
</select>
<script type="text/javascript">
function chk()
{
index3 = document.getElementById("first");
str= index3.options[index3.selectedIndex].value;
alert("str:"+str);
if (str=="two")
{
$("#second option[value='two']").remove();
}
else
{
if ( $("#second option[value='two']").length == 0 )
{
$("#second").append('<option value="two">two</option>');
}
}
}
</script>
In fiddle it works fine here, But on mobile problem is: If I select option two from select id second, and then select option value two in first select id, then also option two is visible in second select id, if I click on second select id then only it removes. But in jsFiddle it works perfect. Any suggestion will be appreciated, Thanks in advance.
Here i have done complete bin for above issue. please go through demo link.
Demo http://codebins.com/bin/4ldqp7p
HTML
<select id="first">
<option value = "one">
one
</option>
<option value = "two">
two
</option>
<option value = "three">
three
</option>
</select>
<select id="second">
<option value = "one">
one
</option>
<option value = "two">
two
</option>
<option value = "three">
three
</option>
</select>
jQuery
$(function() {
$("#first").change(function() {
var optVal = $(this).val().trim();
if (optVal == "two") {
$("#second").find("option[value=" + optVal + "]").remove();
} else {
if ($("#second").find("option[value=two]").length <= 0) {
$("<option value=\"two\">two</option>").insertAfter($("#second").find("option[value='one']"));
}
}
});
});
Demo http://codebins.com/bin/4ldqp7p
check this Edit
$('#first').change(function() {
$("#second option[value='" + $(this).val() + "']").remove();
});
Your code looks a bit odd overall. If your intention is to remove the item from 'second' if it is selected in 'first', try this update: http://jsfiddle.net/NWbXt/58/
$(function() {
var first = $('#first'),
second = $('#second'),
removed;
first.change(function() {
var selected = first.val();
second.append(removed); //.. add back old option
removed = second.find('option[value="' + first.val() + '"]').remove();
}).trigger('change');
});​

jQuery show/hide options from one select drop down, when option on other select dropdown is slected

I need to show/hide options on one select drop down dependant on another select drop down options.
The code below shows what I am trying to achieve.
If the 'column_select' select menu option is set to '1 column' then the 'layout_select' select menu must display only the 'none' option.
If the 'column_select' select menu option is set to '2 column' then the 'layout_select' select menu must display only the 'layout 1' and 'layout 2' options.
If the 'column_select' select menu option is set to '3 column' then the 'layout_select' select menu must display only the 'layout 3', 'layout 4' and 'layout 5' options.
<select name="column_select" id="column_select">
<option value="col1">1 column</option>
<option value="col2">2 column</option>
<option value="col3">3 column</option>
</select>
<select name="layout_select" id="layout_select">
<!--Below shows when '1 column' is selected is hidden otherwise-->
<option value="col1">none</option>
<!--Below shows when '2 column' is selected is hidden otherwise-->
<option value="col2_ms">layout 1</option>
<option value="col2_sm">layout 2</option>
<!--Below shows when '3 column' is selected is hidden otherwise-->
<option value="col3_mss">layout 3</option>
<option value="col3_ssm">layout 4</option>
<option value="col3_sms">layout 5</option>
</select>
So far everything I have tried has failed abysmally.... I am new to jQuery. If anybody could please help it would be much appreciated. Thanks!
Try -
$("#column_select").change(function () {
$("#layout_select").children('option').hide();
$("#layout_select").children("option[value^=" + $(this).val() + "]").show()
})
If you were going to use this solution you'd need to hide all of the elements apart from the one with the 'none' value in your document.ready function -
$(document).ready(function() {
$("#layout_select").children('option:gt(0)').hide();
$("#column_select").change(function() {
$("#layout_select").children('option').hide();
$("#layout_select").children("option[value^=" + $(this).val() + "]").show()
})
})
Demo - http://jsfiddle.net/Mxkfr/2
EDIT
I might have got a bit carried away with this, but here's a further example that uses a cache of the original select list options to ensure that the 'layout_select' list is completely reset/cleared (including the 'none' option) after the 'column_select' list is changed -
$(document).ready(function() {
var optarray = $("#layout_select").children('option').map(function() {
return {
"value": this.value,
"option": "<option value='" + this.value + "'>" + this.text + "</option>"
}
})
$("#column_select").change(function() {
$("#layout_select").children('option').remove();
var addoptarr = [];
for (i = 0; i < optarray.length; i++) {
if (optarray[i].value.indexOf($(this).val()) > -1) {
addoptarr.push(optarray[i].option);
}
}
$("#layout_select").html(addoptarr.join(''))
}).change();
})
Demo - http://jsfiddle.net/N7Xpb/1/
How about:
(Updated)
$("#column_select").change(function () {
$("#layout_select")
.find("option")
.show()
.not("option[value*='" + this.value + "']").hide();
$("#layout_select").val(
$("#layout_select").find("option:visible:first").val());
}).change();
(assuming the third option should have a value col3)
Example: http://jsfiddle.net/cL2tt/
Notes:
Use the .change() event to define an event handler that executes when the value of select#column_select changes.
.show() all options in the second select.
.hide() all options in the second select whose value does not contain the value of the selected option in select#column_select, using the attribute contains selector.
And in 2016.....I do this (which works in all browsers and does not create "illegal" html).
For the drop-down select that is to show/hide different values add that value as a data attribute.
<select id="animal">
<option value="1" selected="selected">Dog</option>
<option value="2">Cat</option>
</select>
<select id="name">
<option value=""></option>
<option value="1" data-attribute="1">Rover</option>
<option value="2" selected="selected" data-attribute="1">Lassie</option>
<option value="3" data-attribute="1">Spot</option>
<option value="4" data-attribute="2">Tiger</option>
<option value="5" data-attribute="2">Fluffy</option>
</select>
Then in your jQuery add a change event to the first drop-down select to filter the second drop-down.
$("#animal").change( function() {
filterSelectOptions($("#name"), "data-attribute", $(this).val());
});
And the magic part is this little jQuery utility.
function filterSelectOptions(selectElement, attributeName, attributeValue) {
if (selectElement.data("currentFilter") != attributeValue) {
selectElement.data("currentFilter", attributeValue);
var originalHTML = selectElement.data("originalHTML");
if (originalHTML)
selectElement.html(originalHTML)
else {
var clone = selectElement.clone();
clone.children("option[selected]").removeAttr("selected");
selectElement.data("originalHTML", clone.html());
}
if (attributeValue) {
selectElement.children("option:not([" + attributeName + "='" + attributeValue + "'],:not([" + attributeName + "]))").remove();
}
}
}
This little gem tracks the current filter, if different it restores the original select (all items) and then removes the filtered items. If the filter item is empty we see all items.
A litle late perhaps but I would suggest
$(document).ready(function() {
var layout_select_html = $('#layout_select').html(); //save original dropdown list
$("#column_select").change(function () {
var cur_column_val = $(this).val(); //save the selected value of the first dropdown
$('#layout_select').html(layout_select_html); //set original dropdown list back
$('#layout_select').children('option').each(function(){ //loop through options
if($(this).val().indexOf(cur_column_val)== -1){ //do your conditional and if it should not be in the dropdown list
$(this).remove(); //remove option from list
}
});
});
Initialy both dropdown have same option ,the option you select in firstdropdown is hidden in seconddropdown."value" is custom attribute which is unique.
$(".seconddropdown option" ).each(function() {
if(($(this).attr('value')==$(".firstdropdown option:selected").attr('value') )){
$(this).hide();
$(this).siblings().show();
}
});
// find the first select and bind a click handler
$('#column_select').bind('click', function(){
// retrieve the selected value
var value = $(this).val(),
// build a regular expression that does a head-match
expression = new RegExp('^' + value),
// find the second select
$select = $('#layout_select);
// hide all children (<option>s) of the second select,
// check each element's value agains the regular expression built from the first select's value
// show elements that match the expression
$select.children().hide().filter(function(){
return !!$(this).val().match(expression);
}).show();
});
(this is far from perfect, but should get you there…)

Categories

Resources