Html button stops working after code run - javascript

I am making a game in HTML and JavaScript. I have a button that the user presses to 'run' a command they entered. But, after they have 'connected' to an ip the button no longer works, there is no error in the console. How can I fix this?
var ip = ["192.168.1.1", "192.168.1.2", "192.168.1.3", "192.168.1.4"]
var gip;
var log;
var compname;
var svirus;
var connected = false;
function runcmd() {
var user = document.getElementById('code').value;
if (user == 'clear') {
l1.innerHTML = '';
l2.innerHTML = '';
l3.innerHTML = '';
l4.innerHTML = '';
l5.innerHTML = '';
l6.innerHTML = '';
l7.innerHTML = '';
l8.innerHTML = '';
l9.innerHTML = '';
l10.innerHTML = '';
};
if (user == 'connect') {
gip = prompt('Enter The Targets IP: ');
for (var key in ip) {
var user = document.getElementById('code').value;
if (ip[key] == gip) {
l1.innerHTML = 'Connecting to ' + gip;
l2.innerHTML = 'Connected to ' + gip;
connected = true;
grant.play()
l3.innerHTML = 'view bank';
l4.innerHTML = 'upload [virus]';
l5.innerHTML = 'disconnect [ip]';
var user = document.getElementById('code').value;
if (user == 'disconnect' + gip) {
connected = false;
l1.innerHTml = 'Disconnected Safely...';
};
if (user == 'view bank') {
var pwrd = Math.floor(Math.random() * 10000);
var nam = Math.floor(Math.random() * 10000);
alert(pwrd);
alert(nam);
var uname = 'user' + nam;
var user = prompt('Username: ');
var pass = prompt('Password: ');
if (user == uname && pass == pwrd) {
console.log('hello')
};
if (user == 'upload') {
svirus = prompt('Enter Virus: ');
for (var key in boughtviruses) {
if (boughtviruses[key] == svirus) {
l1.innerHTML = 'Uploading ' + svirus;
l2.innerHTML = 'Virus Uploaded';
}
else {
alert("You Don't Have This Virus!");
};
};
};
};
};
};
};
};
<span class="span" id="l1"></span><br />
<span class="span" id="l2"></span><br />
<span class="span" id="l3"></span><br />
<span class="span" id="l4"></span><br />
<span class="span" id="l5"></span><br />
<span class="span" id="l6"></span><br />
<span class="span" id="l7"></span><br />
<span class="span" id="l8"></span><br />
<span class="span" id="l9"></span><br />
<span class="span" id="l10"></span><br />
<span >C:\></span>
<input onclick="this.select()" id="code" class="inp" />
<button id="runcodeuser" onclick="runcmd()">Send Command</button>

You could create an event dispatcher. Every possible user input would be a separate event.
Separate the code to handle each event into different functions.
For example:
function user_clear () { ... }
function user_connect () { ... }
function user_bank () { ... }
function user_upload () { ... }
function dispatch_event (user)
{
switch (user)
{
case 'clear': user_clear (); break;
case 'connect': user_connect (); break;
case 'view bank': user_bank (); break;
case 'upload': user_upload (); break;
default: console.log ('dispatch_event: no such event: ' + user);
}
}
Then call it from runcmd():
function runcmd() {
var user = document.getElementById('code').value;
dispatch_event (user);
}
And also after running grant.play(): (inside user_connnect())
grant.play();
var user = document.getElementById('code').value;
dispatch_event (user);

Well, in your code only two "commands" are actually usable - clear and connect.
If the command, that is the value of the textbox, is connect, the browser will ask for the "targets IP". It then iterates through the IPs in the array declared at the top, and in each iteration again sets the variable user to the textbox value - but the textbox will still contain connect, and also the user-variable is already declared, so there's no need to user the var keyword again.
Because of this user == "view bank" for example will never evaluate to true. You'll have to restructure your code considerably for this to work as you want it to.

It would appear that your runcmd() function only has 3 blocks:
var user...
if (user=="clear") { ... }
if (user=="connect") { ... }
Everything else is in that last block/line. If user=="connect" is true, then the block executes, but user=="view bank", etc. will never be true.

There's no semicolon after grant.play() - and this function doesn't seem to be defined anywhere inside your code.
Also, for what it's worth, I do get an error message when running the snippet:
{
"message": "Script error.",
"filename": "",
"lineno": 0,
"colno": 0
}

Related

javascript - localStorage - issue with a loop and message to display

In the script below, I try to record in the bowser the name of the users who connect to my application. If it is the first time that a user connects, when he presses the "submit" button to connect to the application I want a message "Welcome" + name + "!
If the user has already connected (his name is already registered in the localStorage), when he presses the submit button, I want a "Welcome back" + name + "!
Thank you for the comments below, I tried to take them into account. When I run the updated code below, only welcome appear on the message. The name of the user is not included on the message. How can I modify my code to correct this problem?
Thank you in advance for your advice.
JS script:
let myButton = document.getElementById ("myButton");
let myText = document.getElementById ("username");
function store() {
let n = 0;
while (localStorage.getItem("username" + n)) {
n++;
}
localStorage.setItem("username" + n, myText.value);
}
function welcomeUsername(){
let resultMessage = "Welcome "
let n = 0;
while (n) {
let user = localStorage.getItem("username" + n);
if(myText.value != user){
resultMessage += myText.value + "!";
break;
} else {
resultMessage += "back" + myText.value + "!";n++;
}
}
alert(resultMessage);
}
HTML Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login Page</title>
</head>
<body>
<br />
<br />
<div class ="login_card"></div>
<div class = "log_head">
<h1>Login</h1>
</div>
<div class = "log_body">
<br />
<label for="uname"><b>Please enter your username below and click on submit:</b></label> <br>
<input type="text" value = "Enter username" onfocus = 'this.value =""' id = "username"> <br>
<br> <br>
<input type="button" onClick="welcomeUsername();location.href ='/index';" value = "Submit" id = "myButton">
</div>
</div>
this part of your code has problem let value = localStorage.getItem("username"). you cant get any value from your localstorage since you set them 'username'+n, that;s why your if statement always run.
can you try this: while (n) {let user = localStorage.getItem("username" + n); if (myText.value == user) {resultMessage += myText.value; break; } else {resultMessage += "back" + myText.value + "!"; n++; }}
Try this.
const btn = document.getElementById('myButton');
// get a welcome message
const welcomeText = (name) => {
// store the name as an array type, initialize if it does not exist
let names = localStorage.getItem('usernames');
names = names == null ? [] : names;
// check if the name exists and decide the welcome message according to the result
if (names.includes(name)) {
return `Welcome back ${name}`;
} else {
// update storage information
names.push(name);
localStorage.setItem('usernames', names);
return `Welcome ${name}`;
}
};
// send name and call method
const submit = () => {
const name = document.getElementById('username').value;
alert(welcomeText(name));
};
btn.addEventListener('click', submit);

How to update JSON query / data after new user input?

