Cannot properly get the value of a dropdown - javascript

I have a dropdown list and a javascript function which disables other fields when a certain value from the dropdown list is selected.
Javascript Code
function maritalStatusChange()
{
var dropdown = document.getElementById("maritalstatus").value;
if(dropdown == 'Single')
{
document.getElementById("spousefld").disabled = true;
document.getElementById("spouse_occupation").disabled = true;
document.getElementById("address3").disabled = true;
document.getElementById("children_no").disabled = true;
document.getElementById("spousefld").value = "";
document.getElementById("spouse_occupation").value = "";
document.getElementById("address3").value = "";
document.getElementById("children_no").value= "None";
}
if(dropdown == 'Married')
{
document.getElementById("spousefld").disabled = false;
document.getElementById("spouse_occupation").disabled= false;
document.getElementById("address3").disabled = false;
document.getElementById("children_no").disabled = false;
document.getElementById("maritalstatus").value= 'Married';
}
if(dropdown == 'Separated')
{
document.getElementById("spousefld").disabled = false;
document.getElementById("spouse_occupation").disabled= false;
document.getElementById("address3").disabled = false;
document.getElementById("children_no").disabled = false;
}
if(dropdown == 'Widowed')
{
document.getElementById("spousefld").disabled = false;
document.getElementById("spouse_occupation").disabled= false;
document.getElementById("address3").disabled = false;
document.getElementById("children_no").disabled = false;
}
}
Here is the HTML code of the dropdown list and where I call the javascript function.
<select name="maritalstatus" id="maritalstatus" onchange="maritalStatusChange();">
<option>---------------</option>
<option value='Single'>Single</option>
<option value='Married'>Married</option>
<option value='Separated'>Separated</option>
<option value='Widowed'>Widowed</option>
</select><font color="red">*</font>
Right now, the only thing that works is when I select the "Single" option however, it does not seem to get proper selected value for the rest of the options. Can anyone tell me what I did wrong?
Thanks!

Try This:
var dropdown = document.getElementById("maritalstatus").options[document.getElementById("maritalstatus").selectedIndex].value;

You should try "selectedIndex":
document.getElementById("maritalstatus").selectedIndex;

The above code works fine. You can see it at: http://jsfiddle.net/WmHCs/
What is the actual error? Maybe some other part of the code?

Try Below code
var eve = document.getElementById("maritalstatus");
var data = eve.options[eve.selectedIndex].value;

You are using single quotas in HTML. Switch them to double quotas. All values for options are assigned with those single quotas. This is what you are actually comparing: ("'Single'"=="Single") => false.
EDIT
If this code is supposed to add the selection in your db, check if-blocks other than Single. In case Single you set some values, but other blocks are making some disablings only.

You just need to get value from element by id and then alert the value.
Create a function and call it on change. it works in many of values dynamically generated, no limitaion of entries in dropdown.
<select name="maritalstatus" id="maritalstatus" onchange="maritalStatusChange();">
function maritalStatusChange()
{
var getValue = document.getElementById("maritalstatus").value;
alert(getValue);
}

Related

Using Javascript to select a value from a Html Select box

