Picking up a variable from inside an if-statement - javascript

I'm trying to learn JavaScript but I've gotten stuck.
Here's a JSFiddle demonstrating the code below.
The problem here is that I want a function or something to calculate the total, but I do not know how to pick up the variable from inside the if-statement.
Is there any way to do this? Thanks in advance!
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript">
function funky(){
var mengde = document.getElementById("options").value;
var valgt = document.getElementById("fruit").value;
if(valgt == "banan") {
mengde*=10;
document.getElementById("totalt1").innerHTML = mengde;
}
if(valgt == "eple") {
mengde*=20;
document.getElementById("totalt2").innerHTML = mengde;
}
if(valgt == "melon") {
mengde*=30;
document.getElementById("totalt3").innerHTML = mengde;
}
if(valgt == "appelsin") {
mengde*=40;
document.getElementById("totalt4").innerHTML = mengde;
}
}
</script>
</head>
<body>
<input id="options" type="text"></input>
<select id="fruit">
<option>Velg Frukt!</option>
<option value="banan">Banan</option>
<option value="eple">Eple</option>
<option value="melon">Melon</option>
<option value="appelsin">Appelsin</option>
<option value="totis">Totalt</option>
</select>
<button onclick="funky()">Submit!</button>
<p id="totalt1"></p>
<p id="totalt2"></p>
<p id="totalt3"></p>
<p id="totalt4"></p>
</body>
</html>

If I understand correctly, you're looking for something like this (although not the nicest javascript I'm trying to keep it similar to the approach you started out with)
http://jsfiddle.net/YZBL7/
if(valgt == "banan") {
total = mengde + " banan costs " + mengde * 10;
}
//....
document.getElementById("totalt1").innerText += total + "\n";

Related

Problem with making a button that changes color in javascript

I want to make a missing word game where you have to choose correct missing word out of few.
For example.
"The Sun _____."
A. shine
B. shines
C. shining.
After that there should be button that changes the color of missing word to green if its correct and red if its wrong.
I have tried to make if else statement but I think I'm not good enough
function myFunction() {
if (document.getElementById("demo") = "shines") {
document.getElementById("demo").style.color = "green";
} else {
document.getElementById("demo").style.color = "red";
}
}
<p>1. The Sun
<select>
<option id="demo" value="shine">shine</option>
<option id="demo" value="shining">shining</option>
<option id="demo" value="shines">shines</option>
</select>
</p><button onclick="myFunction()">Check!</button>
How can I make it work?
Couple of issues here:
Your if statement is making an assignment instead of equality
This has 1 = sign
if (document.getElementById("demo").value = "shines")
Should be like this:
if (document.getElementById("demo").value == "shines")
You shouldn't create multiple elements with the same id (demo in
your case). I think you wanted to give the <select/> element the
id and not to the <option/>?
You may want to check:
document.getElementById("demo").value
Here is a running code that may help you keep going:
function myFunction() {
if (document.getElementById("demo").value == "shines") {
document.getElementById("demo").style.color = "green";
} else {
document.getElementById("demo").style.color = "red";
}
}
<p>1. The Sun
<select id="demo">
<option value="shine">shine</option>
<option value="shining">shining</option>
<option value="shines">shines</option>
</select>
</p><button onclick="myFunction()">Check!</button>
You should check for value using .value on the <select> element, not on <option>, and secondly, you should compare with === or ==, not with =
function myFunction() {
if (document.getElementById("demo").value === "shines") {
document.getElementById("demo").style.color = "green";
} else {
document.getElementById("demo").style.color = "red";
}
}
<!DOCTYPE html>
<html>
<head>
<title>Present Simple</title>
</head>
<body>
<p>1. The Sun
<select id="demo">
<option value="shine">shine</option>
<option value="shining">shining</option>
<option value="shines">shines</option>
</select>
</p><button onclick="myFunction()">Check!</button>
</body>
</html>

specific e-mail pattern control with javascript

