JavaScript to Change onchange Attribute - javascript

I'm having some issues with using javascript to set the onchange attribute of an HTML element. The script works fine except the else statement does not work even when the select is changed to No. I have tried to debug but nothing shows up. Can someone shed some light as to why this is happening?
<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<style type="text/css">
</style>
<title></title>
<style type="text/css"></style></head>
<body>
<div class="testclass">
<select class="selectClass">
<option value=""></option>
<option value="y">Yes</option>
<option value="n">No</option>
</select>
<input class="inputText" type="text">
</div>
<script type="text/javascript">
var div = document.getElementsByClassName("testclass")[0];
//alert(div.getElementsByClassName("selectClass")[0].value);
var select = div.getElementsByClassName("selectClass")[0];
select.setAttribute("onchange", "myfunction()");
function myfunction() {
var x = document.getElementsByClassName("selectClass")[0];
var y = document.getElementsByClassName("inputText")[0];
if(x.value = "y"){
y.value = "hello";
}
else{
y.value = "boo";
}
}
</script>
</body></html>

You missing "=" in if condition man
if(x.value == "y")

if(x.value = "y"){
y.value = "hello";
}
else{
y.value = "boo";
}
can be converted to
y.value = (x.value === 'y') ? 'hello' : 'boo';
single equal is for assignment. == or === is for comparison. It is also recommended to use === (strong comparision) to ensure they are of same type.

Related

How to call variables out function in javascript

I created this code in javascript, this code work fine, the code use drop-down to select item.
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
</head>
<body><br><div id="id6"></div>
Select an item from the following list:<br />
<select id="select" onchange="myFuntam()">
<option value="">choose
<option value="var_1">car1
<option value="var_2">car2
<option value="var_3">car3
<option value="var_4">car4
</select>
<script>
function myFuntam() {
var x = document.getElementById("select").value;
url="http//domain1.com";
ur2="http//domain2.com";
ur3="http//domain3.com";
ur4="http//domain4.com";
var link_1;
if (x == "var_1") {
link_1=url;
}
if (x == "var_2") {
link_1=ur2;
}
if (x == "var_3") {
link_1=ur3;
}
if (x == "var_4") {
link_1=ur4;
}
document.getElementById("id6").innerHTML = "You selected: " + link_1;
}
</script>
</body>
</html>
Now i need to call variable link_1 out of function, allow me to use this variable with another function or any where out the function.
i try to use this code
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
</head>
<body><br><div id="id6"></div>
Select an item from the following list:<br />
<select id="select" onchange="myFuntam()">
<option value="">choose
<option value="var_1">car1
<option value="var_2">car2
<option value="var_3">car3
<option value="var_4">car4
</select>
<script>
function myFuntam() {
var x = document.getElementById("select").value;
url="http//domain1.com";
ur2="http//domain2.com";
ur3="http//domain3.com";
ur4="http//domain4.com";
var link_1;
if (x == "var_1") {
link_1=url;
}
if (x == "var_2") {
link_1=ur2;
}
if (x == "var_3") {
link_1=ur3;
}
if (x == "var_4") {
link_1=ur4;
}
return link_1;
}
document.getElementById("id6").innerHTML = "You selected: " + link_1;
</script>
</body>
</html>
but this code not correct, link_1 is undefined, so how i use link_1 out of function.
The basics to get it done :
var link_1 = 'foobar';
function ....() { something with link_1; }
console.log(link_1);
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="id6"></div>
Select an item from the following list:<br />
<select id="select" onchange="myFuntam()">
<option value="">choose
<option value="var_1">car1
<option value="var_2">car2
<option value="var_3">car3
<option value="var_4">car4
</select>
<script>
function myFuntam() {
var x = document.getElementById("select").value;
url="http//domain1.com";
ur2="http//domain2.com";
ur3="http//domain3.com";
ur4="http//domain4.com";
var link_1;
if (x == "var_1") {
link_1=url;
}
if (x == "var_2") {
link_1=ur2;
}
if (x == "var_3") {
link_1=ur3;
}
if (x == "var_4") {
link_1=ur4;
}
return link_1;
}
function secondfunction(){
var linkvalue=myFuntam();
alert(linkvalue);
}
document.getElementById("id6").innerHTML = "You selected: " + myFuntam();
</script>
</body>
</html>
An alternative to using a variable, is to store the information in the DOM. You will save some code logic by storing those URL strings in each of the option nodes, as HTML5 data attributes.
The selected URL is then quite easily available.
var sel = document.getElementById('select');
function myFuntam() {
console.log(sel.options[sel.selectedIndex].dataset.url);
return sel.options[sel.selectedIndex].dataset.url;
}
Select an item from the following list:<br>
<select id="select" onchange="myFuntam()">
<option value="">choose
<option value="var_1" data-url="http//domain1.com">car1</option>
<option value="var_2" data-url="http//domain2.com">car2</option>
<option value="var_3" data-url="http//domain3.com">car3</option>
<option value="var_4" data-url="http//domain4.com">car4</option>
</select>
You can of course still decide to store that URL in a global variable, but as you can see, you don't need a lot of logic any more to retrieve it dynamically. Calling the function will just give you the URL you need without much hassle.
You have to declare the var outside the function so the function changes its declared value and you can keep using it the way you wanted after your function is done.
var link_1;
function myFunction() {
link_1 = 'www.anysite.com';
}
myFunction();
//now the var can be used outside
console.log(link_1);
//Anothe option could be
var link;
function myFunction2() {
link = 'www.otherwebsite.com';
return link;
}
link_2 = myFunction2();
console.log(link_2);
The third option could be using localStorage if the other ones did not work.
localStorage.setItem('link_1', link_1_value);
var aLink = localStorage.getItem('link_1');
Choose the one that suits your needs.