Hey guys I am using JavaScript to select a specific value(option) from the html select form tag, but whenever I call my JavaScript function I get a single message repeating for all the choices I want to select.
Ex: If I choose to select 'Rabbit' from the list of options and then display a message saying 'Rabbit chosen'; the message will display for each option/value selected.
Here is my JavaScript Code:
var element = document.getElementById('choices').value;
function SelectElement() {
if (element = 'Rabbit') {
alert("Rabbit Selected");
}
else if (element = 'Wall') {
alert("Wall Selected");
}
else if (element = 'Arrow') {
alert("Arrow Selected");
}
}
Here is my html code:
<form>
<select id="choices" >
<option>Rabbit</option>
<option>Wall</option>
<option>Arrow</option>
</select>
<input type="button" value="Submit" onclick="SelectElement()"/>
</form>
Can you smart guys please help me????
A. You should fetch the value each time before calling the function and then check it otherwise your element variable won't refresh at all.
B. To compare two values you should use ==, = is an assignment operator.
function SelectElement() {
var element = document.getElementById('choices').value;
if (element == 'Rabbit') {
alert("Rabbit Selected");
}
}
(As your question is not much clear) if you just want to alert the selected value for every option clicked, just do:
function SelectElement() {
var element = document.getElementById('choices').value;
alert(element+" Selected");
}
This is basic string concatenation.
There is a something called selected == true or false in a "select" tag.
You could write in HTML :
<form>
<select id="choices">
<option id="Rabbit">Rabbit</option>
<option id="Wall">Wall</option>
<option id="Arrow">Arrow</option>
</select>
</form>
<button onclick="TakeElement()">Click</button>
You could write in javascript:
var ra = document.getElementById('Rabbit');
var wa = document.getElementById('Wall');
var ar = document.getElementById('Arrow');
function TakeElement() {
if (ra.selected == true) {
alert("Rabbit is selected");
}
if (wa.selected == true) {
alert("Wall is selected");
}
if (ar.selected == true) {
alert("Arrow is selected");
}
}
I think you must replace element ='rabbit' with element =='rabbit'
== is comparison operator
and = is assignment operator

Return false if no value is selected (other than heading) from select box

I have a HTML form having select box. On selection of first drop down, next drop down should be auto filled using AJAX.
On Download Records (id="getCsv") button click event a CSV file is generated. Problem is, I want to make all the fields mandatory. Here is the jquery code
var teacher_name = $("#sel_teacher option:selected").text();
var unittest_name = $("#sel_test1 option:selected").text();
var class_name = $("#sel_class1 option:selected").text();
var class_id = $('#sel_class1').val();
var division_name = $("#sel_div1 option:selected").text();
var division_id = $('#sel_div1').val();
var subject_name = $("#sel_sub1 option:selected").text();
if (teacher_name == "") {
alert('Please Select Teacher Name.');
return false;
} else if(class_name == "") {
alert('Please Select Class Name.');
return false;
} else if(division_name == "") {
alert('Please Select Division Name.');
return false;
} else if(subject_name == "") {
alert('Please Select Subject Name.');
return false;
} else if(unittest_name == "") {
alert('Please Select Unit Test Name.');
return false;
} else {
var myObject = new Object();
myObject.class_name = class_name;
myObject.class_id = class_id;
myObject.division_name = division_name;
myObject.division_id = division_id;
myObject.subject_name = subject_name;
myObject.test_name = unittest_name;
var formData = JSON.stringify(myObject);
$('#getCsv').attr('href','csv_generator.php?data=' + formData);
}
The problem is that when I click Download Records, even though the first select box is empty directly alert box for second select box pops up. I tried to solve this problem using the below, but no luck.
if ($("#sel_teacher").attr("selectedIndex") == 0) {
alert("You haven't selected anything!");
return false;
}
Can anybody please help me with this? Any help is appreciated.
selectedIndex is a property, use prop:
$("#sel_teacher").prop("selectedIndex")
Also, you can simplify your code by retrieving the selected value using just $("#sel_teacher").val() and compare to empty string (assuming the value of that option is empty).
var teacher_name = $("#sel_teacher").val();
// get other <select /> values here...
if (teacher_name == '') {
alert("You haven't selected anything!");
return false;
}
// test other values here...
It might be because of the default value that you have given for the first text-box.Just change the value to "" onclick or on blur on that text-box.
Or you can simply handle this matter via HTML5 attribute required and adding onchange() Event Listener .
<select name="sel_teacher" onchange="get_value();" id="sel_teacher" required>
<option>--Select Teacher Name--</option>
</select>
<script>
function get_value() {
var teacher_name = $("#sel_teacher").val();
// get other <select /> values here...
if (teacher_name == '') {
alert("You haven't selected anything!");
return false;
} else {
// write code when teacher_name is selected
}
}
</script>

Getting the ID of a radio button using JavaScript

