Im learning Javascript now and I got a question that's been bugging me!
So, all I needed to do here is to type a color on this input box, click the button and change the headline to the color typed only if that typed color is in the array specified in the variable.
My code is half working... it does check if whatever color typed is inside the array, but the alert button pops up each time, is there a way to make the alert pop up only if the color typed isn't in the array please?
Working code: https://codepen.io/anon/pen/ddPWLP
Javascript code:
const myHeading = document.getElementById('myHeading');
const myButton = document.getElementById('myButton');
const myTextInput = document.getElementById('myTextInput');
var colors = ["red", "black", "blue"];
myButton.addEventListener('click', () => {
for (var i=0; i<colors.length; i++){
if (myTextInput.value === colors[i]){
myHeading.style.color = myTextInput.value
} else {
alert("no color")
}
}
});
Don't do it inside the loop. Use a variable to flag when you find a match, and then after the loop check that flag and display the alert accordingly. Try this:
myButton.addEventListener('click', () => {
var found = false;
for (var i = 0; i < colors.length; i++) {
if (myTextInput.value === colors[i]) {
myHeading.style.color = myTextInput.value
found = true;
}
}
if (!found)
alert("no color");
});
By the way, you don't need a loop for that. You can simply use the indexOf() methods. If the value exists in the array, it returns its index, otherwise it returns -1. Try this:
myButton.addEventListener('click', () => {
if (colors.indexOf(myTextInput.value) > -1)
myHeading.style.color = myTextInput.value
else
alert("no color");
});
Related
a beginner coder here (and also my first post).
I was trying to make function that will change the value of a previously defined variable when the checkbox is checked or unchecked. I tried to write this code to see if the checked property of my checkbox is working.
function calc5() {
var check5Object = document.getElementById("check5");
stat5 = check5Object.checked;
console.log(stat5);
}
When i checked the console, it works out like expected. When the checkbox is checked it logs true and when the checkbox is unchecked it logs false on the console like this.
I thought it was working smoothly... until i added the conditionals. The code looks like this:
function calc5() {
var check5Object = document.getElementById("check5");
stat5 = check5Object.checked;
if ((stat5 = true)) {
bobux5 = 10000;
} else {
bobux5 = 0;
}
console.log(stat5);
}
And the result on the console looks like
this
Everytime I click the checkbox, it just logs as "true" all the time. Can someone help me figure it out what went wrong in my code? It will be very helpful!
(btw im making a robux "scam" website that will rickroll you at the end, its harmless)
You need to use == and rather use =
From:
if (stat5 = true) {
bobux5 = 10000;
}
to:
if (stat5 == true) {
bobux5 = 10000;
}
Use this code:
function calc5() {
var check5Object = document.getElementById("check5");
var bobux5 = 0;
stat5 = check5Object.checked;
if (stat5 == true) {
bobux5 = 10000;
}
console.log(stat5);
}
in fact you should use == in conditions. => (if == X TURE) and (if = X FALSE)
thank you for the help in advance! Please forgive me if this is a stupid question as I a JS noobie.
I am trying to cycle through an array of URL's that I have nested inside of an object. What I am expecting to happen is for the url's (which are google maps) to show up on my website and for the person using my website to be able to click back and forth between the different map URL's. Right now what's happening is the last item (a google maps url) of myCities.index is being properly displayed, but when I click my previous and next buttons it is going to a blank page. I have looked at my JS console and there are no visible errors there. Can anyone give me some advice as to how to fix this? My code is as follows.
const myCities = {
index:
[url1, url2, url3]
}
const prevButton = document.querySelector('.prevBtn');
const nextButton = document.querySelector('.nextBtn');
const map = document.getElementById("myCitiesss");
nextButton.addEventListener('click', nextCity);
prevButton.addEventListener('click', prevCity);
function prevCity() {
myCities.index--;
updateSrc();
checkButtons();
}
function nextCity() {
myCities.index++;
updateSrc();
checkButtons();
}
function updateSrc() {
map.src = myCities.index;
}
function checkButtons() {
prevButton.disabled = false;
nextButton.disabled = false;
if (myCities.index === 2) {
nextButton.disabled = true;
}if (myCities.index === 0) {
prevButton.disabled = true;
}
}
updateSrc();
checkButtons();
The problem is you're treating myCities.index as both the container of your data and as a counter (hence you're running incrementation/decrementation operations on it).
The counter should be a separate variable.
const myCities = [url1, url2, url3]; //<-- can now be a flat array
let index = 0; //<-- this is our counter, i.e. tracker
The relevant code changes are then: (I also took the opportunity to demonstrate some optimisations and efficiencies you can make)
nextButton.addEventListener('click', () => nextPrevCity('next'));
prevButton.addEventListener('click', () => nextPrevCity('prev'));
function nextPrevCity(which) { //<-- one function to handle both next and prev
which == 'next' ? index++ : index--;
map.src = myCities[index];
checkButtons();
}
function checkButtons() {
prevButton.disabled = false;
nextButton.disabled = false;
if (index === myCities.length - 1) //<-- check against array length, not fixed number 2
nextButton.disabled = true;
if (!index) //<-- because 0 is a falsy value, so same as "if (index === 0)"
prevButton.disabled = true;
}
[ -- EDIT -- ]
Forgot the following at the bottom of the code:
map.src = myCities[0];
checkButtons();
i'm writing a Firefox Extension. i need listen to changes in some DOM objects and the log them.
a can't find something specific in JavaScript like DOM changing listener.
a have trouble with infinite loop.
function get_values(){
var names = document.getElementsByClassName('X');
var new_names = [];
for (i=0; i<names.length; i++){
if(names[i].innerText==""){
continue
}
new_names.push(names[i].innerText);
}
return new_names
}
function check_values(names){
new_names = get_values()
if (new_names == names){
return 0
}else{
return new_names
}
}
do = true
var names = []
while(do){
new_values = check_values(names)
if ( new_values != 0){
names = new_values
console.log('___________log_____________')
console.log(names)
}
}
without while expression code is running,but with this code i want listen to changes an log it in console.
with while expression i can't see any log in console.
i new to JavaScript(10H)
So I am currently trying to overwrite a value in my multidimensional array.....where I want to overwrite a value based on the position of where channel.name is and change the value of the mute state if you will.
So what I want to do is:
Mute value in array
When I call the function to unmute it, I want to replace the "Mute" Value with "Unmute".
Then do the same Mute and effectively toggle values.
The problem is I am currently always pushing the values on over and over like so: [ [ '1447682617.29', 'SIP/487-0000000b', 'Mute', 'Unmute' ] ]
I simply just want to overwrite Mute and Replace it with Unmute.
I have the index part fine its just being able to overwrite that value.
The code I have so far is:
//ARI function to mute channels.
function mute(mutval,mutestate) {
console.log("Muting:" + mutval);
var index = 0;
var findex = false;
for (var i in channelArr) {
var channelArrEle = channelArr[i];
if (channelArrEle[0] == mutval) {
index = i;
findex = true;
console.log("First Part works!")
}
}
if (findex) {
channelArr[index].push(mutestate);
console.log(channelArr);
} else {
console.log("Error")
}
}
//ARI function to unmute channels which have been muted.
function unmute(unval,mutestate) {
console.log("Unmuting: " + unval);
var index = 0;
var findex = false;
for (var i in channelArr) {
var channelArrEle = channelArr[i];
if (channelArrEle[0] == unval) {
index = i;
findex = true;
console.log("First Part works!")
}
}
if (findex) {
channelArr[index].push(mutestate);
//Just added this to see what would happen!
channelArr[index] = mutestate;
console.log(channelArr);
} else {
console.log("Error")
}
}
Any suggestions no doubt its something minor question is what.
Try change (in both occurence)
channelArr[index].push(mutestate);
with
var channelData = channelArr[index];
channelData[2] = mutestate;
channelArr[index] = channelData;
And if it works, you can try to shorten the code like this
channelArr[index][2] = mutestate;
I have a page where you can invite teams. Clicking "Invite teams" makes a popup box appear showing a search input. The search-function is AJAX based. When a team is found through your search word(s), you'll have to click on the team whereupon the team will be showed in a "Invited-teams"-box.
It works in a way that when you "add" the team, a hidden input field is generated containing the team's ID as a value. The problem is that with my current code, it is possible to add the same team as many times as you wish. I should be possible to check, if the team can be found in the hidden-input-data. If it already exists, it should not be possible to add the sane team.
My current javascript-code can be found beneath here. Please notice that I have tried to make the code that checks the team, but it doesn't work.
function addTeam(tid) {
// Grab the input value
var teamName = document.getElementById(tid).innerHTML;
var teamID = document.getElementById(tid).id;
// If empty value
if(!teamName || !teamID) {
alert('An error occured.');
} else {
//Tried to do the "team-adlready-added"-test, but it doesn't work
var stored_teams = $t('#store-teams').getElementsByTagName('input');
for (var i = 0; i < stored_teams.length; i++) {
var stored_team = stored_teams[i];
if(stored_team.value == teamID) {
break;
var team_already_added = 1;
}
alert(team_already_added);
}
if((team_already_added) || team_already_added != 1) {
// Store the team's ID in hidden inputs
var store_team = document.createElement('input');
store_team.type = 'hidden';
store_team.value = teamID;
// Append it and attach the event (via onclick)
$t('#store-teams').appendChild(store_team);
// Create the teams with the value as innerHTML
var div = document.createElement('div');
div.className = 'team-to-invite';
div.innerHTML = teamName;
// Append it and attach the event (via onclick)
$t('#teams').appendChild(div);
}
div.onclick = removeTeam;
}
return false;
}
Thanks in advance.
I just want to give you a hint for a possible solution without html elements.
You can create a new functional object for team:
var Team = function (id, name) {
this.name = name;
this.id = id;
}
Create an array which will contain teams:
var TeamList = [];
Add you Teams:
TeamList.push(new Team(1, "Team 1"));
TeamList.push(new Team(2, "Team 2"));
TeamList.push(new Team(3, "Team 3"));
TeamList.push(new Team(4, "Team 4"));
Write a function which loops trough the list of teams and checks with the id if a team already exists:
function containsTeam(id) {
for (var i = 0; i < TeamList.length; i++) {
if (TeamList[i].id == id) {
return true;
}
}
return false;
}
Just check it:
containsTeam(1); //returns true
containsTeam(5); //returns false
Have a look at the jsFiddle DEMO and open the console to see the output.
EDIT: In addition, to remove an element you can write a function which looks pretty much the same as the containsTeam function. Just use array.splice instead of returning true:
function removeTeam(id) {
for (var i = 0; i < TeamList.length; i++) {
if (TeamList[i].id == id) {
TeamList.splice(i, 1);
}
}
}
And remove a team:
removeTeam(3);
Your variable scope is off.
You declare team already added in the wrong spot.
Declare it with team name and team id and it will get you in the right direction