Getting an option value to call a javascript function

I'm trying to get an dropdown menu to call javascript functions. The option value seems to default to calling a web page, but I need it run the javascript instead. The javascript I'm using works great when using an onclick fucntion. How can I modify it so it works for my dropdown menu?
<html>
<head>
<link rel="stylesheet" type="text/css" href="mystylesheet.css">
</head>
<body>
<form>
<p><b>Select a Staff Position </b>
<select onchange="window.open(this.value,'','');">
<option value="">Select one</option>
<option value="myFunction1()">Illustrators</option>
<option value="myFunction2()">Tech Writers</option>
</p>
</select>
</form>
<script>
var iframeExists = false;
function myFunction1() {
var x
if (!iframeExists) {
x = document.createElement("IFRAME");
iframeExists = true;
} else {
x = document.getElementsByTagName("IFRAME")[0];
}
x.setAttribute ("src", "http://www.oldgamer60.com/Project/Illustrators.php");
document.body.appendChild(x);
}
function myFunction2() {
var x;
if (!iframeExists) {
x = document.createElement("IFRAME");
iframeExists = true;
} else {
x = document.getElementsByTagName("IFRAME")[0];
}
x.setAttribute("src", "http://www.oldgamer60.com/Project/TechWriters.php");
document.body.appendChild(x);
}
</script>
<br>
</body>
</html>
DRY code makes your life much simpler.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="mystylesheet.css">
</head>
<body>
<form>
<p><b>Select a Staff Position </b>
<select id="mySelect" onchange="select_change()">
<option value="">Select one</option>
<option value="Illustrators">Illustrators</option>
<option value="TechWriters">Tech Writers</option>
</select>
</p>
</form>
<script>
var iframeExists = false;
function select_change() {
var my_select = document.getElementById("mySelect");
var my_select_value = my_select.options[my_select.selectedIndex].value;
var x;
if (!iframeExists) {
x = document.createElement("IFRAME");
iframeExists = true;
} else {
x = document.getElementsByTagName("IFRAME")[0];
}
if(my_select_value) {
x.setAttribute("src", "http://www.oldgamer60.com/Project/" +
my_select_value + ".php");
document.body.appendChild(x);
}
}
</script>
</body>
</html>
Not sure this is the best way to do it but it should provide a solution.
It's possible to store your functions in an object and then call them from a string using the following syntax:
object['nameOfFunction']();
So if we setup the script like so:
function callFunction(){
console.log('change');
var e = document.getElementById('select');
var value = e.options[e.selectedIndex].value;
if (value !== "") {
functions[value]();
}
}
var functions = {
myFunction1: function(){
/*function1 code*/
},
myFunction2: function(){
/*function2 code*/
}
};
So we've got an object 'functions' which has two members called 'myFunction1' and 'myFunction2'. We then have another function which pulls the value from the select and runs the selected function.
And your html like this:
<form>
<p><b>Select a Staff Position </b>
<select id="select" onchange="callFunction()">
<option value="">Select one</option>
<option value="myFunction1">Illustrators</option>
<option value="myFunction2">Tech Writers</option>
</select></p>
</form>
In the html we change the onchange to call our function selector and remove the brackets from the 'myFunction' values.
NOTE: You need to lay out your code so that the script is above the form, maybe in the header, otherwise the 'onchange=' can't access the 'callFunction' due to it not being defined.
EDIT: Take a look at the code here to see it in action: http://plnkr.co/edit/?p=preview
Your HTML mark-up is incorrect. Your </p> is misplaced.
Use this:
<form>
<p><b>Select a Staff Position </b>
<select onchange="window.open(this.value,'','');">
<option value="">Select one</option>
<option value="myFunction1()">Illustrators</option>
<option value="myFunction2()">Tech Writers</option>
</select>
</p>
</form>
Working demo (let it allow popups): https://jsbin.com/xesiyavilu/edit?html,js,output
Update 1:
The issue is that when you do <option value="myFunction1()">Illustrators</option> then myFunction1() is passed as a string.
Change your markup to:
<select onchange="popup(this.value)">
<option value="">Select one</option>
<option value="1">Illustrators</option>
<option value="2">Tech Writers</option>
</select>
in your Javascript, change myFunction1() and myFunction2() to have it return some value, then add this function:
function popup(val){
console.log('val: ' + val);
if(val === '1'){
// call myFunction1() and get something in return;
} else {
// call myFunction2() and get something in return;
}
window.open(returnedValue,'','');
}