Is there a way to get the ID of a radio button using JavaScript?
So far I have:
HTML
<input type="radio" name="fullorfirst" id="fullname" />
JavaScript
var checkID = document.getElementById(fullname);
console.log(checkID);
It outputs as null.
Essentially what I want to do is:
document.getElementById(fullname).checked = true;
...in order to change the radio button fullname to be checked on page load.
you should put fullname between quotes, since it's a string:
document.getElementById("fullname");
function checkValue() // if you pass the form, checkValue(form)
{
var form = document.getElementById('fullname'); // if you passed the form, you wouldn't need this line.
for(var i = 0; i < form.buztype.length; i++)
{
if(form.buztype[i].checked)
{
var selectedValue = form.buztype[i].value;
}
}
alert(selectedValue);
return false;
}
Hope this helps.
JavaScript Solution:
document.getElementById("fullname").checked = true;
Jquery Solution:
$("#fullname").prop("checked", true);

How to check drop-down values using JavaScript

I have drop-down and Textbox inside a Gridview so I want to check the followings on a button click:
(1) Check if NOTHING is selected from the drop down first (the drop-down options are either YES, NO or NA) . If nothing is selected, I want to show message that reads like this “Please make selection from the drop-down”
(2) If the selection from the drop-down is NO and the Textbox is blank or empty then I want to show message that says: “Please provide comments”
The first code checks if the text-box is blank and it works and the 2nd code checks if no selection is made from the drop down and that one works fine too so how can i combine between those 2 codes? I want to execute both codes on button click, right now it is only calling the first code. please help. Thanks.
here is my code that checks if the textbox is blank:
<script type ="text/javascript">
function Validate() {
var flag = false;
var gridView = document.getElementById('<%= GridView1.ClientID %>');
for (var i = 1; i < gridView.rows.length; i++) {
var selects = gridView.rows[i].getElementsByTagName('select');
var areas = gridView.rows[i].getElementsByTagName('textarea');
if (selects != null && areas != null) {
if (areas[0].type == "textarea") {
var txtval = areas[0].value;
var selectval = selects[0].value;
if (selectval == "No" && (txtval == "" || txtval == null)) {
flag = false;
break;
}
else {
flag = true;
document.getElementById('<%=btnSubmit.ClientID%>').style.visibility = 'visible';
}
}
}
}
if (!flag) {
alert('Please note that comments are required if you select "No" from the dropdown box. Thanks');
document.getElementById('<%=btnSubmit.ClientID%>').style.visibility = 'hidden';
}
return flag;
}
</script>
and here is the code that checks the drop-down
<script type="text/javascript">
function validate_DD() {
var flag = true;
var dropdowns = new Array(); //Create array to hold all the dropdown lists.
var gridview = document.getElementById('<%=GridView1.ClientID%>'); //GridView1 is the id of ur gridview.
dropdowns = gridview.getElementsByTagName('Select'); //Get all dropdown lists contained in GridView1.
for (var i = 0; i < dropdowns.length; i++) {
if (dropdowns.item(i).value == 'Select') //If dropdown has no selected value
{
flag = false;
break; //break the loop as there is no need to check further.
}
}
if (!flag) {
alert('Please select either Yes, No or NA in each dropdown and click the Save button again. Thanks');
document.getElementById('<%=btnSubmit.ClientID%>').style.visibility = 'hidden';
}
return flag;
}
</script>
Try this:
<select id="ddlCars">
<option value="1">Honda</option>
<option value="2" selected="selected">Toyota</option>
<option value="3">BMW</option>
</select>
Accessing dropdown:
To get the value:
var el = document.getElementById("ddlCars");
var val = el.options[el.selectedIndex].value; // val will be 2
To get the text:
var el = document.getElementById("ddlCars");
var car = el.options[el.selectedIndex].text; //car will be Toyota

Multiple select validation

