How to change prompt responses to input boxes in JavaScript and HTML - javascript

Long Detailed Question
I put a part of my code below. It is a small javascript game I am working on. When the game wants to know something, or take an text input from the user, I use the prompt command, which as you probably know brings up an alert box that displays some text and lets the user submit a text response. I want to know how I can change it, so instead of an alert box that pops up there is just a input box on the screen that takes their text response. I assume the code needed would either be JQuery(which I do not have much experience in) or JavaScript.
Short Summarized Question
So in summary I want to know how I can make an input box that takes text inputs similar to how a prompt alert does<<<
Code
var finishAnt = prompt(
"you can either risk your life and finish him, or try to run away. Do you finish him?").toLowerCase()
if (finishAnt == "yes") {
console.log("congratulations you have killed the aint eater!")
} else if (finishAnt == "no") {
console.log(
"You run away and barley make it, you are badly hurt");
} else {
console.log("sorry thats not an option")
}
} else if (meetAnt == "no") {
console.log(
"You run past the ant eater and get to saftey. You are very lucky")
} else {
console.log("Sorry that is not an option.")
}

Either you can use Jquery for this, or you can use document.getElementsByTagName('input').value, assign it to a variable, and act accordingly. Like if the user selects yes to the first, the value of the input box will be set to the boolean: true or a string: yes. Then take those values and display a message based on the results.

There is no way to translate this code directly. You will need to make some significant changes to your code to support it.
The alert(), prompt() and confirm() Javascript functions are unique in that they block execution of scripts until the dialog is dismissed. Essentially all other methods in Javascript, including DOM methods that allow you to manipulate and respond to events in a HTML page, are all non-blocking — that is, they must execute immediately, and cannot wait for an event to occur.
To rework this code to run within a page, you will need to reformulate it as a state machine. This will entail keeping track of what state your game is in at any given point and responding appropriately to events based on that state. For instance, you might write a part of your game as:
var state;
function print(msg) {
document.getElementById("output").innerText = msg;
}
function takeInput() {
var input = document.getElementById("input").value;
if (state == "which-door") {
if (input == "left") {
print("You open the left door and fall into a bottomless pit. What now?");
state = "bottomless-pit";
} else if(input == "right") {
print("You open the right door and find yourself lost outdoors...");
state = "outdoors";
} else {
print("That isn't a door. Which door do you open?");
state = "which-door";
}
} else if (state == "bottomless-pit") {
print("You're still falling down a bottomless pit...");
state = "bottomless-pit";
} else if (state == "outdoors") {
print("Now you're back at those two doors again. Left or right?");
state = "which-door";
}
// ... etc ...
});
// Make the "go" element call the takeInput() method when clicked
document.getElementById("go").addEventListener("click", takeInput);
// Start out in the "which-door" state and display an introduction:
state = "which-door";
print("Do you open the left door or the right door?");
<div id="output"></div>
<div>
<input id="input" size="40">
<button id="go">Go</button>
</div>
See the basic framework of this code? At each step, you're taking the current state and input into account, and using those to decide how to respond (by calling print(), typically), and what state to enter next.
(Note that this structure means that it's much easier to introduce logical loops into your game, as it's no longer necessary to represent them as control structures. For instance, the "bottomless-pit" state in this example loops back to itself, and the "outdoors" state loops back to the "which-door" state.)

I don't think you can modify JS presets, but you can make mockups of them in Visual Basic (TEXT/VBSCRIPT)

Try using CSS to make a fake popup. That'll make it look real. Or embed a PNG. But be warned. Embedding a PNG could result in the user dragging it and finding out it's fake. Try using Animate.CSS to let it pop up in the Windows fashion.

Related

Can Angular/TS promises cause out of order execution?

We have an Angular application which was written for us and we're trying to figure out a specific problem (see below for my voluminous essay). Basically, it's a system where some digital input is supposed to control both the backlight and the page that's displayed. If the digital input is on, the backlight should also be on, and the app should work normally, allowing user interaction.
However, without that digital input signal, the application should give a blank page and turn off the backlight so that the user sees nothing and cannot interact with a real page in some blind fashion.
The backlight is controlled by a back end process, which also deliver information to the front end (both of these run on the same device) using Angular routing. But the decision as to what's displayed on the web page is totally under the control of the front end.
We're seeing a situation where, if the digital input is toggled off and on quickly, we sometimes get the backlight on but with a blank page and I'm wondering whether there's some sort of race condition in the delivery of event through the router.
In terms of code, we have an effect which monitors the digital input signal from the back end (not directly) that looks something like:
#Effect({ dispatch: false })
receiveDigitalInputEvent$ = this.actions.pipe(
ofType(AppActionTypes.RECEIVE_DIGITAL_INPUT),
map((action: AppActions.ReceiveDigitalInput) => action.payload),
withLatestFrom(this.store.pipe(select(getRouterState))),
tap(([data, routerState]) => {
const currUrl = routerState ? routerState.state.url : '';
const { isDigitalInputSet, someOtherStuff } = data;
this.forceNavigateIfNeeded(isDigitalInputSet, currUrl);
})
);
forceNavigateIfNeeded(isDigitalInputSet: boolean, currUrl) {
if (isDigitalInputSet && currUrl.endsWith('/blank')) {
this.router.navigateByUrl('/welcome');
else if (! isDigitalInputSet && ! currUrl.endsWith('/blank')) {
this.router.navigateByUrl('/blank');
}
}
What this basically does is, on digital input event arrival:
if the input is on and the screen is currently blank, go to the welcome screen; or
if the input is off and you're not currently on the blank screen, go to the blank screen.
Now, this works normally, it's just the quick transitions that seem to be causing a problem.
I don't have that much knowledge of the Angular internals but I assume the incoming events are being queued somehow for delivery via the routing mechanism (I believe the back end pushed through stuff via web sockets to the front end).
I've looked into the Angular source and noticed that the navigateByUrl uses promises to do its work so the code may return to get the next message queue item before the page is actually changed. I just wanted someone with more Angular nous to check my reasoning or let me know if what I'm suggesting is rubbish. As to what I'm suggesting:
The digital input goes off and a message (OFF) is queued from the back end to the front end. The back end also turns off the backlight.
The digital input goes on again quickly and a message (ON) is queued from the back end to the front end. The back end also reactivates the backlight.
The front end receives the OFF message and processes it. Because we've gotten an OFF message while not on the blank page, we call navigateByUrl('/blank') which starts up a promise.
Before that promise can be fulfilled (and the routerState.state.url changed from non-blank to blank), we start processing the ON message. At this stage, we have an ON message with a (stale) non-blank page, so forceNavigateIfNeeded() does nothing.
The in-progress navigateByUrl('/blank') promise completes, setting the page to blank.
Now we seem to have the situation described as originally, a blank page with the backlight on.
Is this even possible with Angular/Typescript? It seems to rely on the fact that messages coming in are queued and are acted upon (in a single threaded manner) as quickly as possible, while front-end navigation (and, more importantly, the updated record of your current page) may take some time.
Can someone advise as to whether this is possible and, if so, what would be a good way to fix it?
I assume it's a bad idea to wait around in forceNavigateIfNeeded() for the promise to complete, but I'm not sure how else to do it.
Although your problem is quite complex I can see a suspicious code which might be worth inspecting.
...
withLatestFrom(this.store.pipe(select(getRouterState))),
...
This might be the cause of your issue because it's taking what's there, what's latest. It doesn't request the update nor does it wait for it. We had similar issue where also milliseconds were in play and I came up with the workaround, where I replaced withLatestFrom with switchMap operator. I'm not sure if it works in your case but you can give it try.
map((action: AppActions.ReceiveDigitalInput) => action.payload),
switchMap(data => //data === action.payload
this.store.select(getRouterState).pipe(map(routerState => ({ data, routerState }))
),
tap(({data, routerState}) => { ... }
EDIT:
In our case we used a custom selector in the switchMap, which compares current and previous state and returns comparison result. Honestly I'm not 100% sure if that would also help you but it's a necessary piece of a puzzle in our case.
export const getFeshRouterState= pipe(
select(getRouterState),
startWith(null as RouterStateInterface),
pairwise(),
map(([prev, curr]) => /* do some magic here and return result */),
);
Sorry for initial confusion.

Easiest way of remembering user locale selection in HTML

I've been working on a website of mine for about a week now. I'm very good with HTML and CSS, but I'm still trying to wrap my head around Javascript, JQuery and PHP.
Basically, what I'm trying to do is create a way if remembering the users language and locale based on their selection on a language selection page. What I'd like (if possible), is for a user to select their flag on a /locale page and make that change the url of the homepage (ie. mysite.com/en-us). I'm going to be translating my website content via static pages, not active translation.
This only has to work for the homepage, not subsequent pages, however it would be awesome if it did work for pages under different directories too. You can view a live example of my newly constructed website here.
I'd prefer Javascript or JQuery, but honestly - when someone else is doing the hard part, I don't really have the right to be picky.
Thank everyone very much in advance for any assistance.
There's two ways to achieve this: Cookies or localStorage. The easiest one is localStorage:
Here's two plain Javascript functions. The first runs onbodyload and check if the previous language choice (stored in the localStorage) was Spanish. If not (or blank), the welcome appears in English.
When you click a button, it runs the second function which changes the welcome language plus stores the choice in the localStorage.
HTML
<button onclick="language('en')">english</button>
<button onclick="language('spa')">spanish</button>
<h1><span id=welcome>text</span></h1>
JAVASCRIPT
document.getElementsByTagName("body")[0].onload=function(){session()};
function session() {
var result = localStorage.getItem("session");
if (result === 'spa') {
document.getElementById("welcome").innerHTML = "Hola!";
} else {
document.getElementById("welcome").innerHTML = "Hello!";
}
}
function language(key) {
if (key === 'en') {
document.getElementById("welcome").innerHTML = "Hello!";
localStorage.setItem("session", "en");
} else if (key === 'spa') {
document.getElementById("welcome").innerHTML = "Hola!";
localStorage.setItem("session", "spa");
}
}
Codepen DEMO

Input objects not shared across html files

I'm using jsPsych in behavioral research. The developer of that library is very helpful, yet also busy, so I wanted to try and see if the stack overflow community could help me out with a more general js problem :)
In the instance where I'm getting issues, I push objects into an empty array to update the site after input. In this particular case, I use a script that allows me to use external html pages. My problem is, that, while this function here works in order to correctly display a java prompt when assessing a checkbox
var check_consent = function(elem) {
if ($('#consent_checkbox').is(':checked')) {
return true;
}
else {
alert("If you wish to participate, you must check the box next to the statement 'I agree to participate in this study.'");
return false;
}
return false;
};
this here doesn't work in order to assess a text box
var inp = $("#ctry_box").val();
var check_sociodemo = function(elem) {
if ($.trim(inp).length > 0) {
return true;
}
else {
alert("Please fill out the form.");
return false;
}
return false;
};
More specifically, the prompt does actually work, but no matter what you type into "ctry_box", you can't continue the page and the prompt is shown no matter what the input.
Further, the developer set "data" as a object property designed to store data in accordance with individual variable choices. Regarding the same html files, I would like to gather the input from another text box like this
var sociodemo_block = {
type: 'html',
pages: [{url: "text/sociodemo.html", cont_btn: "end", check_fn: check_sociodemo}],
data: [{age: age_box.value}],
force_refresh: true
If I run this, the console tells me that age_box is not defined. Yet again, #consent_checkbox did work. Am I missing something fundamentally here or are the variables simply not shared across the files properly?
I'm very thankful for any help!

Meteor helper adds appropriate css for a brief second and then disappears

I am attempting to show a certain class if a user clicked the right answer or wrong answer through the {{checkAnswer}} helper below:
<div class="question" {{attributes}}>
A
{{answerOne}}
</div>
A user submits an answer which creates a submission, and then ultimately that user submission is checked to see if it is correct. If the user submission is correct it should display btn-success, incorrect should be btn-danger, and else should be btn-primary.
Template.questionItem.helpers({
checkAnswer: function() {
var user = Meteor.user();
var game = GameCollection.findOne({current: true});
var currentQuestion = game.currentQuestion;
var question = game.gameQuestions[currentQuestion];
var correctAnswer = question.correctAnswer;
var submission = Submissions.findOne({userId: user._id,
gameId: game && game._id,
currentQuestion: currentQuestion});
if (submission && submission.submission === correctAnswer) {
return 'btn-success';
} else if (submission) {
return 'btn-danger';
} else {
return 'btn-primary upvotable'
}
},
When I click a correct submission it turns green from btn-success for a fraction of a second (and if incorrect it turns red for a fraction of a second) but then ultimately goes to btn primary. Why does it not stay btn-success (or btn-danger)?
Something in the context is changing. Meteor data contexts are built in such a way that all the 'current' checking you're doing isn't necessary. You can instead access the current data context using this, which will significantly simplify your code.
I'd start by checking if the submission is correct or not on the server side, and then storing that as a property of the submission itself. Then, you can do a simple if...then to return the correct bootstrap class name.
Here's a simple example: meteorpad
And if you want the JS files to quickly put into a brand new project, here's a Gist.
You'll notice in both of those how you can use this._id or this.correct to access the correct/current data context. Hope that helps / gets you on the right track.

Force a SaveForm in Dynamics CRM 2011 using JavaScript

In CRM 2011, I want to be able to force a save of a form. My requirement is as below.
When the user opens the form, I check if a particular field is empty or not.
If it is empty, I want to force a save, thereby triggering a plugin which will set the field.
My current code is as below. This is in the FormOnLoad function which is associated with LoadForm.
if(checkfield == null){
Namespace.Functions.Contact.FormOnSave();
}
else{
// do nothing.
}
Now, this fails with the following line
Can't execute code from a freed script.
I have no clue as to how to proceed further. As a temporary fix, what I have done is the following
if(checkfield == null){
setTimeout('Namespace.Functions.Contact.FormOnSave()',4000);
}
else{
// do nothing.
}
Any advice on why this is happening and how can I fix it without the timeout would be really helpful?
I have had a look at this question and this, but in my case the form does get loaded or has it actually not yet loaded?
Either way, how can I force a save of a CRM form?
You can save the Form by using:
parent.Xrm.Page.data.entity.save();
But It will only trigger if
(Xrm.Page.data.entity.getIsDirty() == true)
However there is a workaround to set IsDirty property true.
Run the Javascript function on PageLoad. Try to update the value of the field which you are planning to populate through plugin:
For e.g.
function OnPageLoad()
{
var yourField = Xrm.Page.getAttribute("new_yourfield").getValue();
if(yourField == null)
{
parent.Xrm.Page.getAttribute("new_yourfield").setValue("any value");
parent.Xrm.Page.getAttribute("new_yourfield").setSubmitMode("always");
parent.Xrm.Page.data.entity.save();
}
}
You could skip all of this mumble jumbo with loading your form twice with Javascript by creating a plugin registered on the read or the entity. (Or better yet and if possible, on the Create of the entity)
The Plugin would just check for the field, and if it's empty, perform whatever logic you need it to to update the field, then save it, and return the updated field (or possibly just populate the value and don't update the database until the user performs the save)

Categories