Javascript select element to string comparison

Below Code:
<!DOCTYPE html>
<html>
<body>
<select name="cars" id="demo1">
<option value="Volvo">Volvo</option>
<option value="Car">Car</option>
</select>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var compare = 'Volvo';
var e = document.getElementById("demo1");
var val = e.options[e.selectedIndex].value;
if (val == compare) {
alert(val);
}
}
</script>
</body>
</html>
In the above, if I select 'Volvo' from the list and click on "Try it" button it should compare the selected value(here the value is "Volvo") with "Volvo" in javascript and alert the selected value but the "IF" condition in javascript always fails.
Can anyone spot the bug in the code?
Thanks,
ADI
Just insert a closed curly bracket at the end of myFunction
function myFunction() {
var compare = 'Volvo';
var e = document.getElementById("demo1");
var val = e.options[e.selectedIndex].value;
if (val == compare) {
alert(val);
}
}

Check if select options is selected

I am running dataTables plugin for a project.
Could you please show me where I am doing it wrong (it is extremely simple and it doesn't show any errors):
<select name="DataTables_Table_0_length" aria-controls="DataTables_Table_0" class="form-control input-sm">
<option value="10">10</option>
<option value="25">25</option>
<option value="50">50</option>
<option value="100">100</option>
</select>
Basically that is what I have generated. So I want to select the 50 and 100 values to all the tables on the page and show the footer of the generated tables only when these two results are selected.
I tried the following (just for value="50"):
var selected_result = $('select option:nth(2)');
var tfoot = $('tfoot');
tfoot.hide();
if (selected_result.is(':selected')) { tfoot.show(); }
Thank you
Use .change() then check if it's selected to either show/hide the footer.
$(document).ready(function() {
$("#tfoot").hide();
$("select").change(function() {
if ($("select option:nth(2)").is(":selected")) {
$("#tfoot").show();
} else {
$("#tfoot").hide();
}
});
});
http://jsfiddle.net/rcLrf18j/
function showOptionValue() {
var optionSelected = document.getElementById("select_test");
var optionSelected_value = optionSelected.options[optionSelected.selectedIndex].value;
alert(optionSelected_value);
}
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body>
<form action = "" method = "post">
<select name = "select_test" id = "select_test" >
<option value = "10">10</option>
<option value = "25">25</option>
<option value = "50">50</option>
<option value = "100">100</option>
</select>
<input type = "button" value = "show option value" onclick = "showOptionValue()"/>
</form>
</body>
</html>
This code show you the current value of the option when clicking on the button. I let you use this one to modify the function to do what you want to do (meaning, showing your footer).
Hope it helps !
Presumably the footer is hidden by default. If you want to show the footer if either 50 or 100 are selected, then:
$(document).ready(function() {
$('select[name=DataTables_Table_0_length]').change(function() {
if (this.value == '50' || this.value == '100') {
$("#tfoot").show();
} else {
$("#tfoot").hide();
}
});
});
or
$(document).ready(function() {
$('select[name=DataTables_Table_0_length]').change(function() {
this.value == '50' || this.value == '100'? $("#tfoot").show() : $("#tfoot").hide();
});
});
or even:
$(document).ready(function() {
$('select[name=DataTables_Table_0_length]').change(function() {
$("#tfoot")[this.value == '50' || this.value == '100'? 'show' : 'hide']()
});
});

JavaScript Get two dimensional array value based on selected drop down text string

I have the following so far:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html" />
<script src="http://code.jquery.com/jquery-latest.js"></script>
<title>
Select Value From Array
</title>
</head>
<body>
<script type="text/javascript">
var KeysArray = {
"Lake":"imageabc.jpg",
"House":"imagedef.jpg",
"PC":"imageghi.jpg",
"Sky":"imagejkl.jpg"
}
$(function(){
$('.product').change( function() {
var xkey = $.trim( $(".product option:selected").text() );
// alert(xkey);
});
});
</script>
<div>
<select class="product" title="">
<option value="">
-- Select --
</option>
<option value="123">
Lake
</option>
<option value="456">
House
</option>
<option value="789">
PC
</option>
<option value="101">
Sky
</option>
</select>
</div>
</body>
</html>
Once we select a value from the drop down, I need to compare it's option text value with the existing correspondent array value.
So if a user selects "House" I should check if there is a key with that name, and if so, I need to grab it's array value. So in the "House" example it should return "imagedef.jpg".
Can anybody please help? Thank you!
I managed to make it work for you on this jsfiddle.
What you need to do is get the correct key in the KeysArray object on this line:
var xkey = KeysArray[ $.trim( $(".product option:selected").text() ) ];
Alternatively you could do this in 2 steps to improve the readability.
var xkey = $.trim( $(".product option:selected").text() );
xkey = KeysArray[xkey];
It might be worth checking to see if the key actually exists before proceeding. I would suggest a check after getting xkey.
if (typeof xkey !== 'string') { xkey = 'Not found'; }
$('.product').change( function() {
var xkey = $.trim( $(".product option:selected").text() );
alert(KeysArray[xkey]);
});
try this as onchange callback function body
var xkey = $.trim( $(".product option:selected").text() );
alert(KeysArray[xkey] || 'Not found');
I hope this helps.

Categories