Why won't it recognize an invalid selection from my dropdown menu? - javascript

I'm trying to display a message to the user if they decide not to choose an item from the dropdown menu using strictly vanilla JS. Instead, I get an error in the console that says cannot read property 'selectedIndex' of null. I cannot see what I'm doing wrong.
How can I rectify this problem?
Here's HTML:
<form>
<div>
<label>Drop Down Menu
<select name="menu">
<option value="">---</option>
<option value="item1">Item 1</option>
<option value="item2">Item 2</option>
</select>
</label>
</div>
</form>
Here's JS:
var myForm = document.getElementsByTagName("form");
myForm.id = "the-form";
var submitButton = document.getElementsByTagName("button")[1];
submitButton.id = "submit-button";
function formValidation() {
var select = document.getElementsByTagName("select");
select.id = "myMenu";
var selectId = document.getElementById("myMenu");
if(selectId.selectedIndex <= 0) {
console.log("a menu item must be selected!");
}
alert("Chosen!");
}
submitButton.onclick = myForm.onsubmit = function() {
formValidation();
};

You are targeting a DOM node by the id of "myMenu" here:
var selectId = document.getElementById("myMenu");
while the select you want to target has id "menu". Therefore, you have to change either the id in the JS selection or the select's id in the html.

Related

Change var value from dropdown in javascript with onchange

I have a dropdown list which looks like this:
<select id="cityID">
<option value="mission">Mission</option>
<option value="bakersfield">Bakersfield</option>
<option value="knoxville">Knoxville</option>
</select>
And my code to get the value is:
var select = document.getElementById('cityID');
var text = select.options[select.selectedIndex].text;
text.innerHTML = cityID.value;
text.onchange = function(e) {
text.innerHTML = e.target.value;
}
The value always chooses the first item. How can I get it to accept the cityID and change the page,
I'm sure its a formatting or typo or wrong value ?
onchange event is trigger from the select element
your text variable seems to be an HTML element because you set its innerHTML property
a select element has a "value" property so you don't need to get it from the selectedIndex of the options.
var select = document.getElementById('cityID');
var textEl = document.getElementById("text")
text.innerHTML = select.value;
select.onchange = function(e) {
textEl.innerHTML = e.target.value;
}
<select id="cityID">
<option value="mission">Mission</option>
<option value="bakersfield">Bakersfield</option>
<option value="knoxville">Knoxville</option>
</select>
<p id="text"></p>
You could achieve this using addEventListener also.
var select = document.getElementById('cityID');
var textEl = document.getElementById("text")
select.addEventListener("change", (e) => {
textEl.innerText = e.target.value;
})

dynamically add buttons to a division in html css

I am trying to add buttons dynamically to a division when a combobox item is clicked and I want to use the onclick() function rather than onchange() function
Here is my HTML code :
<div class = "row" id = "activityRow">
<select class="combobox" id = "activityCombobox" onclick="addButtons()">
<option value="" selected="true" style = "display:none;">-- Choose your Activity --</option>
<option value="val1" >Val1</option>
<option value="val2">Val2</option>
<option value="val3">Val3</option>
<option value="val4">Val4</option>
</select>
</div>
<div class="row" id = "addonRow">
</div>
Jaavascript Code:
var list = [];
function addButtons() {
var e = document.getElementById("activityCombobox");
var sel = e.options[e.selectedIndex].text;
var buttonName = " ";
buttonName += sel;
list.push(sel);
var funcName = sel;
if(sel == "Val4")
funcName = "Places";
jQuery('#addonRow').append('<button type = "button" id = "addonButton'+funcName+'"><i class="glyphicon glyphicon-remove-sign" onclick = "removeButtons'+funcName+'()"></i>'+buttonName+'</button>');
}
This code works fine in Chrome. But when I run it in mozilla, one button is added every time I click the combobox for dropdown and another button for the selected value. So basically two buttons are added whenever I try to add one button.
I want a way to add buttons using onclick() not onchange().

Javascript to populate an option box with an array

