DropDownList Javascript ( Get, Set and Validate DropDownList)
Get Value or Text from Drop Down List using javascript
Inline code
<select id="ddl1" onchange="getValueOrText(this);">
<option value="0">--Select Color--</option>
<option value="1">--Red--</option>
<option value="2">--Green--</option>
<option value="3">--Blue--</option>
</select>
Javascript Function
<script language="javascript" type="text/javascript">
function getValueOrText(obj)
{
alert('Selected Value is : ' + obj.options[obj.selectedIndex].value);
alert('Selected Text is : ' + obj.options[obj.selectedIndex].innerHTML);
}
</script>
Demo :
Set Value to Drop Down List using javscript
Inline code
<select id="ddl2" onchange="getValueOrText(this);">
<option value="0">--Select Color--</option>
<option value="1">--Red--</option>
<option value="2">--Green--</option>
<option value="3">--Blue--</option>
</select>
Enter value: <input type="text" id="txtValue" />
<input id="btnSet" type=button value="Set Value" onclick="return setValue();" />
Javascript function<script language="javascript" type="text/javascript">
function setValue()
{
var v = document.getElementById('txtValue').value;
var l = document.getElementById('ddl2').options.length;
var obj = document.getElementById('ddl2');
var isMatched=false;
for(var i = 0; i < l; i++)
{
if(obj.options[i].value == v)
{
obj.options[i].selected=true;
isMatched=true;
break;
}
}
isMatched==false?alert('value is invalid!.'):'';
return false;
}
</script>
Demo :
Enter value:
Validate Drop Down List using javascript
Inline code
<select id="ddl3" onchange="getValueOrText(this);">
<option value="0">--Select Color--</option>
<option value="1">--Red--</option>
<option value="2">--Green--</option>
<option value="3">--Blue--</option>
</select>
<input type="button" value="Click Me" id="btn" onclick="return DDLvalidate();" />
Javascript function
function DDLvalidate()
{
var obj=document.getElementById('ddl3');
if(obj.options[obj.selectedIndex].value==0)
{
alert('please select color.');
return false;
}else{ alert('valid'); return false; }
}
Demo:
Javascript Email Validation
function checkEmail(obj)
{
var Regex=/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (!Regex.test(obj.value))
alert("Invalid E-mail Address! Please re-enter.")
else
alert("valid email address.")
}
Check out Demo
For Each in Javascript
Javascript dost not have for each feature but there is somthing like this.
Check out this function. It is equevalent foreach.
Javascript function
var array=new Object();
array[0]='Me';
array[1]='You';
var a1='Me'; a2='She'
function checkArr()
{
for(a1 in array)
alert('Yes');
for(a2 is array)
alert('No');
return false;
}
Check out demo here.
Demo :