I have a small project in which I have a select dropdown menu provided by the JQuery UI plugin.The dropdown contains a list of countries and their call code numbers.Is there a way that I show the country name and call code when the select is on focus and show only the call code when its out of focus with selected value.
Here is the code
HTML
<select class="form-control" id="cdropmovil" name="dropmovil"></select>
JavaScript Function
$.getJSON('../../Content/paises.json', function (json) {
var countries = json.countries;
countries.forEach(function (country) {
var opcion = '<option value="'+country.code+'">' + country.name + ' '
+ country.code + '</option>';
$("#cdropmovil").append(opcion);
}, this);
And here is what I tried obviously unsuccesfully...
$("#cdropmovil").on('change', function () {
$(this).text($("#cdropmovil option:selected").val());
})
You can use data-* attribute to store each option tag text value. This way you text value will not get lost if you update your option tag text value on value change.
your $.getJSON(...) will get modified to
$.getJSON('../../Content/paises.json', function (json) {
var countries = json.countries;
countries.forEach(function (country) {
//updated opcion variable
var opcion = '<option data-country-code-name="'+country.name+' '+country.code+'" value="'+country.code+'">' + country.name + ' '+ country.code + '</option>';
$("#cdropmovil").append(opcion);
}, this);
Now you can use data-* attribute value to change text on change() event handler
Here is the modified code
$(document).ready(function(){
$("body").on("focus","select",function(){
$(this).children("option").each(function(){
$(this).text($(this).data("country-code-name"));
});
});
$("body").on("change","select",function(){
var see = $("select option:selected").val();
$("select option:selected").text(see);
//This blur is added to remove focus on value select which was not commented link
$(this).blur();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select name="countries">
<option data-country-code-name="USA 1" value="1">USA 1</option>
<option data-country-code-name="Africa 2" value="2">Africa 2</option>
<option data-country-code-name="Switzerland 3" value="3">Switzerland 3</option>
<option data-country-code-name="Germany 4" value="4">Germany 4</option>
</select>
https://jsfiddle.net/weuydu6e/2/
When you modify the DOM of you select box, you need to re-initialise or refresh your JQuery SelectMenu:
$( "#cdropmovil" ).selectmenu( "refresh" );
This line should be after your forEach.
Reference:
http://api.jqueryui.com/selectmenu/#method-refresh
When you select the element from the UI the text should change automatically in the UI.
If you want to take it from the callback to use somewhere else:
$("#cdropmovil").on('change', function () {
var text = $(this).val();
// Do whatever you want with text
});
Related
I have an array of select boxes, with a unique id like this.
<select class="taskcompleted" id="c392018">
<option value="No">No</option>
<option value="Yes">Yes</option>
</select>
I have a JSON in the format
{"id":"c392018","value":"Yes"}
I am using the following Javascript to set the selected value
$.getJSON('getstatus.php') //place correct script URL
.done(function(response) {
$.each(response, function(key) {
var SelectObj = response[key];
console.log(SelectObj['value']);
jQuery('#' + SelectObj['id']).val(SelectObj['value']).attr('selected', true);
});
});
This is not selecting the value of "Yes". How can I do this?
You simply need to use .val() to set the selected option using the value from your object:
So where you have:
jQuery('#' + SelectObj['id']).val(SelectObj['value']).attr('selected', true);
Should be:
jQuery('#' + SelectObj['id']).val(SelectObj['value']);
See the snippet example below:
Also if you really want the selected property on the item, you should use:
.prop("selected", "selected");
var SelectObj = {"id":"c392018","value":"Yes"};
jQuery('#' + SelectObj['id']).val(SelectObj['value']).prop('selected','selected');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="taskcompleted" id="c392018">
<option value="No">No</option>
<option value="Yes">Yes</option>
</select>
Well, you don't really need jQuery here.
var select = document.getElementById(SelectObj.id);
select.value = SelectObj.value;
When an option is selected that wasn't previously, the onChange handler can detect this. How can a preselected option be detected (i.e., whether a select field has any option selected)? Is this possible without jQuery? Is there a handler, such as onSelected (not the same as onSelect for highlighted text) for this event?
Example:
<select onSelected="FunctionRunIfOptionSelected()">
<option> ... </option>
...
</select>
The preselected option will have been selected on page load. i.e., with the HTML dynamically rendered:
<option selected> ... </option>
If I understand, the task is to tell if an option has the selected attribute hard-coded into the HTML? If so, this should work:
function test () {
var opts = document.getElementById("myselect").options;
var i, len = opts.length;
for(i = 0; i < len; i++) {
if (opts[i].getAttribute("selected" ) != null ) { // opts[i] has the selected attribute
change_other_select(i); // pass the option index to your other function
break;
}
}
}
window.onload = test;
The trick is to distinguish between the selected property and the selected attribute, and also between a null value and an empty string.
var myselect = document.getElementByid('selectid');
myselect.options[myselect.selectedIndex];
To test for selected option on page load, you'll need to catch these in the window.onload handler
One the page is loaded you'll need to continue to use the onChange handler, but use selectedIndex property to test if this is populated with an index within your option list.
Alternatively give your options values in the HTML and check the values themselves. This will allow deterministic behavior when expanding the option list.
Yes, using the .options[] and .selectedIndex methods you can handle this cleanly and unobtrusively like so:
HTML
<select name="select" id="select">
<option value="">...</option>
<option value="1">One</option>
<option value="2" selected="selected">Two</option>
</select>
JavaScript
window.onload = function(){
var select = document.getElementById("select"), selected = select.value;
select.onchange = function(){
var val = select.options[select.selectedIndex].value;
if(val != selected) {
alert("Another value " + val + " was selected, which is not the same as the default value of " + selected);
} else {
alert("Same value as the default of " + selected + " was selected");
}
};
};
From within the JS, you can check and manipulate the val variable as you like.
You can detect if the select field does not have the default value selected like this:
var selects = document.getElementsByTagName("select");
for (i=0;i<selects.length;i++) {
if (selects[i].selectedIndex != 0) {
eval(selects[i].getAttribute("onSelected"));
}
}
I'm trying to get the value of a dropdown on change (and then change the values in a second dropdown).
EDIT: Thanks for all the replies, i've updated to add the () but the code is returning nothing, not null or undefined just a blank alert window
However when I alert it out the attr(value) is undefined.
Any ideas on what i'm missing?
Here is my code:
<script type="text/javascript">
$(document).ready(function() {
var roomID = "0"
$('.dropone').load('ajaxdropdown.aspx');
$('.droptwo').load('ajaxdropdown.aspx?drpType=room&roomid=' + roomID);
$('.dropone').change(function() {
var ts = new Date().getTime();
alert($(this).val)
$(".droptwo").empty();
$(".droptwo").load("ajaxdropdown.aspx?drpType=room&roomid=" + $(this).attr("value") + "&ts=" + ts);
});
});
</script>
val is a method, not a property.
use it like val()
If you are using it many places, i would assign it to a local variable and use it thereafter.
Also you can use the $.now() function to get the unique time stamp. It is equal to DategetTime();
$('.dropone').change(function() {
var item=$(this);
alert(item.val())
$(".droptwo").empty();
$(".droptwo").load("ajaxdropdown.aspx?drpType=room
&roomid=" +item.attr("value") + "&ts=" + $.now());
});
$('.dropone').change(function() {
var val = $(this).val();
// OR
var val = this.value;
})
You must obtain the value using a method, not a property. Use this:
alert($(this).val())
Add round brackets to your val: alert($(this).val())
You can also obtain custom attributes from the dropdown as below;
$('.someclass').change (function () {
var val = this.value;
alert(val); //selected value
var element = $(this).find('option:selected'); // assign selected element
var myTag = element.attr("aTag"); // get attribute by name
alert(myTag);
});
<option name='somename' id='someid' aTag='123' value='XYZ'>XYZ</option>
Check jQuery and Javascript methods here to get Single/ Multiple selected values in the Drop Down
Demo Link
jQuery Method:
Method to get Selected Value from a select box:
HTML
<select id="singleSelectValueDDjQuery" class="form-control">
<option value="0">Select Value 0</option>
<option value="8">Option value 8</option>
<option value="5">Option value 5</option>
<option value="4">Option value 4</option>
</select>
<input type="text" id="textFieldValueJQ" class="form-control"
placeholder="get value on option select">
jQuery
$("#singleSelectValueDDjQuery").on("change",function(){
//Getting Value
var selValue = $("#singleSelectValueDDjQuery").val();
//Setting Value
$("#textFieldValueJQ").val(selValue);
});
Method to get Selected Value Option Text from a select box:
HTML
Select Value 0
Option value 8
Option value 5
Option value 4
<input type="text" id="textFieldTextJQ" class="form-control"
placeholder="get value on option select">
jQuery
$("#singleSelectTextDDjQuery").on("change",function(){
//Getting Value
var selValue = $("#singleSelectTextDDjQuery :selected").text();
//Setting Value
$("#textFieldTextJQ").val(selValue);
});
How can you get the selected value from drop down list using JavaScript? I have tried the following but it does not work.
var sel = document.getElementById('select1');
var sv = sel.options[sel.selectedIndex].value;
alert(sv);
It is working fine with me.
I have the following HTML:
<div>
<select id="select1">
<option value="1">test1</option>
<option value="2" selected="selected">test2</option>
<option value="3">test3</option>
</select>
<br/>
<button onClick="GetSelectedItem('select1');">Get Selected Item</button>
</div>
And the following JavaScript:
function GetSelectedItem(el)
{
var e = document.getElementById(el);
var strSel = "The Value is: " + e.options[e.selectedIndex].value + " and text is: " + e.options[e.selectedIndex].text;
alert(strSel);
}
See that you are using the right id. In case you are using it with ASP.NET, the id changes when rendered.
Direct value should work just fine:
var sv = sel.value;
alert(sv);
The only reason your code might fail is when there is no item selected, then the selectedIndex returns -1 and the code breaks.
Hope it's working for you
function GetSelectedItem()
{
var index = document.getElementById(select1).selectedIndex;
alert("value =" + document.getElementById(select1).value); // show selected value
alert("text =" + document.getElementById(select1).options[index].text); // show selected text
}
Here is a simple example to get the selected value of dropdown in javascript
First we design the UI for dropdown
<div class="col-xs-12">
<select class="form-control" id="language">
<option>---SELECT---</option>
<option>JAVA</option>
<option>C</option>
<option>C++</option>
<option>PERL</option>
</select>
Next we need to write script to get the selected item
<script type="text/javascript">
$(document).ready(function () {
$('#language').change(function () {
var doc = document.getElementById("language");
alert("You selected " + doc.options[doc.selectedIndex].value);
});
});
Now When change the dropdown the selected item will be alert.
I would say change var sv = sel.options[sel.selectedIndex].value;
to var sv = sel.options[sel.selectedIndex].text;
It worked for me. Directing you to where I found my solution
Getting the selected value dropdown jstl
According to Html5 specs you should use --
element.options[e.selectedIndex].text
e.g. if you have select box like below :
<select id="selectbox1">
<option value="1">First</option>
<option value="2" selected="selected">Second</option>
<option value="3">Third</option>
</select>
<br/>
<button onClick="GetItemValue('selectbox1');">Get Item</button>
you can get value using following script :
<script>
function GetItemValue(q) {
var e = document.getElementById(q);
var selValue = e.options[e.selectedIndex].text ;
alert("Selected Value: "+selValue);
}
</script>
Tried and tested.
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…)