Hi was wondering if you could help, i need to use JavaScript to populate the clothes option box with appropriate options when the user specifies what type of gender they are. This is the code I have so far,
<script type="text/javascript">
var subListArray = [];
subListArray[0] = 'Select a type first';
subListArray[1] = ['skirt', 'dress', 'tights'];
subListArray[2] = ['jeans', 'hat'];
</script>
Person
Gender Type: <select name="genderType" id="genderType" >
<option value="">Gender Type?</option>
<option value="girl">Female</option>
<option value="boy">Male</option>
</select> </br>
Clothes <select name="clothType">
<option value="">Choose a Type</option>
</select>
Use objects instead of arrays so that you can map the subList to the selected gender. You don't have to do this, but it simplifies things a bit. Add a "change" listener to the gender selector that creates the option elements for the new select box:
var subListArray = {
'default': ['Select a type first'],
'girl': ['skirt', 'dress', 'tights'],
'boy': ['jeans', 'hat'],
};
document.getElementById('genderType').addEventListener('change', function () {
var sel = document.getElementById('clothType'),
value = this.value ? this.value : 'default';
sel.innerHTML = '';
subListArray[value].forEach(function (item) {
sel.appendChild(new Option(item));
});
});
http://jsfiddle.net/VdXk6/
See this page which explains adding elements to the DOM:
http://www.javascriptkit.com/javatutors/dom2.shtml
You need to use createElement, setAttribute and appendChild. E.g:
html:
<select id="mySelect">...</select>
<select id="mySubSelect"></select>
javascript:
var myNewOption = document.createElement( 'option' );
myNewOption.setAttribute( 'value', 'myOptionValue' );
document.getElementById( 'mySubSelect' ).appendChild( myNewOption );
This can go in a loop. Also you can detect when the selection changes like this:
javascript:
document.getElementById('mySelect').addEventListener('change',function(){
document.getElementById('mySelect').selectedIndex; // a number showing which element is selected
});
With jQuery it is a lot easier.

How to get selected value from Dropdown list in JavaScript

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.

How do i get different information in a field based on what i select in a dropdown menu?

I want to add this functionality to my form. when a option from a dropdown menu is selected i want it to input the text field above with the corresponding info. For example:
<form name="form1" action="formhandler">
<input type="text" name="typecar">
<select name="BMWCars">
<option value="Sedan">Sedan</option> // when this option is chosen put string "5-series" in textfield above
<option value="Convertible">Convertible</option> // when this option is chosen put string "6-series" in textfield above
<option value="Truck">Truck</option> // when this option is chosen put string "X5" in textfield above
<option value="Coupe">Coupe</option> // when this option is chosen put string "3-series" in textfield above
<option value="Hatchback">Hatchback</option> // when this option is chosen put string "5-series GT" in textfield above
</select>
</form>
How can this be done with and without having to connect to the to get strings?
The code is tidier if you make your HTML conform to what you need.
http://jsfiddle.net/TgM2W/3/
<form name="form1" id="form1" action="formhandler">
<input type="text" name="typecar" id="typecar">
<select name="BMWCars" id="BMWCars">
<option value="">Select one...</option>
<option value="5-series">Sedan</option>
<option value="6-series">Convertibles</option>
<option value="X5">Truck</option>
<option value="3-series">Coupe</option>
<option value="5-series GT">Hatchback</option>
</select>
</form>
JavaScript (without jQuery):
window.onload = function() {
document.forms['form1'].elements['BMWCars'].onchange = function() {
var opts = this.options;
document.forms['form1'].elements['typecar'].value = opts[opts.selectedIndex].value;
};
};
or using jQuery:
$(document).ready(function() {
$('#BMWCars').change(function() {
var opts = $(this)[0].options;
$('#typecar').val(opts[opts.selectedIndex].value);
});
});
However, if you can't change the HTML, just use an object to store the values and reference that:
objBMW = {
"Sedan":"5-series",
"Convertible":"6-series",
"Truck":"X5",
"Coupe":"3-series",
"Hatchback":"5-series GT"
};
window.onload = function() {
document.forms['form1'].elements['BMWCars'].onchange = changer;
};
function changer() {
var opts = this.options;
document.forms['form1'].elements['typecar'].value =objBMW[opts[opts.selectedIndex].value];
};
Jan. This is what you have to do:
Add identifier to all your referenced items in the HTML.
Write an small Javascript code to detect changes in the dropdown and update the textfield accordly.
<form name="form1" action="formhandler">
<input type="text" name="typecar" id="typecar" />
<select name="BMWCars" id="dropdown">
<option value="5-series">Sedan</option>
<option value="6-series">Convertible</option>
<option value="X5">Truck</option>
<option value="3-series">Coupe</option>
<option value="5-series GT">Hatchback</option>
</select>
</form>
<script type="text/javascript">
var dropdown = document.getElementById( 'dropdown' );
dropdown.onchange = function() {
document.getElementById( 'typecar' ).value = dropdown.value;
};
</script>
You're going to want to do it in jQuery (or javascript).
$("option").change(function() {
var value;
//Do some logic to get the value you want to put in the textbox
$("input[name='typecar']").val(value);
});
Depending on the complexity of your site, there's a couple different ways you can grab the value to put in your textbox. If it will only ever be those 5 options, I would suggest a switch...case. Like this:
$("option".change(function() {
var value;
switch($(this).val()) {
case "Sedan":
value = "5-series";
break;
case "Convertible":
value = "6-series";
break;
case "Truck":
value = "X5";
break;
case "Coupe":
value = "3-series";
break;
case "Hatchback":
value = "5-series GT";
break;
}
$("input[name='typecar']").val(value);
});
$('select').change(function() {
var value = $(this).val();
$("#typecar").val(value);
});
Should do it. Add an ID of typecar to your input field first however.

Categories

Resources