Javascript var name counting variable - javascript

I have the following bit of code:
function finalCheck(theForm) {
var z = 0;
for(var i=0;i<15;i++){
var _i = theForm.elements[i].value;
if(_i == ""){
theForm.elements[i].style.background = '#FFD6D6';
z = 1;
}
}
if(z == 1){
alert("Please correct the fields highlighted in red");
return false;
} else {
return true;
}
}
What I was attempting to do was set the name of var _i to var _ and then the index that the counting variable was currently on. For example, _1 _2 _3 etc. Any way to do this?

So I under stand what you are trying to do, and your solution is to use eval
eval("var _" + i + "= theForm.elements[i].value;");
Anyways your code doesn't need any dynamic generation of variable names as var _i is a local variable.
I hope you are asking this question for learning purpose.

Related

Bucket Sort JavaScript

I am having trouble implementing a search engine for my webpage in JavaScript. Firstly, I have an array[strings] of classnames. With the classnames I want to do a bucketsort with buckets namely a-z, so a bucketSize[a-z]. Once I detect the first letter of the classname[i] I place it in the correct bucket. That is my first function classSort().
Then next I want to be able to read an input from HTML tag and search the buckets with the first letter and return it. I am having trouble creating a for loop that run through the bucket and return every string with the letter that the user typed. I am still fairly new to programming and im trying to challenge by self to built a website, but i keep getting stuck on the searching of the webpage. This is my code so far.
let classNames;
let bucketSize;
function classSort(classNames, bucketSize){
//empty check
if(classNames.length === 0){
return classNames;
}
//initialize buckets
var bucketSize = new Array();
for (var aToz = 'a'; aToz <= 'z'; aToz++){
bucketSize.push(new Array());
}
//Detect first letter of each ith String and put it in the right bucket
for ( var i = 0; i <= classNames.length; i++){
for (var aToz = 'a'; aToz <= 'z'; aToz++){
if (className[i].startsWith(String.valueOf(aToz)){
bucketSize.find(aToz).push(classNames[i]);
}
}
}
function classSearch(inputSearch){
document.getElementById("submit").onsubmit = function()
inputSearch = document.getElementById("search").value;
if (inputSearch === ""){
return ("Nothing was typed!")
}else{
for (var aToz = 'a'; aToz <= 'z'; aToz++){
if (inputSearch.startsWith(String.valueOf(aToz)){
//for (var i = 0; i <= )
bucketSize.find(aToz).pop(classNames[i]);
}
}
}
}
Any help is greatly appreciated. THANKS!!!!

Make field required based on dropdown

I'm hoping for some help getting around an issue I just can't seem to solve.
I need to make a field required based on a value of "new" in a select box. I have googled, and looked at some questions here, but can't seem to get it to work in my case.
Here's my current code, which doesn't quite seem to work - I keep getting undefined for dd, and for the builder fields.
function selection() {
alert("got in");
var x;
var number_of_input = $("#formtable select").length;
alert(number_of_input);
for (var i = 1; i < number_of_input; i++) {
if (i > 1) { x = (i * 9) + 5; }
else { x = 14 };
alert(x);
var name = "vnew_or_resold" + x;
var sel = document.getElementById(name);
var opt = sel.options[sel.selectedIndex];
var dd = opt.text;
alert(dd);
var builder = "vbuilder_name" + (x + 1);
alert(builder);
var build = builder.val();
alert(build);
if (dd == "new") {
if (build == "") {
alert('Mandatory');
return false;
}
}
}
return true;
}
I have include the "alerts" because I need to see the values that are being inputted.
Also, the values of x in the for loop work...there are six static fields then 9 static in a table, and 9 in an unlimited number of dynamic rows. The x is reading the correct rows - that I know for sure. My problem really starts with the section starting at
var sel = document.getElementById(name);
Additionally, it's not actually going through all the dynamic rows, probably because either true or false are being registered - but I'm not sure.
I appreciate any help in advance.

indexOf() : is there a better way to implement this?

EDIT
Thank you guys, and i apologize for not being more specific in my question.
This code was written to check if a characters in the second string is in the first string. If so, it'll return true, otherwise a false.
So my code works, I know that much, but I am positive there's gotta be a better way to implement this.
Keep in mind this is a coding challenge from Freecodecamp's Javascript tree.
Here's my code:
function mutation(arr) {
var stringOne = arr[0].toLowerCase();
var stringTwo = arr[1].toLowerCase().split("");
var i = 0;
var truthyFalsy = true;
while (i < arr[1].length && truthyFalsy) {
truthyFalsy = stringOne.indexOf(stringTwo[i]) > -1;
i++
}
console.log(truthyFalsy);
}
mutation(["hello", "hey"]);
//mutation(["hello", "yep"]);
THere's gotta be a better way to do this. I recently learned about the map function, but not sure how to use that to implement this, and also just recently learned of an Array.prototype.every() function, which I am going to read tonight.
Suggestions? Thoughts?
the question is very vague. however what i understood from the code is that you need to check for string match between two strings.
Since you know its two strings, i'd just pass them as two parameters. additionally i'd change the while into a for statement and add a break/continue to avoid using variable get and set.
Notice that in the worst case its almost the same, but in the best case its half computation time.
mutation bestCase 14.84499999999997
mutation worstCase 7.694999999999993
bestCase: 5.595000000000027
worstCase: 7.199999999999989
// your function (to check performance difference)
function mutation(arr) {
var stringOne = arr[0].toLowerCase();
var stringTwo = arr[1].toLowerCase().split("");
var i = 0;
var truthyFalsy = true;
while (i < arr[1].length && truthyFalsy) {
truthyFalsy = stringOne.indexOf(stringTwo[i]) > -1;
i++
}
return truthyFalsy;
}
function hasMatch(base, check) {
var strOne = base.toLowerCase();
var strTwo = check.toLowerCase().split("");
var truthyFalsy = false;
// define both variables (i and l) before the loop condition in order to avoid getting the length property of the string multiple times.
for (var i = 0, l = strTwo.length; i < l; i++) {
var hasChar = strOne.indexOf(strTwo[i]) > -1;
if (hasChar) {
//if has Char, set true and break;
truthyFalsy = true;
break;
}
}
return truthyFalsy;
}
var baseCase = "hello";
var bestCaseStr = "hey";
var worstCaseStr = "yap";
//bestCase find match in first iteration
var bestCase = hasMatch("hello", bestCaseStr);
console.log(bestCase);
//worstCase loop over all of them.
var worstCase = hasMatch("hello", worstCaseStr);
console.log(worstCase);
// on your function
console.log('mutation bestCase', checkPerf(mutation, [baseCase, bestCaseStr]));
console.log('mutation worstCase', checkPerf(mutation, [baseCase, worstCaseStr]));
// simple performance check
console.log('bestCase:', checkPerf(hasMatch, baseCase, bestCaseStr));
console.log('worstCase:', checkPerf(hasMatch, baseCase, worstCaseStr));
function checkPerf(fn) {
var t1 = performance.now();
for (var i = 0; i < 10000; i++) {
fn(arguments[1], arguments[2]);
}
var t2 = performance.now();
return t2 - t1;
}

How to pass an array through Javascript Function Arguments

I have found a couple other similar threads on stackoverflow (Pass Array Thread 2) and (Pass Array Thread 1) as well as from a few other sites but I either did not understand them, they did not fully answer my question, or I did not know how to implement it into my code.
I have the following code which should create a map for a game based on some arrays:
function createMap(level) {
var map = document.getElementById('map');
mapWidth = parseInt(level[0]);
mapHeight = parseInt(level[1]);
map.innerHTML = '';
rowNumber = 1;
tileID = 1;
var consoleHelp = level[7];
console.log(k+' and value is '+consoleHelp);
k = 1;
for (k = 1; k <= mapHeight; k++) { // repeat below loop until specified height is reached
for (k = 1; k <= mapWidth; k++) { // create a row of tiles based on the specified width of the array
console.log('Row '+k+' created')
if (rowNumber == 1) {
k++;
}
else {
k--;
}
if (level[k] == 'w') {
map.innerHTML += '<span id="'+rowNumber+'-'+tileID+'">desert<image class="tiles" src="desert.png"></span>';
}
else if (level[k] == 'g') {
map.innerHTML += '<span id="'+rowNumber+'-'+tileID+'"><image class="tiles" src="grass.png"></span>';
}
else {
console.log('crap dis did not work');
var consoleHelp = level[k];
console.log(k+' and value is '+consoleHelp);
}
if (rowNumber == 1) {
k--;
}
else {
k++;
}
tileID++
}
rowNumber++
level = level + '_1';
map.innerHTML = "<br>";
}
spawnTile();
}
and the variable arrays (incomplete but you get the idea):
var map_beginning_1 = ['20','10','w','w','w','w','w','w','w','w','w','w','w','w','w','w','w','w','w','w','w','w'];
var map_beginning_1_1 = ['w','g','g','g','g','g','g','g','g','g','g','g','g','g','g','g','g','g','g','w'];
My problem is that I call in
createMap('map_beginning_1')
and nothing happens. There's no errors but nothing else happens. I did a test to see what it was getting and the value of "level[7]" is "i" and "level1" is "a", which is the location of the characters in "map_beginning_1". Can someone please explain to me how to or if it's even possible to variably pass an array through a Javascript function argument and how to do it? And if it isn't possible, can you suggest any alternatives for what I'm trying to do? Javascript is preferable but I can use Jquery if I must.
You have passed a string into the function and not a variable please try the following, removing the single quotes.
createMap(map_beginning_1);
Try createMap(map_beginning_1). Lose the ' (quotes), as you are trying to pass an array but are actually passing a string.

Online quiz with radio buttons having same name

I'm making a simple Quiz using Js, the problem is that my inner loop (i.e i) is not works as expected.
I have taken 3 questions and each question has 3 radio options, options of each question have same name. all the options of fist question have name='cap', options of second question name='an' and third question is name='lang'.
My js function is as follows:
function my(){
var count=0;
var totalQuestions = 3;
var correctAnswers = 0;
var alertText;
var n=["cap","an","lang"];
var j,i;
for(j=0; j<n.length; ++j){
var x = document.getElementsByName('n[j]');
for(i = 0; i < x.length; ++i){
if (x[i].checked){
if (x[i].value == 'true'){
count=count+10;
correctAnswers++;
break;
}
}
}
}
if(correctAnswers == totalQuestions){
alertText = "Congratulations! You got all the questions right!";
}
else {
alertText = "You got " + correctAnswers + " correct answers and score is " + count;
}
alert(alertText);
}
Replace line
var x = document.getElementsByName('n[j]');
to
var x = document.getElementsByName(n[j]);
That's problem because for js getElementsByName('n[y]') means "get elements with name n[y]", but not item of list n, which contain name of elements you need to select.
Good Luck !
var x = document.getElementsByName('n[j]');
Should be
var x = document.getElementsByName(n[j])
getElementsByName returns all elements that match the name per docs.
The issue is you hardcoded the string 'n[j]' so its looking for all elements with the name 'n[j]'.
You actually want to look up the name from y our array n at index j So removing the quotes will actually evaluate that expression n[j]
Change your code from
var x = document.getElementsByName('n[j]');
To
var x = document.getElementsByName(n[j]);
Your existing code tries to find a element which has name='n[j]'ie: a string. But what you want is to evaluate the expression get the element with the name equal to evaluated value.

Categories

Resources