Check HTML DropDown option - javascript

I have a HTML dropdown control. I want to check that if the text in it is "Select", it must display error message. I am using following code to do this, but it is not working.
if (document.getElementById("StudentCountry").value == "Select")
{
alert("Please select your country.");
document.getElementById("StudentCountry").focus();
return false;
}

document.GetElementById("StudentCountry").SelectedIndex=0;
or
function getDropDownListvalue()
{
var IndexValue = document.GetElementById("StudentCountry").selectedIndex;
var SelectedVal = document.GetElementById("StudentCountry").options[IndexValue].value;
alert(SelectedVal);
}
check for selected value="select"

var box = document.getElementById("StudentCountry");
if(box.options[box.selectedIndex].text == "Select")

How is this javascript code embedded in your html file? Is it just inside a script element and not in a distinct function? If so, this will probably always return null for the function, as the dropdown is not loaded at the moment it is used. Otherwise the code should work. Just put in a function, let's say checkCountry() and add it as onchange="checkCountry();" to the tag.
The second thing that could break your code is the check for the "Select" text. If you check for value on an option, it will most likely check for the value attribute, such as:
Select
And in this example select is written all lowercase, which would not compare to your ==.
I hope this helps.

Your code seems to be perfect .check onceagain Default options values is "select" or not..
<html>
<head>
<script language="javascript">
function validate(){
alert('ddddddddddd ='+document.getElementById("StudentCountry").value);
if (document.getElementById("StudentCountry").value == "select")
{
alert("Please select your country.");
document.getElementById("StudentCountry").focus();
return false;
}
return false;
}
</script>
</head>
<body>
<select id="StudentCountry">
<option value="select" >---------Please Select ---------</option>
<option value="India" >India</option>
<option value="USA" >UAS</option>
<option value="UK" >UK </option>
</select>
<a onclick="javascript:validate();" href="#">click here to validate</a>

Related

Can't change html select selected value in javascript

I need to change the 'selected' attribute of a html option element within a select object using javascript.
I already tried this: Solution
This is what I have:
.cshtml
<div class="form-group form-group-default" id="divStateEUA">
<label>Estado</label>
<select id="listStateEUA" name="listStateEUA" data-init-plugin="select2" style="width: 100%">
#foreach (var state in ViewBag.EUAStates)
{
<option>#state</option>
}
</select>
</div>
javascript
<script>
$(document)
.ready(function () {
CheckState();
});
function CheckState() {
if (selectedText == 'Estados Unidos') {
var element = document.getElementById('listStateEUA');
element.value = 'Chicago';
}
}
</script>
rendered html:
And still not working. Any ideas?
You are missing value attribute in the option tag of select.
Modify your razor code to have value attribute in option tag, so that you can change the combo-box selection on basis of value :
#foreach (var state in ViewBag.EUAStates)
{
<option value="#state">#state</option>
}
and now in your jquery code, you should be able to do :
function CheckState() {
if (selectedText == 'Estados Unidos') {
$("#listStateEUA").val("Chicago");
}
}
You must provide a value for the options. Your JS is trying to set the select to the "Chicago" value, but none exists. <option>Chicago</option> vs <option value="Chicago">Chicago</option>
function CheckState() {
var element = document.getElementById('listStateEUA');
element.value = 'chicago';
}
CheckState();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Estado</label>
<select id="listStateEUA" name="listStateEUA">
<option value="nevada">nevada</option>
<option value="chicago">chicago</option>
<option value="arizona">arizona</option>
</select>
As Mike McCaughan suggested (thank you very much), since I'm using select2 plugin, it have a different way to get and set values.
$("#select").select2("val"); //get the value
$("#select").select2("val", "CA"); //set the value
Answer found here: select2 plugin get and set values

Set option of the Select box according to JSON result

I actually have some questions but I will start with the main one. I want to set the value of Select box on the basis of JSON.
Here's the HTML in question,
<label class="lbl">Office: </label>
<select tab-index="6" class="required" name="office" class="off">
<option value="">---------</option>
<option value="U">London</option>
<option selected="selected" value="R">Delhi</option>
<option value="W">Lisbon</option>
</select>
JSON sends it like this, I can't show the full JSON since it's too big, but I will show a part, Location: "U".
Here's the JS part:
if (data.Office === "R") {
$('select option[value="Delhi"]').prop('selected', true);
}
if (data.Office === "U") {
console.log('here');
$('.off option[value="London"]').attr('selected', 'selected');
}
if (data.Office === "W") {
$('select option[value="Lisbon"]').prop('selected', true);
}
But it's not working? Can any one point out why?
Moreover, I have a list of managers say and I am also getting that in JSON. So I am doing this,
for (var i = 0; i < data.Managers.length; i++) {
find_input = $('input[name="project_manager[]"').length;
if (find_input != data.Managers.length) {
$('<input type="text" name="project_manager[]" class="" value="" />').appendTo('#managers');
}
console.log(data.Managers[i].Manager);
$('input[name="project_manager[]"').each(function() {
$(this).val(data.Managers[i].Manager);
});
}
No of textboxes depend on the number of managers, but it only sets the value of last item from the array of managers in text boxes that are appended. Why?
Moreover I am not able to set value of textarea in Firefox like this:
$('textarea#some_id').val(data.Description);
It works in Chrome though.
First you need to add the character "<" in the beginning of the 3rd option of the select box:
<option selected="selected" value="R">Delhi</option>
Now, in the JS code, your problem is that you're using the wrong value. Instead of:
$('select option[value="Lisbon"]').prop('selected', true);
You must use:
$('select option[value="W"]').prop('selected', true);
I hope it help.
I think your selectors should be of the form:
$('select option[value="R"]').prop('selected', true);
Note the value is the same as the value in the HTML, not the displayed string (i.e. 'R' instead of 'Delhi').
Also, you should be using prop() consistently for selected flag, as described here by John Resig.

Getting a Select Value after appending

This is for javascript and jquery.
I have in my body...
<select id="option1_select" name="courseCodeSelectName">
<option></option>
<option>Word1</option>
<option>Word2</option>
</select>
<script>
$("select").change(function () {
functionLoadOpt2() }).trigger("change" );
</script>
<select id="option2_select" name="courseNumSelectName">
<option></option>
</select>
<button onclick="changePage()">Load Textbook Page!</button>
As we see above, the web page has 2 select boxes and a button. Depending on what you select in the first select box loads what is in the second one, using the functionLoadOpt2 function locating higher up in my code.
if (result == "Word1") {
$("#option2_select").append('<option>Letter1</option>');
...
There is more but it follows the same code different values.
Result is the following, above the if statement(just a row up),
var result = (document.getElementById('option1_select').value);
now on the button click, the function changePage() runs,
and all I want is ...
var result = (document.getElementById('option1_select').value);
var result2= (document.getElementById('option2_select').value);
Assume they selected and option for both. Result2 doesnt work. I'd imagine because I'm appending it but how would I work around this. So that when I click changePage() I get the selected value of option1_select and option2_select.
functionLoadOpt2:
function functionLoadOpt2(){
var opt1Val = (document.getElementById('option1_select').value);
$("#option2_select").find('option').remove().end().append('<option></option>');
if (opt1Val == "Word1") {
$("#option2_select").append('<option>Letter1</option>');
$("#option2_select").append('<option>Letter2</option>');
$("#option2_select").append('<option>Letter3</option>');
$("#option2_select").append('<option>Letter4</option>');
$("#option2_select").append('<option>Letter5</option>');
}else if (opt1Val == "Word2") {
$("#option2_select").append('<option>Letter3</option>');//they have similar ones in some cases
$("#option2_select").append('<option>Letter6</option>');
$("#option2_select").append('<option>Letter7</option>');
$("#option2_select").append('<option>Letter8</option>');
$("#option2_select").append('<option>Letter9</option>');
$("#option2_select").append('<option>Letter10</option>');
$("#option2_select").append('<option>Letter11</option>');
$("#option2_select").append('<option>Letter12</option>');
$("#option2_select").append('<option>Letter13</option>');
$("#option2_select").append('<option>Letter14</option>');
$("#option2_select").append('<option>Letter15</option>');
$("#option2_select").append('<option>Letter16</option>');
$("#option2_select").append('<option>Letter17</option>');
//this works
}
}
use jQuery to get and set the value of <select> with .val()
Both your select elements have the same id, fix it the it should be fine
<select id="option1_select" name="courseCodeSelectName">
<option></option>
<option>Word1</option>
<option>Word2</option>
</select>
<select id="option2_select" name="courseNumSelectName">
<option></option>
</select>
<button onclick="changePage()">Load Textbook Page!</button>
Demo: Fiddle
Note: You can improve the script a lot by using proper jQuery constructs, like this

Jquery event for option box and typing action

I am doing the jquery event programming for option box for premium box.
For example, i can type on the option box.
So, I type in the option box instead of selecting my select option box.
the following code is the example:
But seems like it is not correct. Is the event is 'change' event ?
My HTML code is as following:
<div id = 'divContent'>
<select id="my_id" style="width: 120px;"
onchange="$('input#my_id').val($(this).find('option:selected').text());"
name="my_id">
<option value="10000">10000</option>
<option value="20000">20000</option>
<option value="30000">30000</option>
<option value="50000">50000</option>
<option value="80000">80000</option>
<option value="100000">100000</option>
</select>
</div>
You need to replace my_id with the id of your select box:
$("#divContent").on('change', "select[id='my_id']", function () {
Will work only when you have a select like:
<select id="my_id">
...
I don't see any elements with the id divContent so change the first line to
$("select[id='my_id']").on('change', function () {
Secondly, even when the code is working, with the example given, there won't be any alerts because none of the if statements will evaluate to true
You have a syntax error here -
if (selectedValue = '') {
alert("Please enter Premium")
}
it should be == not =
if (selectedValue == '') {
alert("Please enter Premium");
}
you can also use -
if(!selectedValue) or if(selectedValue == null)

Enabling and disabling fields

I have a form that has two drop down fields lets say A is one and B is another. I want the drop down box B to be disabled until one of the value in the drop down A is selected .
How should I write a Java script?
Use the onchange event of dropdown A to check it's value and change the disabled property of dropdown B:
document.getElementById("dropdown_A").onchange = function ()
{
if (this.selectedIndex == 2) // if the 3rd option is selected
document.getElementById("dropdown_B").disabled = true;
}
Note this code needs to run after the dropdown A element (or the entire document) has been parsed.
For your dropdown_b, make the disabled property = "disabled"
for your dropdown_a, make the onchange to a function that will change dropdown_b's disabled property.
<html>
<head>
window.onload = function()
{
dda = document.getElementById("dropdown_A");
ddb = document.getElementById("dropdown_b");
dda.onchange = function()
{
if(dda.options[dda.selectedIndex] != "")
ddb.disabled = "";
};
}
</head>
<body>
<select id="dropdown_A">
<option value="" selected="selected"></option>
<option value="asdf">asdf</option>
<option value="12345">12345</option>
</select>
<select id="dropdown_B">
..
</select>
</body>
</html>
Basically, until the user selects an actual option nothing will happen... so the blank option [""] won't deselect the other select.

Categories

Resources