I'm creating a weather dashboard that updates every 5 seconds. I would like the user to be able to change the target city, and have the dashboard update with the new data.
Problem is every time they input a new city, the previous data stays and it seems to be looping through all the inputs the user has made so far.
I would like the data to be updated after the user inputs a new city, rather than added. This is my code:
window.onload = function() {
const api_key = "c7eedc2fa8594d69aa6122025212904";
const inputCity = document.getElementById("inputCity");
const getCity = document.querySelector("form");
getCity.addEventListener("submit", e => {
// Prevent the form from submission
e.preventDefault();
var inputVal = inputCity.value;
var api_url = "http://api.weatherapi.com/v1/forecast.json?key=" + api_key + "&q=" + inputVal + "&days=3&aqi=no&alerts=no";
// Get the dataset
function refreshData() {
fetch(api_url).then(response => {
response.json().then(json => {
var dataset = json;
var output = formatResponse(dataset);
})
// Catch error - for example, the user doesn't input a valid city / postcode / country
.catch(error => console.log("not ok")); // TO BE IMPROVED
})
}
refreshData(); // Display the dashboard immediately
setInterval(refreshData, 5000); // And then refresh the dashboard every X milliseconds
});
function formatResponse(dataset) {
console.log(dataset);
// Current temp
var currentTemp = [dataset.current.temp_c];
console.log(currentTemp);
document.getElementById("currentTempDsp").innerHTML = currentTemp + "°";
// Current state icon
var currentIcon = [dataset.current.condition.icon];
console.log(currentIcon);
document.getElementById("iconDsp").src = "http://" + currentIcon;
// Current state text
var currentText = [dataset.current.condition.text];
console.log(currentText[0]);
document.getElementById("currentStateDsp").innerHTML = currentText;
}
}
<form id="getCity" class="search">
<label id="labelCity">Search for a city...</label></br>
<input type="text" id="inputCity" class="inputCity" placeholder="Type city name here...">
<button id="submitCity" type="submit" class="submitCity"><i class="fas fa-search"></i>Submit</button>
</form>
<div class="state">
<h2 id="currentTempDsp"></h2>
<img id="iconDsp"/>
<span id="currentStateDsp"></span>
</div>
</div>
</div>
When you create an interval using setInterval() it continues to execute until the page is reloaded, navigated away from, or explicitly cleared using clearInterval(). Simply setting more intervals will not stop any previous ones from firing.
Use a globally-scoped variable to store the return value of setInterval() - check if it's set in the beginning of your submit event handler and clear it if it is.
A simplified example of how you could get this done:
const locations = [{
temp: 73,
conditions: 'Sunny'
}, {
temp: 22,
conditions: 'Mostly Cloudy'
}];
var currentInterval = null;
const updateTemp = locationData => {
document.querySelector(".number").innerText = locationData.temp;
document.querySelector(".conditions").innerText = locationData.conditions;
console.log(`updated interface with temperature (${locationData.temp}) and conditions (${locationData.conditions}) data`);
}
[...document.querySelectorAll('.add-location')].forEach(button => {
button.addEventListener('click', (e) => {
// clear the interval
if (currentInterval) {
clearInterval(currentInterval);
currentInterval = null;
console.log('cleared currentInterval');
}
updateTemp(locations[parseInt(e.srcElement.dataset.loc)]);
currentInterval = setInterval(function () {
updateTemp(locations[parseInt(e.srcElement.dataset.loc)]);
}, 2500);
});
});
* {
font-family: sans-serif;
}
.temp {
font-size: 2em;
}
.conditions {
font-style: italic;
}
<div class="temp">
<span class="number">--</span>
<span class="deg">°</span>
</div>
<div class="conditions">--</div>
<div>
<button class="add-location" data-loc="0">Add location 0</button>
<button class="add-location" data-loc="1">Add location 1</button>
</div>

Inserting User Input Values into a Function

I am trying to take a user input value that is entered through an html input box, and have it as a value within my function (the negKeyword function in my code to be more specific). The problem that I think is happening is this input value is stored as a variable, so when the code is first stored in memory it is stored as "", since the user has not inputed anything yet. How do I get it so when the user inputs something it replaces blank or "" with what ever the user inputs?
What I basically want to happen next is the user will click a button, it will then compare what the user inputs to what the "negKeyword" function outputs and give a result on whether they match or not (this action is demonstrated in my booleanKeyword function in my code).
Here is my code.
var input = document.getElementById("input").value;
var arr = ['no', 'not', 'checked'];
var text = ''; //JS output variable.
var keyword = 'leak'; //Individual keyword.
function negKeyword() {
for (i = 0; i < arr.length; i++) {
if (text == input) { break; }
text = arr[i] + ' ' + keyword;
}
return text;
}
function booleanKeyword() {
if (input == negKeyword()) {
document.getElementById("result").style.color="green";
document.getElementById("result").innerHTML="Match";
} else {
document.getElementById("result").style.color="red";
document.getElementById("result").innerHTML="No Match";
}
}
document.getElementById("result2").innerHTML=keyword;
<label for="Full Negative Keyword">Negative Keyword</label> <input id="input" type="text" />
<div id="message">Result: <span id="result"></span></div>
<div id="message">Keyword: <span id="result2"></span></div>
<button id="test" onclick="booleanKeyword()">Click to Test</button>
You can retrieve the input's value again, by getting it and assigning to the same variable (but inside the function that is called after the button click).
var input = document.getElementById("input").value;
var arr = ['no', 'not', 'checked'];
var text = ''; //JS output variable.
var keyword = 'leak'; //Individual keyword.
function negKeyword() {
input = document.getElementById("input").value;
for (i = 0; i < arr.length; i++) {
if (text == input) { break; }
text = arr[i] + ' ' + keyword;
}
return text;
}
function booleanKeyword() {
input = document.getElementById("input").value;//The variable is reassigned, only after the click
if (input == negKeyword()) {
document.getElementById("result").style.color="green";
document.getElementById("result").innerHTML="Match";
} else {
document.getElementById("result").style.color="red";
document.getElementById("result").innerHTML="No Match";
}
}
document.getElementById("result2").innerHTML=keyword;
Edit: added the same code to negKeyword() function as it requires the input too.
It is not working because your variable input is always "". You have to assign new value to it each time the button is clicked. I just moved your code for input in BooleanKeyword() function. Now everything is working fine.
Everytime when something like this is not working, just try to log/alert values.
For example you could just alert(input + ' ' + negKeyword()); on top of booleanKeyword() function and you would see problem by yourself.
var input;
var arr = ['no', 'not', 'checked'];
var text = ''; //JS output variable.
var keyword = 'leak'; //Individual keyword.
function negKeyword() {
for (i = 0; i < arr.length; i++) {
if (text == input) { break; }
text = arr[i] + ' ' + keyword;
}
return text;
}
function booleanKeyword() {
input = document.getElementById("input").value;
if (input == negKeyword()) {
document.getElementById("result").style.color="green";
document.getElementById("result").innerHTML="Match";
} else {
document.getElementById("result").style.color="red";
document.getElementById("result").innerHTML="No Match";
}
}
document.getElementById("result2").innerHTML=keyword;
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<label for="Full Negative Keyword">Negative Keyword</label> <input id="input" type="text" />
<div id="message">Result: <span id="result"></span></div>
<div id="message">Keyword: <span id="result2"></span></div>
<button id="test" onclick="booleanKeyword()">Click to Test</button>
</html>

Javascript save , erase and reload input value

