Unable to display the details of items - javascript

var par = new Array(2);
par.push("Apple");
par.push("Orange");
var nar = new Array("2");
nar.push("red ");
nar.push("dark orange");
var ok = document.getElementById('one').value;
function abc() {
for (var i = 0; i < par.length; i++) {
if (par[i] == ok) {
break;
}
}
document.write(par[i] + " " + "color is " + " " + nar[i]);
}
<!doctype html>
<html>
<head>
</head>
<body>
<label>Enter the name</label>
<input type="text" id="one">
<input type="submit" onclick="abc()" id="on">
</body>
</html>
// In the above code snippets I am trying to display the color of apple and orange by defining the required details in an array but while running the code I am getting output as "undefined color is undefined".I am unable to figure out the exact problem in my code.

In Ist Statement you have used var par =new Array(2); This means it is creating 2 empty slots and then 2 values so creating array of length 4 . And in 2nd one you are using var par =new Array("2"); means ist value s string and then 2 value so creating array of length 3. So you are getting wrong result. Use new Array() this. Also get the value of ok inside abc function
var par =new Array();
par.push("Apple");
par.push("Orange");
var nar= new Array();
nar.push("red ");
nar.push("dark orange");
function abc(){
var ok= document.getElementById('one').value;
for (var i=0;i<par.length;i++){
if(par[i]==ok){
break;
}
}
document.write(par[i]+" "+"color is "+" "+nar[i]);
}
<!doctype html>
<html>
<head>
</head>
<body>
<label>Enter the name</label>
<input type="text" id="one">
<input type="submit" onclick="abc()" id="on">
</body>
</html>

in your code after the loop ends i,j will be 2 and bar[2] or nar[2] will be undefined (accessing element of array with not existing index)
you need to move the write command to loop
for (var i = 0; i < par.length; i++) {
if (par[i] == ok) {
break;
}
document.write(par[i] + " " + "color is " + " " + nar[i]);
}

The problem is you define ok outside the abc() function. At the time you define it (as the pages loads), the input is empty.
When you click on your submit button, ok is still the value of the input as it loaded.
The following should work :
function abc(){
for (var i=0;i<par.length;i++){
var ok= document.getElementById('one').value;
if(par[i]==ok){
break;
}
}
document.write(par[i]+" "+"color is "+" "+nar[i]);
}

<html>
<head>
</head>
<body>
<label>Enter the name</label>
<input type="text" id="one">
<input type="submit" onclick="abc()" id="on">
<script>
var par =new Array("Apple","Orange");
var nar= new Array("red ","dark orange");
var ok= document.getElementById('one').value;
function abc(){
for (var i=0;i<par.length;i++){
if(par[i]==ok){
break;
}
document.write(par[i]+" "+"color is "+" "+nar[i]);
}
}
</script>
</body>
</html>

Related

Javascript: why am i getting NaN even after using parseInt() function?