I have a form in HTML, that has several select elements, what is the best way to make validation for them in such way that no two select elements can have same value, validation function should fire on select, so it can check are there any selects with the same option value if yes then alert something, can I get a explanation how to write this in javascript?
Thank you
here is a bit of HTML code I want to validate :
<form name="forma" action="" method="POST">
<select name="sel1">
<option>Please select</option>
<option>brand1</option>
<option>brand2</option>
<option>brand3</option>
</select>
<select name="sel2">
<option>Please select</option>
<option>brand1</option>
<option>brand2</option>
<option>brand3</option>
</select>
<select name="sel3">
<option>Please select</option>
<option>brand1</option>
<option>brand2</option>
<option>brand3</option>
</select>
</form>
Here is the solution slightly adjusted but this is it:
var selectTest = function () {
var i, j;
sels = [document.getElementById("sel1"), document.getElementById("sel2"), document.getElementById("sel3")];
for (i = 0; i < sels.length; i += 1) {
for (j = i + 1; j < sels.length; j += 1) {
if(sels[i].value != "Please select")
{
if (sels[i].value === sels[j].value) {
alert("Selected values must be different");
return;
}
}
}
}
};
Special tnx to austin cheney, thanks to everyone who posted and participated.
First, don't use the name attribute as a reference point for script. Name refers to an array of named elements in the DOM, which is typically useless in the global DOM outside of form controls. When using the name array it is difficult to tell child nodes apart from child nodes of a same named element. Use the id attribute for use with script, which is a unique identifier instead.
var selTest = function () {
var i, j, error = document.getElementById("error"),
sels = [document.getElementById("sel1"), document.getElementById("sel2"), sel3 = document.getElementById("sel3")];
for (i = 0; i < sels.length; i += 1) {
for (j = i + 1; j < sels.length; j += 1) {
if (sels[i].value === sels[j].value) {
error.display = "block";
sels[i].backgroundColor = "#f00";
sels[j].backgroundColor = "#f00";
return false;
}
}
}
};
EDIT: changed return; to return false; for use with an onsubmit event.
Simply add the id attribute value of the select lists to the "sels" array in the code above. The above code will make a hidden element with an id of "error" appear if the test results in a true condition. It will also change the background color of the offended select lists to red.
I would generally recommend using jQuery for this as it simplifies it quite a bit. You'd want to do something along these lines.
function hasDuplicates() {
var dupe = false;
$("select option:selected").each(function(i) {
var id = $(this).parent().attr("id");
var value = $(this).attr("value");
$("select option:selected").each(function(c) {
if ($(this).parent().attr("id") != id && $(this).attr("value") == value) {
alert("Duplicate");
dupe = true;
return false;
}
});
if (dupe) {
return false;
}
});
return dupe;
}
This will cycle through all the select boxes on the page and compare each one to every other one. If there's a duplicate value it will popup an alert and return true.
For it to fire when a change to a select box is made you'd want to add onchange events to each as shown below. Each select will need a unique id to be set, although you could change the calls to attr("id") to attr("name") if you don't want to add ID's.
<select onchange="hasDuplicates()">...
Performance wise it may make sense to store the values in an array, as this solution hits the DOM quite a lot by having a nested loop.
Give onchange="validate('1')" onchange="validate('2')" onchange="validate('3')" for each selecte statement.
function validate(x){
if(x==1)
{
var selectedvalue=document.forma.sel1.options[document.forma.sel1.selectedIndex].value
if(selectedvalue==document.forma.sel2.options[document.forma.sel2.selectedIndex].value ||
selectedvalue==document.forma.sel3.options[document.forma.sel3.selectedIndex].value)
alert("No two values cannot be same");
}
esle if(x==2)
{
var selectedvalue=document.forma.sel2.options[document.forma.sel2.selectedIndex].value
if(selectedvalue==document.forma.sel1.options[document.forma.sel1.selectedIndex].value ||
selectedvalue==document.forma.sel3.options[document.forma.sel3.selectedIndex].value)
alert("No two values cannot be same");
}
else if(x==3)
{
var selectedvalue=document.forma.sel3.options[document.forma.sel3.selectedIndex].value
if(selectedvalue==document.forma.sel1.options[document.forma.sel1.selectedIndex].value ||
selectedvalue==document.forma.sel1.options[document.forma.sel1.selectedIndex].value)
alert("No two values cannot be same");
}
}

Categories

Resources