...

View Full Version : Function into IF. Don't work



triko
11-12-2012, 04:24 PM
HI all!
I have this code, but when I running, the program ignore the function vocals and it run without remove the vocals!!! Can you fund my error?
Thanks All :D


function vocals ()
{
var v;
v = "a" + "e" + "i" + "o" + "u";
}

function calculateName(name)
{

var myName = "";
var countConsonants = 0;
for (var i = 0; i < name.length; i++)
{
// after here was: if ( (name[i] != "a") && (name[i] != "e") && (name[i] != "i") && (name[i] != "o") && (name[i] != "u")

/*And now that is*/ if ( name[i] != vocals )
{
myName = myName + name[i];
myName = myName.substring (0,3);
countConsonants ++;
}
}

Logic Ali
11-12-2012, 04:30 PM
if ( name[i] != vocals )

That compares a string with a function address, which doesn't begin to make sense.



function vocals ()
{
var v;
v = "a" + "e" + "i" + "o" + "u";
}



That function (even if you call it properly) has no effect. It does no useful processing and returns nothing.

BluePanther
11-12-2012, 04:37 PM
HI all!
I have this code, but when I running, the program ignore the function vocals and it run without remove the vocals!!! Can you fund my error?
Thanks All :D


function vocals ()
{
var v;
v = "a" + "e" + "i" + "o" + "u";
}

function calculateName(name)
{

var myName = "";
var countConsonants = 0;
for (var i = 0; i < name.length; i++)
{
// after here was: if ( (name[i] != "a") && (name[i] != "e") && (name[i] != "i") && (name[i] != "o") && (name[i] != "u")

/*And now that is*/ if ( name[i] != vocals )
{
myName = myName + name[i];
myName = myName.substring (0,3);
countConsonants ++;
}
}


vocals() is different from vocals.

Regardless, you need to understand how functions work. Just now, vocals() doesn't return anything. All it does, is set a variable inside itself. So, doing name[i] != vocals() doesn't do anything (that's not entirely true, it checks if name[i] will equal the return from vocals() but because there's no return specified, nothing is returned, and your if will always evaluate true).

I don't know why you're wrapping your list of vowels in a function anyway tbh, it's not needed. You could just define the list above the for loop and it'll do an identical job. Functions are about reusable code - if you only need to do something once, don't make it a function.

On top of this, v in vocals will equal "aeiou", so when you do name[i] = v, you're comparing a single character in name with aeiou, which will always be false. You need to approach that differently.

devnull69
11-12-2012, 05:24 PM
Hm ... there are several things that make me think that you are still in a very basic learning phase.

- vocals is a function. To call the function, you need parentheses () vocals(). To compare the result of a function to some other value, you must return something from the function
- What exactly do you want to achieve? Remove the vocals? So you want to find out if name[i] is a vocal?


function vocal(character) {
var returnValue = false;
if(character == "a" || character == "i" || character == "e" || character == "o" || character == "u")
returnValue = true;
return returnValue;
}

...

if(!vocal(name[i])) {
// here the current character is not a vocal
}

sunfighter
11-12-2012, 05:38 PM
I'm sure RegEx would make this a snap, but they take me all day to work out so I used a loop and

if (name[i] == 'a' || name[i] == 'e' || name[i] == 'i' || name[i] == 'o' || name[i] == 'u') This does lead to some strange results if you remove the vowel from the string. So I ended up substituting for the vowels and then removing the token. It took two loops:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script type="text/javascript">
function calculateName(name)
{
var myName = "";
var countConsonants = 0;
var count = name.length;
for (var i = 0; i < count; i++)
{
if (name[i] == 'a' || name[i] == 'e' || name[i] == 'i' || name[i] == 'o' || name[i] == 'u')
{
name = name.replace(name[i], '~');
}
}
for (var i = 0; i < count; i++)
{
name = name.replace('~', '');
}
document.getElementById('here').innerHTML = name;
}
</script>
</head>
<body>
<button onclick="calculateName('BillyJoeBoo')">PUSH</button>
<div id="here"></div>
</body>
</html>

Logic Ali
11-12-2012, 07:13 PM
I'm sure RegEx would make this a snapSlightly simpler but easily avoided for a beginner. I suspect the original intention may have been to build a string from the extracted vowels, otherwise counting the consonants would be unnecessary.

<!DOCTYPE html >
<html>
<head>
<title>TEST</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">

function calculateName( str )
{
var vowelString = "", ch;

for( var i = 0; (ch = str.charAt( i )); i++ )
if( "aeiouAEIOU".indexOf( ch ) > -1 )
vowelString += ch;

document.getElementById('here').innerHTML = vowelString;

return str.length - vowelString.length;
}

</script>
</head>
<body>
<button onclick="alert('Consonants: '+calculateName('BillyJoeBoo'))" >PUSH</button>
<div id="here"></div>
</body>
</html>

triko
11-12-2012, 09:15 PM
I don't know why you're wrapping your list of vowels in a function anyway tbh, it's not needed. You could just define the list above the for loop and it'll do an identical job. Functions are about reusable code - if you only need to do something once, don't make it a function.

I would put the list of vowels into function because I reuse this in other point of program :D!!! :D
But i don't know how to do!!!
:D

devnull69
11-12-2012, 09:23 PM
Did you even read my response?

BluePanther
11-12-2012, 09:38 PM
I would put the list of vowels into function because I reuse this in other point of program :D!!! :D
But i don't know how to do!!!
:D

The best way is to assign it to a variable, then pass the variable list into functions in the future, rather than calling the function inside it. Much more efficient - less operations and less memory.

triko
11-12-2012, 11:31 PM
Did you even read my response?
Yes now I read, sorry!!!
You understand me.. I have low experience with Javascript, and the method that you reccomended it's for me :D

triko
11-12-2012, 11:32 PM
The best way is to assign it to a variable, then pass the variable list into functions in the future, rather than calling the function inside it. Much more efficient - less operations and less memory.

Yes blue, but I must use this function many times in the program :D

triko
11-12-2012, 11:34 PM
Slightly simpler but easily avoided for a beginner. I suspect the original intention may have been to build a string from the extracted vowels, otherwise counting the consonants would be unnecessary.

<!DOCTYPE html >
<html>
<head>
<title>TEST</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">

function calculateName( str )
{
var vowelString = "", ch;

for( var i = 0; (ch = str.charAt( i )); i++ )
if( "aeiouAEIOU".indexOf( ch ) > -1 )
vowelString += ch;

document.getElementById('here').innerHTML = vowelString;

return str.length - vowelString.length;
}

</script>
</head>
<body>
<button onclick="alert('Consonants: '+calculateName('BillyJoeBoo'))" >PUSH</button>
<div id="here"></div>
</body>
</html>
Logic, i'm a low level in Javascript and what that you write it's more complicately for me :D
And don't understand more passages of problem :D

triko
11-13-2012, 12:06 AM
Thanks for all Helping, I complete the first part of program :D
Please test! If you have advice for me, please post :D


<!DOCTYPE HTML>
<html>
<head>
<title>Tax Code</title>
<meta charset = "UTF-8" lang= "en, it" />
<script type="text/javascript">

function consonants (consonant)
{
var returnValueConsonant = false;
if (consonant == "b" || consonant == "c" || consonant == "d" || consonant == "f" || consonant == "g" || consonant == "h" || consonant == "i" || consonant == "j" || consonant == "k" || consonant == "l" || consonant == "m" || consonant == "n" || consonant == "p" || consonant == "q" || consonant == "r" || consonant == "s" || consonant =="t" || consonant == "v" || consonant == "w" || consonant == "x" || consonant == "y" || consonant == "z")
{
returnValueConsonant = true;
}
return returnValueConsonant;
}

function vowels (vowel)
{
var returnValueVowel = false;
if (vowel == "a" || vowel == "i" || vowel == "e" || vowel == "o" || vowel == "u")
{
returnValueVowel = true;
}
return returnValueVowel;
}

function calculateName(name)
{

var myName = "";
var countConsonants = 0;
for (var i = 0; i < name.length; i++)
{

if ( !vowels (name[i]) )
{
myName = myName + name[i];
myName = myName.substring (0,3);
countConsonants ++;
}
}
if (i == 1)
{
myName = myName + "XX";
var nameReturn = name + myName;
}
if (i == 2)
{
myName = myName + "X";
var nameReturn = name + myName;
}
if (countConsonants == 3)
{
var nameReturn = myName;
}
if (countConsonants < 3)
{
var emanYm= "";
for (var i = 0; i < name.length; i++)
{
if ( !consonants (name[i]) )
{
emanYm = emanYm + name[i];
emanYm = emanYm.substring (0,1);
}
}
myName = myName + emanYm;
nameReturn = myName;
}
if (countConsonants > 3)

{
var eman= "";
for (var i = 0; i < name.length; i++)
{
if ( (name[i] != "a") && (name[i] != "e") && (name[i] != "i") && (name[i] != "o") && (name[i] != "u") )
{
eman = eman + name[i];
eman = eman.substring (0,4);
}
}
name = eman.charAt(0) + eman.charAt(2) + eman.charAt(3);
var nameReturn = name;
}
alert (nameReturn.toUpperCase() )
alert (countConsonants);
}

function calculateSurname(surname)
{

var mySurname = "";
var countConsonants = 0;
for (var i = 0; i < surname.length; i++)
{

if ( (surname[i] != "a") && (surname[i] != "e") && (surname[i] != "i") && (surname[i] != "o") && (surname[i] != "u") )
{
mySurname = mySurname + surname[i];
mySurname = mySurname.substring (0,3);
countConsonants ++;
}
}
if (countConsonants == 1)
{
mySurname = mySurname + "XX";
var surnameReturn = mySurname;
}
if (countConsonants == 2)
{
mySurname = mySurname + "X";
var surnameReturn = mySurname;
}
if (countConsonants > 2)
{
var emanrus= "";
for (var i = 0; i < surname.length; i++)
{
if ( (surname[i] != "a") && (surname[i] != "e") && (surname[i] != "i") && (surname[i] != "o") && (surname[i] != "u") )
{
emanrus = emanrus + surname[i];
emanrus = emanrus.substring (0,3);
}
}
var surnameReturn = emanrus;
}
alert (surnameReturn.toUpperCase() );
alert (countConsonants);
}
function calculation()
{
//Create var, for take a data to input
var name = document.getElementById("myName").value;
var surname = document.getElementById("mySurname").value;


//With value of var I do the calculation of Tax Code
var txName = calculateName(name);
var txSurname = calculateSurname(surname);
}
</script>

</head>

<body>
Name: <input type = "text" id = "myName" /> <br />
Surname: <input type = "text" id = "mySurname" /> <br />
<button type = "button" onclick = "calculation()"> CONFIRM </button>


</body>
</html>

Logic Ali
11-13-2012, 01:12 AM
function vowels (vowel)
{
var returnValueVowel = false;
if (vowel == "a" || vowel == "i" || vowel == "e" || vowel == "o" || vowel == "u")
{
returnValueVowel = true;
}
return returnValueVowel;
}

Use the indexOf (https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/indexOf) method:

function vowels (vowel)
{
return "AEIOUaeiou".indexOf( vowel ) > -1;
}

I'm sure you can guess how to write the consonants function.

Old Pedant
11-13-2012, 02:11 AM
I may get shot for this, but...



function calculateName(name)
{
return (name.toUpperCase() + "XXX" ).replace( /[aeiou]/ig, "" ).substring(0,3);
}

Presto. Done.

If you want to keep the first letter, even if it is a vowel, then:


function calculateName(name)
{
return (name.charAt(0) + (name + "XXX").substring(1).replace(/[aeiou]/ig,"") ).substring(0,3).toUpperCase();
}


Totally untested. Off the top of my head. Shall I go test it?

Old Pedant
11-13-2012, 02:16 AM
Yep. Worked fine.



<html>
<body>
<script type="text/javascript">

function calculateName(name)
{
return (name.toUpperCase() + "XXX" ).replace( /[aeiou]/ig, "" ).substring(0,3);
}
function calculateName2(name)
{
return (name.charAt(0) + (name + "XXX").substring(1).replace(/[aeiou]/ig,"") ).substring(0,3).toUpperCase();
}

function demo( word )
{
document.write( word + "==>> (1) " + calculateName(word) + ", ==>> (2) " + calculateName2(word) + "<hr/>" );
}

demo("zamboni");
demo("alphabet");
demo("zoo");
demo("oui");
</script>
</body>
</html>


Note: Both functions work for words of at least 1 letter. The second one will fail if given a word with no characters. The first one will produce "XXX".

triko
11-14-2012, 08:59 PM
Yep. Worked fine.



<html>
<body>
<script type="text/javascript">

function calculateName(name)
{
return (name.toUpperCase() + "XXX" ).replace( /[aeiou]/ig, "" ).substring(0,3);
}
function calculateName2(name)
{
return (name.charAt(0) + (name + "XXX").substring(1).replace(/[aeiou]/ig,"") ).substring(0,3).toUpperCase();
}

function demo( word )
{
document.write( word + "==>> (1) " + calculateName(word) + ", ==>> (2) " + calculateName2(word) + "<hr/>" );
}

demo("zamboni");
demo("alphabet");
demo("zoo");
demo("oui");
</script>
</body>
</html>


Note: Both functions work for words of at least 1 letter. The second one will fail if given a word with no characters. The first one will produce "XXX".

Ok thanks Guy :D
Now please, Can you tell me how to use a radio button and his function checked true, false? Because in www.w3schools.com I don't find how to use it!!!! :D

felgall
11-14-2012, 09:47 PM
Ok thanks Guy :D
Now please, Can you tell me how to use a radio button and his function checked true, false? Because in www.w3schools.com I don't find how to use it!!!! :D

Not sure if w3schools would even cover how to do that since the javaScript covered there ismostly the antiquated version for Netscape 4 and earlier. The two guys who wrote the site in their spare time tried to cover so many different topics that they are struggling to keep any of them up to date and JavaScript has undergone enormous changes since they wrote their site and while they have added pages on the new commands they haven't updated the existing pages to reflect the changes in how they should be used.

To be able to make your code interactive you will first need to get rid of the document.write statement and replace it either with innerHTML calls or proper Document Object Model calls.

To attach processing to elements in the web page you need to be able to identify the element from the JavaScript (giving it an id and using getElementById is easiest but there are lots of other ways) and then attach an appropriate event handler or event listener to the element to specify what code to run when a specific event occursa on that element.

sunfighter
11-15-2012, 06:01 PM
It's not easy, but here's how to find things on w3school:
Main page http://www.w3schools.com/ on right is "Web References" Find and click JavaScript. Bottom of page under "HTML DOM Objects Reference" is "Input Checkbox object" click. Your on the Checkbox Object page and under "Checkbox Object Properties" is "checked" On that page is an example on setting the box, getting the state of the box and a link to a "Try it yourself" page.

triko
11-16-2012, 12:20 AM
Not sure if w3schools would even cover how to do that since the javaScript covered there ismostly the antiquated version for Netscape 4 and earlier. The two guys who wrote the site in their spare time tried to cover so many different topics that they are struggling to keep any of them up to date and JavaScript has undergone enormous changes since they wrote their site and while they have added pages on the new commands they haven't updated the existing pages to reflect the changes in how they should be used.

To be able to make your code interactive you will first need to get rid of the document.write statement and replace it either with innerHTML calls or proper Document Object Model calls.

To attach processing to elements in the web page you need to be able to identify the element from the JavaScript (giving it an id and using getElementById is easiest but there are lots of other ways) and then attach an appropriate event handler or event listener to the element to specify what code to run when a specific event occursa on that element.

AN ok! Thanks for info! So my function checked have simple use: if female ad 40 at number of day date that i0m insert on text type, if male don't add anything and write only the number of day :D

Old Pedant
11-16-2012, 12:48 AM
Ummm...but you *ASKED* for

Can you tell me how to use a radio button and his function checked true, false?
And that's not as simple.

A normal radio button, if there is only ONE of the given name=, can *NOT* be unchecked. Only checked.

You would need some mildly sneaky JavaScript code to be able to un-check a single radio button.

I don't think that's what you really wanted, based on your last post, but just be aware of it.

triko
11-16-2012, 01:09 PM
Ummm...but you *ASKED* for
And that's not as simple.

A normal radio button, if there is only ONE of the given name=, can *NOT* be unchecked. Only checked.

You would need some mildly sneaky JavaScript code to be able to un-check a single radio button.

I don't think that's what you really wanted, based on your last post, but just be aware of it.

I badly explained, re ask my question :D
So my function day contains the document.getElementById (*day that i have selected from mený select*) and if select radio female button, add 40 at number that i selected from mený, else if I have selected male write only the number that I take from mený :D
I would like this method


<script>
function day (myDay)
{
Now write that I think :)
if (id = "male" == checked false)
{
var number;
number = myDay + 40;
}
else (id = "male" == checked true)
{
var number;
number = myDay;
}
alert (myDay);
}
</script>
<body>
<input type = "radio" name = "sex" id = "male" checked = "false" />
<input type = "radio" name = "sex" id = "female" checked = "true" />
Day: <select id = "myDay">
<option>1</option>
<option>2</option>
</select>

Old Pedant
11-16-2012, 09:44 PM
WOW! You know, you can *NOT* just make up your own language. You have to use the language AS IT EXISTS.


function day(myDay)
{
var num = myDay;
if ( document.getElementById("female").checked ) { num += 40; }
alert( num );
}

CAUTION: This *ASSUMES* that if "female" is *NOT* checked, then "male* *IS* checked.

If you want to be careful about it:


function day(myDay)
{
var num = "You did not check either radio button!";
if ( document.getElementById("male").checked ) { num = myDay; }
if ( document.getElementById("female").checked ) { num = myDay + 40; }
alert( num );
}

triko
11-16-2012, 10:37 PM
WOW! You know, you can *NOT* just make up your own language. You have to use the language AS IT EXISTS.


function day(myDay)
{
var num = myDay;
if ( document.getElementById("female").checked ) { num += 40; }
alert( num );
}

CAUTION: This *ASSUMES* that if "female" is *NOT* checked, then "male* *IS* checked.

If you want to be careful about it:


function day(myDay)
{
var num = "You did not check either radio button!";
if ( document.getElementById("male").checked ) { num = myDay; }
if ( document.getElementById("female").checked ) { num = myDay + 40; }
alert( num );
}


Ok, sorry but I don't know how take to input checked!!! And it's so Easy, only add getElementById ("").checked :D Thanks so much my mentor Master javascript!

triko
11-16-2012, 10:45 PM
Sorry Pedant, but what mean:
var num = "You didn't check either radio button!";
???

Old Pedant
11-16-2012, 11:13 PM
That means they did not check EITHER Male OR Female.

BOTH buttons were NOT CHECKED.

triko
11-16-2012, 11:42 PM
That means they did not check EITHER Male OR Female.

BOTH buttons were NOT CHECKED.

And what I need to check whether it is male or female?
I know tht is female check :D

Old Pedant
11-17-2012, 12:13 AM
*TRY* the code I gave you.

It looks for *BOTH* Female and Male and gives the right answer if EITHER ONE is checked.

ONLY if NONE are checked does it give that other message.

Or use the FIRST code I gave you instead of the second code.

triko
11-20-2012, 03:19 PM
*TRY* the code I gave you.

It looks for *BOTH* Female and Male and gives the right answer if EITHER ONE is checked.

ONLY if NONE are checked does it give that other message.

Or use the FIRST code I gave you instead of the second code.

OK thanks guy <3



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum