ReferenceError - Function not defined when using onchange attribute - javascript

I'm trying to change the value of an input based on what was selected on a dropdown menu, but it always returns "undefined". Here is the HTML:
<select id="dropdown">
<option id="AU">Australia</option>
<option id="CH" >Switzerland</option>
</select>
<input type="text" id="regionInput">
And the JS:
document.getElementById('dropdown').setAttribute("onchange","myFunction()");
function myFunction(){
var country = document.getElementById('dropdown').options[document.getElementById('dropdown').selectedIndex].text;
var region = document.getElementById('regionInput').value;
if (country == "Australia"){
region = 'test';
} else {
region = 'test 2';
}
}
Any help would be greatly appreciated !

It sounds like you're defining the function a local scope of another function. Code called from onXXX attributes is executed in the global scope.
You can use addEventListener and provide a function reference:
document.getElementById('dropdown').addEventListener("change",myFunction);
Notice that the event name doesn't begin with on, and you don't put () after the function name (that will call the function instead of passing a reference).

Try removing the quotation mark "" in myFuction() like this: document.getElementById('dropdown').setAttribute("onchange", myFunction() );

Related

What am I doing wrong? Get selection from drop down list. Javascript

For some reason, I cannot get this to work. I am new to JS (and pretty new to coding in general) and I've been looking at it for several hours and searching here as well. I do not see what is wrong with my code.
I am trying to retrieve a value from a select options list. I want to use that value in another function.
This is what I am trying, and "Vocation" does not change to the value, even though I believe it should.
<body>
<div class="wooh" style="width:200px;margin: 25px;">
<select id="Vocation">
<option value="0">Select Voc:</option>
<option value="3.0">EK</option>
<option value="1.4">RP</option>
<option value="1.1">ED</option>
<option value="1.1">MS</option>
</select>
<p id="result">Vocation</p>
</div>
<script>
// Edit your script here
function selection() {
var x = document.getElementById("Vocation").value;
document.getElementById("result").innerHTML = x;
}
</script>
My end "goal" is to pass the value on to this function:
var x = document.getElementById("level").value;
var y = [value here]
var z = 1600
var a = 305000
document.getElementById("result").innerHTML = Math.ceil((z * Math.pow(y, x))/305000);
Where y should be the value from the selected option. What am I doing wrong?
You have written the code but nothing to specify when the code should run. You need to take your function and turn it into an "event handler".
<div class="wooh" style="width:200px;margin: 25px;">
<select id="Vocation">
<option value="0">Select Voc:</option>
<option value="3.0">EK</option>
<option value="1.4">RP</option>
<option value="1.1">ED</option>
<option value="1.1">MS</option>
</select>
<p id="result">Vocation</p>
</div>
<script>
// You will be needing to refer to the result element more than once, so
// just scan the document for it one time and cache the reference
let result = document.getElementById("result");
// Get a reference to the <select> element and bind a function to its change
// event, which will trigger any time the select's value changes
document.getElementById("Vocation").addEventListener("change", function() {
// Because this function is bound to the select, when it is triggered
// "this" will be an automatic reference to the select.
// Don't use .innerHTML when the string you are working with doesn't
// contain any HTML because .innerHTML has security and performance
// implications. For plain text, use .textContent
result.textContent = this.value;
});
</script>
Learn more about events and event handling here.

Get the values of all select options on change event javascript

