I would like to know what the best way would be to loop through a dropdown list in html to see if and item has been selected or not.
I know in C# it would be something along the lines of
int selected = cmbFamily.SelectedIndex;
for (int loop = 0; loop < cmbFamily.Items.Count; loop++)
{
if (selected == -1)
{
MessageBox.Show("please select an item", "Please", MessageBoxButtons.OK, MessageBoxIcon.Error);
break;
}
}
how would I go about in doing this with javascript?
<tr style="font-size:12pt; font-weight:bold; color:#FFFFFF; font-family:High Tower Text;">
<td>Family to join:</td>
<td><select name="drpFamily">
<option/>-select-
<option/>Gambino
<option/>Genovese
<option/>Lucchese
<option/>Colombo
<option/>Bonanno
</select><font color="red">*</font></td>
</tr>
Kind regards
Arian
First off you HTML code is totally wrong. It is not </option>text, it is <option>text</option>
To loop through the options it is as simple as
//var options = document.getElementById("selectId").options;
var options = document.formName.selectName.options;
for(var i=0;i<options.length;i++){
if(options[i].selected){
alert(options[i].value);
}
}
but there is no need to loop through a single select. The easiest way is just to use selected index for a single select.
//var sel = document.getElementById("selectId");
var sel = document.formName.selectName;
var opt = sel.options[sel.selectedIndex];
alert(opt.value);
First: your HTML is wrong.
It should be
<option>-select-
...
or
<option>-select-</option>
...
If you just want the selected value, you can get it via the value attribute of the select element:
var value = document.getElementsByName('drpFamily')[0].value
This only works if there is only one element with name drpFamily. If not, you have to find an appropriate way to select it.
You might want to compare it against the first value (which is selected by default)
if(value !== '-select-')
You could also add a change event listener to the select element:
document.getElementsByName('drpFamily')[0].onchange = function() {
if(this.value !== '-select-') {
//a value other '-select-' than was selected
}
}
Related
I made select tag with html which contain all the names of the countries and I want to search into their values with search bar without any plugins or add-on is that possible ?
Answer
Yes you can, first, see it in action in this demo, if you like what you see, here's how to do it:
HTML
<input type="search" id="searchBox">
<select id="countries">
<option value="arg">Argentina</option>
<option value="usa">United States of America</option>
<option value="som">Somalia</option>
</select>
It's pretty straight forward, a search input and a select with a few options.
JavaScript
searchBox = document.querySelector("#searchBox");
countries = document.querySelector("#countries");
var when = "keyup"; //You can change this to keydown, keypress or change
searchBox.addEventListener("keyup", function (e) {
var text = e.target.value;
var options = countries.options;
for (var i = 0; i < options.length; i++) {
var option = options[i];
var optionText = option.text;
var lowerOptionText = optionText.toLowerCase();
var lowerText = text.toLowerCase();
var regex = new RegExp("^" + text, "i");
var match = optionText.match(regex);
var contains = lowerOptionText.indexOf(lowerText) != -1;
if (match || contains) {
option.selected = true;
return;
}
searchBox.selectedIndex = 0;
}
});
Explanation
First, the variables:
searchBox : link to the HTMLElement search input.
countries : link to the HTMLElement select.
when : event type, I used "keyup" and that means the select will update when you press and lift a key in the searchBox.
text, lowerText : The value of the searchBox (in other words, the input text). The second one equals the first but lowercased for case insensitive testing.
options : The select options objects.
optionText, lowerOptionText : The text of the option object (ej. "Argentina") and the other one is the lower version for case insensitive testing (ej. "argentina")
regex : It's a RegExp Object, a regular expression, basically what it does is it tests (case insensitive, because of the 'i' in the second parameter) wether the some string begins with some value, in this case, the value would be the input text.
match : It executes the RegExp Object agains the option's text, that means it will test if the inputted text is the same as the beggining of the option's text.
contains : It checks if the option's text contains the inputted text.
Few, that was a lot, so, why do we need 2 tests? Because there are two possibilities for selection with searchBox, one is that when you start typing "Unit.." it should match "United States of America"(regexp), and the other one is that you just type "america" and it should also match "United States of America"(contains)
So, it checks for both tests, and if either one is true it will select that option. (It will also return so that it doesn't continue executing code)
By default, if no test is true, it will select the first element of the select.
Hope that helps :)
If you must not use a plugin or third party script, you could create an array to populate the options and the search through the array using inarray http://api.jquery.com/jquery.inarray/ you would then need to have a method to select the result and use iterator value to tie it back to the corresponding select option.
Also there is this post: Search the options of a select, find the value, add selected to it and write it's html text on a div
Thank you #undefined
In your code instead of making it selected i want to disabled it like display none.
But display: none not working in IE11
What I did is disabled the un matched options and the hide them.
After this I have sorted the options to show only enabled options on top.
The code I have written is pasted below - please try to understand the logic I hope it will work
to disabled the options use
$("#addselect option")attr('disabled', 'disabled').hide
and to again enable it use
$("#addselect option").removeAttr('disabled').show();
sort by disabled options.
$("#addselect option").each(function (i, val) {
if ($(this)[i].disabled) {
moveDown("selectId");
}
else {
moveUp("selectId");
}
}
function moveUp(selectId) {
var selectList = document.getElementById(selectId);
var selectOptions = selectList.getElementsByTagName('option');
for (var i = 1; i < selectOptions.length; i++) {
var opt = selectOptions[i];
if (!opt.disabled) {
selectList.removeChild(opt);
selectList.insertBefore(opt, selectOptions[i - 1]);
}
}
}
function moveDown(selectId) {
var selectList = document.getElementById(selectId);
var selectOptions = selectList.getElementsByTagName('option');
for (var i = selectOptions.length - 2; i >= 0; i--) {
var opt = selectOptions[i];
if (opt.disabled) {
var nextOpt = selectOptions[i + 1];
opt = selectList.removeChild(opt);
nextOpt = selectList.replaceChild(opt, nextOpt);
selectList.insertBefore(nextOpt, opt);
}
}
}
I am not sure if I confused everyone with the above title. My problem is as follows.
I am using standard javascript (no jQuery) and HTML for my code. The requirement is that for the <select>...</select> menu, I have a dynamic list of varying length.
Now if the length of the option[selectedIndex].text > 43 characters, I want to change the option[selectecIndex] to a new text.
I am able to do this by calling
this.options[this.selectedIndex].text = "changed text";
in the onChange event which works fine. The issue here is once the user decides to change the selection, the dropdownlist is showing the pervious-selected-text with changed text. This needs to show the original list.
I am stumped! is there a simpler way to do this?
Any help would be great.
Thanks
You can store previous text value in some data attribute and use it to reset text back when necessary:
document.getElementById('test').onchange = function() {
var option = this.options[this.selectedIndex];
option.setAttribute('data-text', option.text);
option.text = "changed text";
// Reset texts for all other options but current
for (var i = this.options.length; i--; ) {
if (i == this.selectedIndex) continue;
var text = this.options[i].getAttribute('data-text');
if (text) this.options[i].text = text;
}
};
http://jsfiddle.net/kb7CW/
You can do it pretty simply with jquery. Here is a working fiddle: http://jsfiddle.net/kb7CW/1/
Here is the script for it also:
//check if the changed text option exists, if so, hide it
$("select").on('click', function(){
if($('option#changed').length > 0)
{
$("#changed").hide()
}
});
//bind on change
$("select").on('change', function(){
var val = $(":selected").val(); //get the value of the selected item
var text = $(':selected').html(); //get the text inside the option tag
$(":selected").removeAttr('selected'); //remove the selected item from the selectedIndex
if($("#changed").length <1) //if the changed option doesn't exist, create a new option with the text you want it to have (perhaps substring 43 would be right
$(this).append('<option id="changed" value =' + val + ' selected="selected">Changed Text</option>');
else
$('#changed').val(val) //if it already exists, change its value
$(this).prop('selectedIndex', $("#changed").prop('index')); //set the changed text option to selected;
});
I have an ASP.NET web page with a databound RadioButtonList. I do not know how many radio buttons will be rendered at design time. I need to determine the SelectedValue on the client via JavaScript. I've tried the following without much luck:
var reasonCode = document.getElementById("RadioButtonList1");
var answer = reasonCode.SelectedValue;
("answer" is being returned as "undefined")
Please forgive my JavaScript ignorance, but what am I doing wrong?
Thanks in advance.
ASP.NET renders a table and a bunch of other mark-up around the actual radio inputs. The following should work:-
var list = document.getElementById("radios"); //Client ID of the radiolist
var inputs = list.getElementsByTagName("input");
var selected;
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
selected = inputs[i];
break;
}
}
if (selected) {
alert(selected.value);
}
Try this to get the selected value from the RadioButtonList.
var selectedvalue = $('#<%= yourRadioButtonList.ClientID %> input:checked').val()
I always View Source. You will find each radio button item to have a unique id you can work with and iterate through them to figure out which one is Checked.
Edit: found an example. I have a radio button list rbSearch. This is in an ascx called ReportFilter. In View Source I see
ReportFilter1_rbSearch_0
ReportFilter1_rbSearch_1
ReportFilter1_rbSearch_2
So you can either loop through document.getElementById("ReportFilter1_rbSearch_" + idx ) or have a switch statement, and see which one has .checked = true.
RadioButtonList is an ASP.NET server control. This renders HTML to the browser that includes the radio button you are trying to manipulate using JavaScript.
I'd recommend using something like the IE Developer Toolbar (if you prefer Internet Explorer) or Firebug (if you prefer FireFox) to inspect the HTML output and find the ID of the radio button you want to manipulate in JavaScript.
Then you can use document.getElementByID("radioButtonID").checked from JavaScript to find out whether the radio button is selected or not.
The HTML equivalent to ASP.NET RadioButtonList, is a set of <input type="radio"> with the same name attribute(based on ID property of the RadioButtonList).
You can access this group of radio buttons using getElementsByName.
This is a collection of radio buttons, accessed through their index.
alert( document.getElementsByName('RadioButtonList1') [0].checked );
function CheckRadioListSelectedItem(name) {
var radioButtons = document.getElementsByName(name);
var Cells = radioButtons[0].cells.length;
for (var x = 0; x < Cells; x++) {
if (document.getElementsByName(name + '_' + x)[0].checked) {
return x;
}
}
return -1;
}
For a 'RadioButtonList with only 2 values 'yes' and 'no', I have done this:
var chkval=document.getElemenById("rdnPosition_0")
Here rdnposition_0 refers to the id of the yes ListItem. I got it by viewing the source code of the form.
Then I did chkval.checked to know if the value 'Yes' is checked.
I would like to add the most straightforward solution to this problem:
var reasons= document.getElementsByName("<%=RadioButtonList1.UniqueID%>");
var answer;
for (var j = 0; j < reasons.length; j++) {
if (reason[j].checked) {
answer = reason[j].value;
}
}
UniqueID is the property that gave you the name of the inputs inside the control, so you can just check them really easily.
I've tried various ways of determining a RadioButtonList's SelectedValue in Javascript with no joy. Then I looked at the web page's HTML and realised that ASP.NET renders a RadioButtonList control to a web page as a single-column HTML table!
<table id="rdolst" border="0">
<tr>
<td><input id="rdolst_0" type="radio" name="rdolst" value="Option 1" /><label for="rdolst_0">Option 1</label></td>
</tr>
<tr>
<td><input id="rdolst_1" type="radio" name="rdolst" value="Option 2" /><label for="rdolst_1">Option 2</label></td>
</tr>
</table>
To access an individual ListItem on the RadioButtonList through Javascript, you need to reference it within the cell's child controls (known as nodes in Javascript) on the relevant row. Each ListItem is rendered as the first (zero) element in the first (zero) cell on its row.
This example loops through the RadioButtonList to display the SelectedValue:
var pos, rdolst;
for (pos = 0; pos < rdolst.rows.length; pos++) {
if (rdolst.rows[pos].cells[0].childNodes[0].checked) {
alert(rdolst.rows[pos].cells[0].childNodes[0].value);
//^ Returns value of selected RadioButton
}
}
To select the last item in the RadioButtonList, you would do this:
rdolst.rows[rdolst.rows.length - 1].cells[0].childNodes[0].checked = true;
So interacting with a RadioButtonList in Javascript is very much like working with a regular table. Like I say I've tried most of the other solutions out there but this is the only one which works for me.
I wanted to execute the ShowShouldWait script only if the Page_ClientValidate was true. At the end of the script, the value of b is returned to prevent the postback event in the case it is not valid.
In case anyone is curious, the ShouldShowWait call is used to only show the "please wait" div if the output type selected is "HTML" and not "CSV".
onclientclick="var isGood = Page_ClientValidate('vgTrxByCustomerNumber');if(isGood){ShouldShowWait('optTrxByCustomer');} return isGood"
To check the selected index of drop down in JavaScript:
function SaveQuestion() {
var ddlQues = document.getElementById("<%= ddlQuestion.ClientID %>");
var ddlSubQues = document.getElementById("<%=ddlSecondaryQuestion.ClientID%>");
if (ddlQues.value != "" && ddlSubQues.value != "") {
if (ddlQues.options[ddlQues.selectedIndex].index != 0 ||
ddlSubQues.options[ddlSubQues.selectedIndex].index != 0) {
return true;
} else {
return false;
}
} else {
alert("Please select the Question or Sub Question.");
return false;
}
}
reasonCode.options[reasonCode.selectedIndex].value
From here:
if (RadioButtonList1.SelectedIndex > -1)
{
Label1.Text = "You selected: " + RadioButtonList1.SelectedItem.Text;
}
i have a drop down menu, on clicking any item from the list i want to get the previously selected item. Is it possible using javascript?
You mean
<script>
var selHistory =[];
var sel;
window.onload=function() {
sel = document.getElementById('selID');
sel.onchange=function() {
selHistory[selHistory.length]=sel.selectedIndex;
}
sel.onchange(); // save the current option
}
function getPrev() {
return (selHistory.length < 1) ? "no previous":sel.options[selHistory[selHistory.length-2]].value
}
</script>
or perhaps
<select onChange="var prevSel=(this.selectedIndex>0) ? this.options[this.selectedIndex-1].value:'nothing previous'">
You can just save selected item into some var and read from it when next item will be selected.
I have an .aspx hidden control that stores a defaultId for this dropdown. However, the values in the dropdown can change and sometime the defaultId is listed as one of the selections, other times it isn't. When the drop down clears we run this to reset it:
Global.getComponent("ddlVehicleType").setValue(Global.getComponent("DefaultVehicleTypeId").getValue());
Now when it sets that, if the dropdown doesn't have a value associated with that Id, it displays the actual Id in the field. I have a check for isNumeric now to see when that happens, but how do I make the field display the first value in the list of Id's it DOES have:
var displayedValue = Global.getComponent("ddlVehicleType").getRawValue();
if (IsNumeric(displayedValue)) {
}
Put together a unique little way of doing it, by going through the current populated store of that dropdown on the page:
var newId = 0;
var firstId = 0;
var typeStore = Global.getComponent("ddlVehicleType").getStore();
firstId = typeStore.getAt(0).get('LookupID');
typeStore.each(function(rec) {
if (rec.get('LookupID') == Global.getComponent("DefaultVehicleTypeId").getValue())
{
newId = Global.getComponent("DefaultVehicleTypeId").getValue();
}
});
if (newId != 0) {
Global.getComponent("ddlVehicleType").setValue(newId);
} else {
Global.getComponent("ddlVehicleType").setValue(firstId);
}