I want to create a HTML page that can do the following tasks:
Take a number from the user
Calculate a multiplication table and show it below the calculate button
Format of multiplication table should be like this, but on the same page and below the calculate button:
5
10
15
20
25
30
35
40
45
50
But I am getting NaN error, and also need help with how to get table displayed like this on the same page, please help and bear with my newbie mistakes :-)
<!doctype html>
<html>
<head>
<title>Multiplication Table</title>
<script type="text/javascript">
function createTable(nn)
{
for(i=1; i<=10; i++)
{
document.getElementById("t1").innerHTML = nn*i;
}
return true;
}
</script>
</head>
<body>
<h1><center>Assignment No.4</center></h1>
<h4><center>Please Enter Number for Table and press the button</center><h4>
<form>
<center><input type="text" name="num" size=10></center><br />
<center><button type="button" onclick="createTable('n')">Calculate</button></center>
</form>
<center><p id="t1"></p></center>
<script type="text/javascript">
m = "num".value;
n = Number(m);
</script>
</body>
</html>
There's no mystery
m = "num".value;
here, m = undefined, because the string "num" has no property called value, i.e. it's undefined
n = Number(m);
Number(undefined) === NaN - because undefined is not a number
edit: also your onclick is called like this - createTable('n')
same problem, 'n' is not a number, it's a string .. 'n' * anything == NaN
There some problem with your program just see this one
<!doctype html>
<html>
<head>
<title>Multiplication Table</title>
<script type="text/javascript">
function createTable()
{
var nn = document.getElementById("num").value;
var str="<table>";
for(i=1; i<=10; i++)
{
str+="<tr><td>" + nn + "*" + i +" = " + (nn*i) + "</td></tr>";
}
str+="</table>";
document.getElementById("t1").innerHTML = str;
}
</script>
</head>
<body>
<h1><center>Assignment No.4</center></h1>
<h4><center>Please Enter Number for Table and press the button</center><h4>
<form>
<center><input type="text" id="num" name="num" size=10></center><br />
<center><button type="button" onclick="createTable()">Calculate</button></center>
</form>
<center><p id="t1"></p></center>
</body>
</html>
You are converting a value to a number, but it's at the wrong time, and it's the wrong value. Then you don't even use the result.
This code:
m = "num".value;
n = Number(m);
is executed when the page loads, so that's before the user has had any chance to enter any number. It doesn't use the field where the user could enter a number, it only uses the string "num". As the string isn't the input element, it doesn't have a property named value, so m gets the value undefined. Turning that into a number gives you NaN, but that's not even the NaN that you get in the output, because the value of n is never used.
This code:
onclick="createTable('n')"
doesn't use the variable n, it uses the string 'n'. That is what gives you the NaN in the output, because that is what you get when you try to use the string in the multiplication. I.e. 'n' * i results in NaN.
To get the value that the user entered, you should get it at the time that the user clicks the button. Put the code in a function so that you can call it at that time. Use the getElementsByName method to locate the element:
function getValue() {
var m = document.getElementsByName("num")[0].value;
return Number(m);
}
When the user clicks the button, call the function to get the value and send it to the function that creates the table:
onclick="createTable(getValue())"
In your code where you create the table, you should put the items together and then put them in the page. If you put each item in the element, they will replace each other and you end up with only the last one. Also, you would want to put an element around each item, otherwise you end up with just a string of digits:
function createTable(nn) {
var str = '';
for(var i = 1; i <= 10; i++) {
str += '<div>' + (nn * i) + '</div>';
}
document.getElementById("t1").innerHTML = str;
}
Demo:
function createTable(nn) {
var str = '';
for(var i = 1; i <= 10; i++) {
str += '<div>' + (nn * i) + '</div>';
}
document.getElementById("t1").innerHTML = str;
}
function getValue() {
var m = document.getElementsByName("num")[0].value;
return Number(m);
}
<h1><center>Assignment No.4</center></h1>
<h4><center>Please Enter Number for Table and press the button</center><h4>
<form>
<center><input type="text" name="num" size=10></center><br />
<center><button type="button" onclick="createTable(getValue())">Calculate</button></center>
</form>
<center><p id="t1"></p></center>

Double tilde (~~) operator is removing decimal portion of number

So all this time I thought I was doing it wrong. But can jQuery read decimals? My first textbox has to multiply the input with .10, the second is .05. But I only get 1 as final result. How can I fix it?
<!DOCTYPE html>
<head>
<title>Test</title>
<script src="../js/jquery-1.11.1.min.js"></script>
<head>
<body>
<input id="first" type="text" />
<script>
$('#first').on('change', function () {
$(this).val($(this).val() * .10);
compute();
});
</script>
<input id="second" type="text" />
<script>
$('#second').on('change', function () {
$(this).val($(this).val() * .05);
compute();
});
</script>
<script>
function compute() {
var first = ~~$('#first').val();
var second = ~~$('#second').val();
var result = $('#result');
var grade = first + second;
result.val(grade);
}
</script>
<input id="result" type="text" readonly />
</body>
</html>
I believe you want to change compute() to this:
function compute() {
var first = parseFloat($('#first').val());
var second = parseFloat($('#second').val());
var result = $('#result');
var grade = first + second;
result.val(grade);
}