I've a textBox control and would like my users to only be able to enter ....#firm1.com' or '....#firm2.com'
How can I do this with a JavaScript function? The function must take a textbox value.
It doesn't make sense to give the user a textbox but allowing him to write two values only,
You should use a dropdown instead:
<select>
<option value="0"> #firm1.com </option>
<option value="1"> #firm2.com </option>
</select>
Update:
If you really have to use textbox for some unknown reason:
$('#textboxId').change(function(){
if (!this.value.match(/(#firm1.com|#firm2.com)$/g))
alert('invalid value');
});​
Live DEMO
Try this code-
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
var patt1 = "[A-Za-z0-9._%+-]+#firm(1|2).com";
function demoShowMatchClick(str) {
var re = new RegExp(patt1);
var m = re.exec(str);
if (m == null) {
document.getElementById("match").innerHTML = "no match";
} else {
document.getElementById("match").innerHTML = "match";
}
}
</script>
</head>
<body>
<span id="match"></span>
<input type="text" onkeyup="demoShowMatchClick(this.value)" />
</body>
</html>

JavaScript code for getting the selected value from a combo box

Can any one give me a sample code that gets the selected value from an existing combo box?
I have this code but its not doing anything:
function check ()
{
var e = document.getElementById("ticket_category_clone");
var str = e.options[e.selectedIndex].text;
alert(str);
if (str==="Hardware")
{
SPICEWORKS.utils.addStyle('#ticket_c_hardware_clone{display: none !important;}');
}
}
SPICEWORKS.app.helpdesk.ready(check);​
heres a img of the code
and the code
<select id="ticket_category_clone" name="ticket[category]" hdpp="ticket_category">
<option value=""></option><option value="Hardware">Hardware</option>
<option value="Software">Software</option>
<option value="Rede" selected="selected">Rede</option>
<option value="Pedidos">Pedidos</option>
<option value="Formação/Dúvida">Formação/Dúvida</option>
<option value="Outro">Outro</option><option value="#edit_categories#">Edit Categories...</option></select>
what i want its find a way to get the selected value fo that combobox
There is an unnecessary hashtag; change the code to this:
var e = document.getElementById("ticket_category_clone").value;
I use this
var e = document.getElementById('ticket_category_clone').value;
Notice that you don't need the '#' character in javascript.
function check () {
var str = document.getElementById('ticket_category_clone').value;
if (str==="Hardware")
{
SPICEWORKS.utils.addStyle('#ticket_c_hardware_clone{display: none !important;}');
}
}
SPICEWORKS.app.helpdesk.ready(check);​
It probably is the # sign like tho others have mentioned because this appears to work just fine.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<select id="#ticket_category_clone">
<option value="hw">Hardware</option>
<option>fsdf</option>
<option>sfsd</option>
<option>sdfs</option>
</select>
<script type="text/javascript">
(function check() {
var e = document.getElementById("#ticket_category_clone");
var str = e.options[e.selectedIndex].text;
alert(str);
if (str === "Hardware") {
alert('Hi');
}
})();
</script>
</body>

Dynamic javascript select dropdown

This was interesting. In a select dropdown, trying not to use jQuery (with the exception of easing some of my pain on recreation), I ran into an issue that doesn't properly let any current browsers catch the proper selected option. Here is my code, for the page that recreates the issue (remember, no jQuery to necessarily solve issue, but more or less just telling me what I am doing wrong.
This one has me stumped.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
<div id="select-holder" />
<input id="some-button" type="button">
<script type="text/javascript">
$("#some-button").click(function(){
var select_element = document.createElement('select');
select_element.setAttribute("id", "some-id");
select_element.setAttribute("name", "some-name");
var options = new Array();
for ( var i = 0; i < 3; i++ ){
options.push(new Option("Option " + i, "Value" + i, false, false));
}
options[1].setAttribute("selected", "selected");
for ( var option in options ){
select_element.appendChild(options[option]);
}
$("#select-holder").append(select_element);
});
</script>
</body>
</html>
The html this creates is:
<select id="some-id" name="some-name">
<option value="Value0">Option 0</option>
<option value="Value1" selected="selected">Option 1</option>
<option value="Value2">Option 2</option>
</select>
But the anomaly here is that (in firefox at least), the selected option ends up being Option 0, which isn't the selected DOM element. In IE6, this select dropdown doesn't work at all.
There is an alternate method that does work, which includes piecing the options together manually, which works in all browsers that I have tested.
A small change made it work for me in Firefox:
...
//options[1].setAttribute("selected", "selected");
options[1].selected = true;
...
I'm manipulating the DOM element's attributes directly. Not sure why your method doesn't work. Maybe you should keep both lines so that the HTML generated has the selected = "selected" in it.
some old thread - however try something like this:
var idx=0;
while(obj.options[idx]) {
if(obj.options[idx].value==value) obj.options[idx].setAttribute('selected',true);
else obj.options[idx].removeAttribute('selected');
idx++;
}
Use selectedIndex to set the selected index of a select object.
options.selectedIndex = 1;
Here is the working code, which seems like more of a Hack!
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
<div id="select-holder" />
<input id="some-button" type="button">
<script type="text/javascript">
$("#some-button").click(function(){
var select_element = document.createElement('select');
select_element.setAttribute("id", "some-id");
select_element.setAttribute("name", "some-name");
for ( var i = 0; i < 3; i++ ){
var option_element = document.createElement('option');
option_element.setAttribute('value', "Value" + i);
option_element.appendChild( document.createTextNode( "Option " + i ) );
if (i == 1){
option_element.setAttribute("selected", "selected");
}
select_element.appendChild(option_element);
}
$("#select-holder").append(select_element);
});
</script>
</body>
</html>
options[1].setAttribute("selected", "selected");
is likely where your issue lies. The output you're getting is:
<option value="Value1" selected="selected">Option 1</option>
and the standard is:
<option value="Value1" selected>Option 1</option>
You may be able to do:
options[1].selected = true;

jQuery Live Search with Quicksilver Style in a Multi Select List Box

I am trying to get John Resig's jQuery Live Search with Quicksilver Style to work with a select multi form control. His code is based John Nunemaker's Work developing his quicksilver.js code.
The problem I am having is that within a select box only Firefox supports .hide() on option values, I can't figure out a snappy approach for IE, Safari, Opera and Chrome.
Here is an example, I have inlined John R's code but you will need to grab quicksilver.js and host it locally yourself. Again this works great in Firefox but the call to rows.hide() does nothing on other browsers.
I have tried wrapping the tags in in a div and hiding that but no luck.
Any ideas?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>LiveSearch</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script type="text/javascript" src="../jquery/quicksilver.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$('#q').liveUpdate('#posts').focus();
});
jQuery.fn.liveUpdate = function(list){
list = jQuery(list);
if ( list.length ) {
// Changed 'li' to 'option' below
var rows = list.children('option'),
cache = rows.map(function(){
return this.innerHTML.toLowerCase();
});
this
.keyup(filter).keyup()
.parents('form').submit(function(){
return false;
});
}
return this;
function filter(){
var term = jQuery.trim( jQuery(this).val().toLowerCase() ), scores = [];
if ( !term ) {
rows.show();
} else {
rows.hide();
cache.each(function(i){
var score = this.score(term);
if (score > 0) { scores.push([score, i]); }
});
jQuery.each(scores.sort(function(a, b){return b[0] - a[0];}), function(){
jQuery(rows[ this[1] ]).show();
});
}
}
};
</script>
</head>
<body>
<form method="get" autocomplete="off" action="">
<div>
<input type="text" value="" name="q" id="q"><br><br>
<select id="posts" multiple name="choices" SIZE="10" style="width: 250px">
<option value="1">The Well-Designed Web</option>
<option value="2">Welcome John Nunemaker</option>
<option value="3">Sidebar Creative: The Next Steps</option>
<option value="4">The Web/Desktop Divide</option>
<option value="5">2007 in Review</option>
<option value="6">Don't Complicate the Solution</option>
<option value="7">Blog to Business</option>
<option value="8">Single Line CSS</option>
<option value="9">The Great Divide</option>
<option value="10">What's in a Name?</option>
</select>
</div>
</form>
</body>
</html>
The best approach is just to add and remove options from the DOM.
Like this:
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$('#q').liveUpdate('#posts').focus();
});
jQuery.fn.liveUpdate = function(list){
list = jQuery(list);
if ( list.length ) {
// Changed 'li' to 'option' below
var rows = list.children('option'),
cache = rows.map(function(){
return this.innerHTML.toLowerCase();
});
var all = rows;
all.each(function(i){
$(this).attr("itext", this.innerHTML.toLowerCase());
});
this
.keyup(filter).keyup()
.parents('form').submit(function(){
return false;
});
}
return this;
function filter(){
var term = jQuery.trim( jQuery(this).val().toLowerCase() ), scores = [];
if ( !term ) {
list.append(all);
} else {
rows.remove();
all.each(function(i){
var score = $(this).attr("itext").score(term);
if (score > 0) { scores.push([score, i]); }
});
jQuery.each(scores.sort(function(a, b){return b[0] - a[0];}), function(){
list.append(all[this[1]]);
});
rows = list.children('option');
}
}
};
</script>
EDIT:
Need to score over array "all" rather than rows.

Categories

Resources