I have a problem with my Script. I want to do the following steps in this order:
1. Save the text in the input field.
2. Delete all text in the input field.
3. Reload the same text that was deleted before in the input field.
The problem with my script is that the ug()- function writes undefined in my textbox instead of the string that should be stored in var exput. The alert(exput) however shows me the correct content.
Help would be very much appreciated. And I'm sure there is better ways to do that, I'm quite new to this stuff.
HTML
<textarea id="a" style="width: 320px; height: 200px;"></textarea>
<input type="checkbox" id="remember" onclick="merker();deleter();ug()" />
Javascript
function merker() {
var merkzeug = document.getElementById('a').value;
ug(merkzeug);
};
function deleter() {
if(document.getElementById('remember').checked == true)
{
document.getElementById('a').value = "";
}
else {document.getElementById('a').value = "";
}
};
function ug(exput) {
alert(exput);
document.getElementById('a').value = exput;
};
Your code is calling merker(); deleter(); ug(); in the onclick event, but ug() is already called by merker(). You should be doing this instead:
function merker() {
var merkzeug = document.getElementById('a').value;
deleter();
ug(merkzeug);
};
function deleter() {
if(document.getElementById('remember').checked == true)
{
document.getElementById('a').value = "";
}
else {document.getElementById('a').value = "";
}
};
function ug(exput) {
alert(exput);
document.getElementById('a').value = exput;
};
<textarea id="a" style="width: 320px; height: 200px;"></textarea>
<input type="checkbox" id="remember" onclick="merker();" />
I changed Your Javascript:
function merker() {
merkzeug = document.getElementById('a').value;//global variable without var
ug();//why You use it here? I think only for test. So delete it after.
};
function deleter() {
if(document.getElementById('remember').checked == true)
{
document.getElementById('a').value = "";
}
else {document.getElementById('a').value = "";
}
};
function ug() {
alert(merkzeug);
document.getElementById('a').value =merkzeug;
};
Problems with your code:
method ug was used with argument and without argument ( i changed to without )
to restore deleted value it must be saved to some variable, i saved to global merkzeug variable - this is not good practice but sufficient in this case
next i used merkzeug to restore value in textarea in ug() function
i do not know why You using ug() two times? maybe delete one of them is good thing to do.
In plunker - https://plnkr.co/edit/fc6iJBL80KcNSpaBd0s9?p=info
problem is: you pass undefined variable in the last ug function:
you do: merker(value) -> ug(value); delete(); ug(/*nothing*/);
or you set your merkzeung variable global or it will never be re-inserted in your imput:
var merkzeug = null;
function merker() {
merkzeug = document.getElementById('a').value;
ug(merkzeug);
};
function deleter() {
if(document.getElementById('remember').checked == true)
{
document.getElementById('a').value = "";
}
else {document.getElementById('a').value = "";
}
};
function ug(exput) {
if (typeof exput === 'undefined') exput = merkzeung;
alert(exput);
document.getElementById('a').value = exput;
};

Microsoft Dynamics CRM 2011/2013

In my entity (A) has 50 option set. If the user select 10 optionsset value and not selected remaining one, and he/she click save button. In that situation i need to alert user "To fill all the option set". I don't want to get the Schema name for the optionset individually, i need to get all the option set schema name dynamically.
Is it possible? Help me.
I have not tested this function, but you can try this and make changes if needed.
function IsFormValidForSaving(){
var valid = true;
var message = "Following fields are required fields: \n";
Xrm.Page.data.entity.attributes.forEach(function (attribute, index) {
if (attribute.getRequiredLevel() == "required") {
if(attribute.getValue() == null){
var control = attribute.controls.get(0);
// Cheking if Control is an optionset and it is not hidden
if(control.getControlType() == "optionset" && control.getVisible() == true) {
message += control.getLabel() + "\n";
}
valid = false;
}
}
});
if(valid == false)
{
alert(message);
}
}
Ref: Microsoft Dynamics CRM 2011 Validate required form javascript
Required fields individual alert fire before the on save event. If you wish to prevent the single alert routine for all unfilled option sets you need to remove the requirement constraint and manage the constraint yourself, probably in your on save handler. I’m just writing the idea here (not tested).
// enter all optionsets ids
var OptionSets50 = ["new_optionset1","new_optionset2","new_optionset50"];
var dirtyOptions = [];
function MyOptionSet(id) {
var mos = this;
var Obj = Xrm.Page.getAttribute(id);
var Ctl = Xrm.Page.getControl(id);
Obj.addOnChange(
function () {
if (Obj.getValue() != null)
delete dirtyOptions[id];
else
dirtyOptions[id] = mos;
});
this.GetLabel = function() {
return Ctl.getLabel();
}
if (Obj.getValue() == null)
dirtyOptions[id] = mos;
}
function OnCrmPageLoad() {
for(var x in OptionSets50) {
OptionSets50 [x] = new MyOptionSet(OptionSets50 [x]);
}
Xrm.Page.data.entity.addOnSave(OnCrmPageSave);
}
//check for dirty options and alert
function OnCrmPageSave(execContext) {
var sMsg = "The following Optinsets Are Required: ";
var sLen = sMsg.length;
for(var os in dirtyOptions) {
sMsg += dirtyOptions[os].GetLabel() + "\n";
}
if (sMsg.length > sLen) {
execContext.getEventArgs().preventDefault();
alert(sMsg);
}
}

Categories

Resources