Uncaught ReferencEerror function is not defined, how to use typeof with an if else?

I am trying to get the initials (upper case letters) of the name that the user enters inside the text field. I get and error that my function getInitials() is not defined. Why do I get this error? Also I want to check if the function exists with typeof.
<!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">
<head>
<title>Second task HS</title>
</head>
<body>
<form name="myForm" id="eForm" action="#">
<label for="name">Name</label>
<input type="text" id="name" name="fullname"/><br>
<input name="button" type="button" value="Pick" onclick="getInitials();"/>
</form>
<div id="result">
</div>
<script type="javascript">
var nameInput = document.getElementById('name').value;//I need to stringify the input and use it!
var arr, nameArr, first, last;
nameArr = name.split(' ');
first = nameArr[0][0].toUpperCase();
last = nameArr[nameArr.length - 1][0].toUpperCase();
if(typeof getInitials == 'function'){
function getInitials(nameArr) {
return {first: first, last: last};
}
getInitials(nameInput);
}else{
alert('Check getInitials!');
}
</script>
</body>
</html>
From what I see, you are checking if the function exists... before creating it !
Try rather this JS code :
function getInitials( nameInput ) {
var nameArr = nameInput.split(' ');
return {
first: nameArr[0][0].toUpperCase(),
last: nameArr[nameArr.length - 1][0].toUpperCase()
};
}
function getInitialsFromInput() {
var nameInput = document.getElementById('name').value;
if(getInitials instanceof Function){ //strictly speaking, useless because it is obviously a function
alert(getInitials(nameInput));
}else{
alert('Check getInitials!');
}
}
getInitialsFromInput() ;
(and use "getInitialsFromInput()" for the onclick to gather the input's value)
You missed the text in <script type="javascript">, the statement should be like this <script type="text/javascript">
Here is the simple version of what you wanted, try it, this program expects first name Or first and last name only.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Second task HS</title>
<script type="text/javascript">
var arr, first, last;
function getInitials() {
var nameInput = document.getElementById('name').value; //I need to stringify
nameArr = nameInput.split(' ');
if(nameArr.length > 1){
first = nameArr[0].toUpperCase();
last = nameArr[1].toUpperCase();
}else{
first = nameInput.toUpperCase();
}
var result = {first: first, last: last};
alert(result.first);
alert(result.last);
}
</script>
</head>
<body>
<label for="name">Name</label>
<input type="text" id="name" name="fullname"/><br>
<input name="button" type="button" value="Pick" onclick="getInitials()"/>
<div id="result">
</div>
</body>
</html>
Your code makes no sense. getInitials Just is not assigned initially, so the inline click handler within the button will never work.
If you need the input value with first characters uppercased and initials, try something like:
document.querySelector('button[value=Pick]').onclick = getInitials;
function getInitials(e) {
var value = document.querySelector('#name')
.value.split(/\s+/)
.map( first2Upper );
if (value[0].length){
var ret = {first: value[0],
last: value[1],
initials: value[0][0] +(value[1] && value[1][0] || '')};
document.querySelector('#result').innerHTML =
value.join(' ') + ' (initials: '+ret.initials+')';
return ret;
} else {
alert('please enter a value');
}
}
function first2Upper(str) {
return str.slice(0,1).toUpperCase() + str.slice(1);
}
Here's a mockup in jsFiddle

I'm trying to make this random name generator in JS. The array is returning undefined?

I'm trying to make a simple generator that takes some syllables from a user and randomly forms a made up word out of them.
I've managed to make a nice input system. It puts the syllables into a 2D array. I've tested it and it works.
When I try to alert random parts of the array it yells at me: "Uncaught TypeError: Cannot read property '0' of undefined"
<html>
<head>
<script type = "text/javascript">
var sounds = [[],[],[]];
function makeName(x){
alert(x[0][random(x[0].length)] + x[1][random(x[1].length)] + x[2][random(x[2].length)]); //Something is wrong here
}
function random(x){ //Random number between 0 and x-1
return Math.floor(Math.random()*x); //The problem might be here too
}
var Count0 = 0;
var Count1 = 0;
var Count2 = 0;
function add(type, fooNum) {
//Create an input type
var element = document.createElement("input");
//Add to index of user supplied data
if(fooNum == 1){
Count0++;
element.setAttribute("id","0:" + Count0);
}else if(fooNum == 2){
Count1++;
element.setAttribute("id","1:" + Count1);
}else if(fooNum == 3){
Count2++;
element.setAttribute("id","2:" + Count2);
}else{
alert("Somethin' went wrong, man!");
}
console.log(element.id);
//Assign different attributes to the element.
element.setAttribute("type", type);
element.setAttribute("value", "");
var foo = document.getElementById("fooBar"+fooNum);
//Append the element in page (in <span>).
foo.appendChild(element);
}
function generate(){ //Assign the inputs to a 2D array
var counts = [Count0, Count1, Count2];
hello=counts;
for(k=0; k<=2; k++){
for(i=0; i<=counts[k]; i++){
sounds[k][i] = document.getElementById(k + ":" + i).value;
alert(sounds[k][i]);
}
i = 0;
}
}
</script>
</head>
<body>
<FORM>
<INPUT type="button" value="Add" onclick="add(document.forms[0].element.value, 1)"/><INPUT type="text" name="element" id="0:0"/><span id="fooBar1"> </span><P>
<INPUT type="button" value="Add" onclick="add(document.forms[0].element.value, 2)"/><INPUT type="text" name="element" id="1:0"/><span id="fooBar2"> </span><P>
<INPUT type="button" value="Add" onclick="add(document.forms[0].element.value, 3)"/><INPUT type="text" name="element" id="2:0"/><span id="fooBar3"> </span><P>
<INPUT type="button" value="Generate" onclick="generate()"/><P>
<INPUT type="button" value="Make Name" onclick="makeName()"/><P>
</FORM>
</body>
My guess is that the problem lies within random() or makeName().
Please help! Thank you in advance.
Your makeName function takes argument x:
function makeName(x) {
but you call it like this:
<INPUT type="button" value="Make Name" onclick="makeName()"/>
that's why x is undefined in makeName.
In your html you've called makeName function without any argument
<INPUT type="button" value="Make Name" onclick="makeName()"/><P>
but your function requires an argument
function makeName(x){
alert(x[0][random(x[0].length)] + x[1][random(x[1].length)] + x[2][random(x[2].length)]);
}
So x is undefined in your makeName function.

Adding select menu default value via JS?

i'm developing a meta search engine website, Soogle and i've used JS to populate select menu..
Now, after the page is loaded none of engines is loaded by default, user needs to select it on his own or [TAB] to it..
Is there a possibility to preselect one value from the menu via JS after the page loads?
This is the code:
Javascript:
// SEARCH FORM INIT
function addOptions(){
var sel=document.searchForm.whichEngine;
for(var i=0,l=arr.length;i<l;i++){
sel.options[i]=new Option(arr[i][0], i);
}
}
function startSearch(){
var searchString=document.searchForm.searchText.value;
if(searchString.replace(/\s+/g,"").length > 0){
var searchEngine=document.searchForm.whichEngine.selectedIndex,
finalSearchString=arr[searchEngine][1]+searchString;
window.location=finalSearchString;
}
return false;
}
function checkKey(e){
var key = e.which ? e.which : event.keyCode;
if(key === 13){
return startSearch();
}
}
// SEARCH ENGINES INIT
var arr = [
["Web", "http://www.google.com/search?q="],
["Images", "http://images.google.com/images?q="],
["Knowledge","http://en.wikipedia.org/wiki/Special:Search?search="],
["Videos","http://www.youtube.com/results?search_query="],
["Movies", "http://www.imdb.com/find?q="],
["Torrents", "http://thepiratebay.org/search/"]
];
HTML:
<body onload="addOptions();document.forms.searchForm.searchText.focus()">
<div id="wrapper">
<div id="logo"></div>
<form name="searchForm" method="POST" action="javascript:void(0)">
<input name="searchText" type="text" onkeypress="checkKey(event);"/>
<span id="color"></span>
<select tabindex="1" name="whichEngine" selected="Web"></select>
<br />
<input tabindex="2" type="button" onClick="return startSearch()" value="Search"/>
</form>
</div>
</body>
I appreciate that your question asks for a solution that utilises JavaScript, but having looked at the webpage in question I feel confident in making this point:
Your problem is that you are trying to use JavaScript for something that HTML itself was designed to solve:
<select name="whichEngine">
<option value="http://www.google.com/search?q=" selected="selected">Web</option>
<option value="http://images.google.com/images?q=">Images</option>
<option value="http://en.wikipedia.org/wiki/Special:Search?search=">Knowledge</option>
<option value="http://www.youtube.com/results?search_query=">Videos</option>
<option value="http://www.imdb.com/find?q=">Movies</option>
<option value="http://thepiratebay.org/search/">Torrents</option>
</select>
Fear not, though! You can still access all of the options from JavaScript in the same way that you did before.
function alertSelectedEngine() {
var e = document.getElementsByName("whichEngine")[0];
alert("The user has selected: "+e.options[e.selectedIndex].text+" ("+e.options[e.selectedIndex].value+")");
}
Please, forgive and listen to me.
I have modified the code to use jQuery. It is working fine in IE8, IE8 (Compatibility mode) and in FireFox.
<!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" >
<head id="Head1" runat="server">
<title>Index</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
// SEARCH ENGINES INIT
var arr = new Array();
arr[arr.length] = new Array("Web", "http://www.google.com/search?q=");
arr[arr.length] = new Array("Images", "http://images.google.com/images?q=");
arr[arr.length] = new Array("Knoweledge", "http://en.wikipedia.org/wiki/Special:Search?search=");
arr[arr.length] = new Array("Videos", "http://www.youtube.com/results?search_query=");
arr[arr.length] = new Array("Movies", "http://www.imdb.com/find?q=");
arr[arr.length] = new Array("Torrents", "http://thepiratebay.org/search/");
// SEARCH FORM INIT
function addOptions() {
// Add the options to the select dropdown.
var nOptions = arr.length;
var optionText = '';
for (var i = 0; i < nOptions; i++) {
optionText += '<option value="' + i + '">' + arr[i][0] + '</option>'
}
//alert('optionText = ' + optionText);
// Add the options to the select drop down.
$('select#whichEngine').html(optionText);
// set the second option as default. This can be changed, if required.
$('select#whichEngine option:eq(1)').attr('selected', true);
}
function startSearch() {
var searchEngineIndex = $('select#whichEngine option:selected').attr('value');
searchEngineIndex = parseInt(searchEngineIndex, 10);
var searchString = $('input#searchText').val();
if (searchEngineIndex >= 0 && searchString) {
var searchURL = arr[searchEngineIndex][1] + searchString;
//alert('location = ' + searchURL);
window.location.href = searchURL;
}
return false;
}
function checkKey(e) {
var character = (e.which) ? e.which : event.keyCode;
if (character == '13') {
return startSearch();
}
}
$(function() {
// Add the options to the select drop down.
addOptions();
// Add focus to the search text box.
$('input#searchText').focus();
// Hook the click event handler to the search button.
$('input[type=button]').click(startSearch);
$('input#searchText').keyup(checkKey);
});
</script>
</head>
<body>
<div id="wrapper">
<div id="logo"></div>
<form name="searchForm" method="POST" action="javascript:void(0)">
<input id="searchText" name="searchText" type="text"/>
<span id="color"></span>
<select tabindex="1" id="whichEngine" name="whichEngine"></select>
<br />
<input tabindex="2" type="button"value="Search"/>
</form>
</div>
</body>
</html>
You had some errors in how you handle the <select> values and options. I would reorganize your JavaScript like this:
// SEARCH ENGINES
var arr = [["Web", "http://www.google.com/search?q="],
["Images", "http://images.google.com/images?q="],
["Knowledge", "http://en.wikipedia.org/wiki/Special:Search?search="],
["Videos", "http://www.youtube.com/results?search_query="],
["Movies", "http://www.imdb.com/find?q="],
["Torrents", "http://thepiratebay.org/search/"]];
// SEARCH FORM INIT
function addOptions(){
var sel=document.searchForm.whichEngine;
for(var i=0;i<arr.length;i++) {
sel.options[i]=new Option(arr[i][0],arr[i][1]);
}
}
function startSearch(){
var searchString = document.searchForm.searchText.value;
if(searchString!==''){
var mySel = document.searchForm.whichEngine;
var finalLocation = mySel.options[mySel.selectedIndex].value;
finalLocation += encodeURIComponent(searchString);
location.href = finalLocation;
}
return false;
}
function checkKey(e){
var character=(e.which) ? e.which : event.keyCode;
return (character=='13') ? startSearch() : null;
}
I would also move your onload handler into the main body of your JavaScript:
window.onload = function() {
addOptions();
document.searchForm.searchText.focus();
};
I also made some changes to your HTML:
<body>
<div id="wrapper">
<div id="logo"></div>
<form name="searchForm" method="POST" action="." onsubmit="return false;">
<input name="searchText" type="text" onkeypress="checkKey(event);" />
<span id="color"></span>
<select tabindex="1" name="whichEngine" selected="Web"></select><br />
<input tabindex="2" type="button" value="Search"
onclick="startSearch();" />
</form>
</div>
</body>
You could specify which egine you would like preselected in the engines array like this:
// SEARCH ENGINES INIT
// I've used array literals for brevity
var arr = [
["Web", "http://www.google.com/search?q="],
["Images", "http://images.google.com/images?q="],
["Knoweledge", "http://en.wikipedia.org/wiki/Special:Search?search="],
/*
* notice that this next line has an extra element which is set to true
* this is my default
*/
["Videos", "http://www.youtube.com/results?search_query=", true],
["Movies", "http://www.imdb.com/find?q="],
["Torrents", "http://thepiratebay.org/search/"]
];
Then in your setup function:
// SEARCH FORM INIT
function addOptions() {
var sel = document.searchForm.whichEngine;
for (var i = 0; i < arr.length; i++) {
// notice the extra third argument to the Option constructor
sel.options[i] = new Option( arr[i][0], i, arr[i][2] );
}
}
if your only concern is preselecting an engine onload, don't "over-engineer" it.
var Web = "http://www.google.com/search?q=";
var Images = "http://images.google.com/images?q=";
var Knowledge = "http://en.wikipedia.org/wiki/Special:Search?search=";
var Videos = "http://www.youtube.com/results?search_query=";
var Movies = "http://www.imdb.com/find?q=";
var Torrents = "http://thepiratebay.org/search/";
function addOptions(source){
var sel=document.searchForm.whichEngine;
for(var i=0,l=arr.length;i<l;i++){
sel.options[i]=new Option(arr[i][0], i);
}
}
then insert your argument made onto your body tag to a pre-defined variable. If you want something random, create a new function with your equation for selecting a random variable then load your addOptions(function) within your new function. Then remove addOptions from your body tag.
<body onload="addOptions(Web);document.forms.searchForm.searchText.focus()">

Categories