I want to know all the values of a select element once the change event is recorded on it.
Code is like this:
PHP
<select name='variant' class='variantsselect' onchange='on(this.value)'>
<option value='a'>a</option>
<option value='a'>a</option>
</select>
JAVASCRIPT
function on(value){
alert(value); //This gives me selected value
};
I need values a & b when change event is recorded on select element. Can someone help?
<select name='variant' class='variantsselect' onchange="javascript:valueselect(this)">
function valueselect(sel) {
var value = sel.options[sel.selectedIndex].value;
alert(value)
}
EDIT:
<select name='variant' id='variant' class='variantsselect' onchange="javascript:displayResult()">
function displayResult() {
var x = document.getElementById("variant");
var i;
var txt = "Text: ";
for (i = 0; i < x.length; i++) {
txt = txt + "\n" + x.options[i].text;
}
alert(txt);
}
You can store the last selected value in a variable and overwrite the variable with the new selected value at the end of your function. When the function is called the variable will = to the last option selected (If you don't set a default value the variable will be empty on the first call)
Click Here For Demo
OR
This will work for a simple hide/show select without having to remember the previous selection.
The hide/show content have a class name of HideShow, this class name css display is set to none. When you change the option it will loop through all elements using the class name HideShow to compare the selected value with the id of the element, if they match it will set the style display to block }else{ set style display to none.
Demo
function HideShow(Selection){
var HScontent=document.getElementsByClassName('HideShow');
for(var i=0; i<HScontent.length; i++){
if(HScontent[i].id==Selection){
HScontent[i].style.display="block";
}else{
HScontent[i].style.display="none";
}
}
}
.HideShow{display:none;}
<select onchange="HideShow(this.value);">
<option value="cars">Cars</option>
<option value="bikes">Bikes</option>
<option value="buses">Buses</option>
</select>
<div id="cars" class="HideShow">Cars content.....</div>
<div id="bikes" class="HideShow">Bikes content....</div>
<div id="buses" class="HideShow">Buses content....</div>
If you don't understand something in the demo, leave a comment below and I will try get back to you as soon as possible.
I hope this helps. Happy coding!

How to pass id, name & value of a div tag to a javascript function

I am trying to pass value stored inside a div tag to a javascript function based on the onchange property of a drop down menu in HTML.
But nothing is being passed. Undefined error is shown.
Here my code:
Suppose $temp_c has a value 30.
<span id="temperature_div"><?php echo $temp_c; ?></span>
<label for="ddl_temptype"></label>
<select id="ddl_temptype" name="ddl_temptype" onchange="choose_temperature(this.value,temperature_div.value,temperature_div.name); ">
<option value="celcius" selected>°C</option>
<option value="farenheit">°F</option>
</select>
And JavaScript
function choose_temperature(conv, value, name) {
alert(conv);
alert(value);
alert(name);
}
Where did I go wrong??
In JavaScript you can't just use temperature_div as a variable and assume it will be the object with id temperature_div. There are functions for fetching elements from the DOM. In plain JavaScript: document.getElementById('temperature_div') will return the element. If you're using JQuery, then $('#temperature_div') will do a similar thing.
Edit:
Try this function:
function choose_temperature(conv) {
alert(conv);
var element = document.getElementById('temperature_div');
alert(element.innerHTML);
alert(element.attributes["name"].value);
}
Called by: choose_temperature(this.value);
Edit: Changed to use innerHTML and attributes["name"].value instead of value and name. I'm assuming that these are what are wanted.
First of all you have used the parameter 'value' which I think is a key word and better not to use.
and I am assuming you are referring to the 'name' html attribute in the 'temperature_div', which you have not defined. I am putting a name attribute just for the sake of understanding.
<html>
<script type="text/javascript">
function choose_temperature(conv, t_value, name)
{
alert(conv);
var div = document.getElementById("temperature_div");
alert(div.innerHTML);
alert(div.getAttribute("name"));
}
</script>
<label for="ddl_temptype"></label>
<select id="ddl_temptype" name="ddl_temptype" onchange="choose_temperature(this.value); ">
<option value="celcius" selected>°C</option>
<option value="farenheit">°F</option>
</select>
Use jquery instead, it is easier.
Get value inside a div as: $('#temperature_div').html() Or $('#temperature_div').text()
You can write onchange for a select box as:
$(document).on('change', '#ddl_temptype', function() {
// Write your function here
var div_value = $('#temperature_div').html();
var select_val = $(this).val();
alert(div_value);
});
Or like this
$('#some_id').on('change', function() {
// Write your function here
var div_value = $('#temperature_div').html();
var select_val = $(this).val();
alert(div_value);
});
Use getElementById() in javascript
<span id="temperature_div"><?php echo $temp_c; ?></span>
<label for="ddl_temptype"></label>
<select id="ddl_temptype" name="ddl_temptype" onchange="choose_temperature(); ">
<option value="celcius" selected> °C</option>
<option value="farenheit"> °F</option>
</select>
function choose_temperature()
{
var value=document.getElementById('temperature_div').innerHTML; //to get html inside span
var conv=document.getElementById('ddl_temptype').value;
alert(conv);
alert(value);
}

Pass variable from a select value to a javascript function CDATA string

Currently I have a basic javascript which will alert the value of a selection. I would like to tie this into a javascript function so instead of alerting the value, it replaces the value within the script.
<script type="text/javascript">
function cselect(){
var CID = document.getElementById('country').value;
alert(CID);
}
</script>
<select id="country" onchange="cselect()">
<option value="4242">US</option>
<option value="4243">Canada</option>
</select>
I would like to pass the option value into the script below in place of the static value. Any help greatly appreciated!
<script>// <![CDATA[
cii_EmbedProductLinks('Chairs','{{ prodID }}','4242', CI_LinkID);
// ]]></script>
Maybe something like this:
var sub = $("body").html().replace('4242',CID);
$("body").html(sub);

<Select> with onChange working only once, and setting values with getElementsByName

I have various forms on a page, and a PHP-generated select on the top of the page.
What I want to do is:
The user selects an option from the form.
The value of the option is put into all of the inputs with a specific name.
The user can select another option, and the value of that option would replace the old value of the input.
The code I have so far (that doesn't work):
It doesn't work as in the onChange only fires the first time you select an option, and the values of the inputs aren't updated to the chosen option's value.
The select: (It can have more or less than three options, depending on the user.)
<select name="example" onchange="setexample()" id="exampleID">
<option value="1">Default Example</option>
<option value="12">User-created Example #2</option>
<option value="8">User-created Example #1</option>
</select>
This is part of one of the forms around the page:
<form action="[URL]" method="get">
<input type="hidden" name="exampleform" id="example1" value="">
// Other inputs //
</form>
JavaScript:
<script>
function setexample(){
setexample = document.getElementById("exampleID").options[document.getElementById("exampleID").selectedIndex].value;
document.getElementsByName("exampleform").value = setexample;
}
</script>
I don't want to use jQuery. This is just JavaScript.
Thank you in advance.
In your code:
> function setexample(){
> setexample = document...
The assignment to setexample overwrites the existing value (which is the function setexample). Declare the variable inside the function:
var setexample = document...
For the rest, see nnnnnn's answer.
The getElementsByName() method returns a list of elements, so you can't just directly set the value property that belongs to the individual elements in the list. You need to loop through the list (it's an HTMLCollection but for this purpose you can treat it like an array):
var els = document.getElementsByName("exampleform");
for(var i = 0; i < els.length; i++)
els[i].value = setexample;
For the rest, see RobG's answer.
You have these issues:
You're overwriting the name of your function and should use a local variable of a different name.
You're reference a single element form getElementsByName when it returns an array.
Try this:
<script>
function setexample(){
var item = document.getElementById("exampleID");
var val = item.options[item.selectedIndex].value;
var list = document.getElementsByName("exampleform");
for (var i = 0; i < list.lenth; i++) {
list[i].value = val;
}
}
</script>

Categories

Resources