I'm pretty new to Javascript, so I figured I'd start on a Text Based Game to start out. What I need to do, is to be able to detect when the game is waiting for a command, and when the game is waiting for an answer. Here's what I've got.
var textIn = document.getElementById('input-textbox');
var textOut = document.getElementById("output-textbox");
function process(input) {
var command = input.split(" ")[0];
if(command == "help") {
return "Help dialog";
}else{
return "Unknown command: " + input + ". Please type /help for a list of commands.";
}
}
function go() {
var input = textIn.value;
textIn.value = "";
output(process(input));
}
function output(text){
textOut.value += text + "\n";
}
function createPlayer(){
output("Please Type Your Name")
// Wait for player response and set it as a variable.
}
createPlayer();
What would be the best way to implement this?
You have a few options, you could use onclick and have a button that the user clicks and then call your functionality to fill in the answer for your HTML answer (id="output-textbox" in your example)<-- My vote *.
... or you could choose to check on which element is focused or if tab/enter is hit while in the input box and then put your answer field after the tab/enter is hit. I think the latter method, you should have a HTML5 placeholder attribute to say "hit tab{enter} when finished" or something along those lines and then check for the tab while focused on the element -- this could be accomplished with jQuery selectors or override the current focus method for that input element or potentially use document.activeElement to see what is focused on and then if it is the answer that is focused on and the input isn't blank fill it in, etc, etc, etc.
*If you are new to Javascript, I say have two buttons (one labeled 'answer' and one labeled 'clear'), and then use the onclick attribute for HTML button elements to call a Javascript method easily. This will get you started and be more straightforward, double check what you have works for DOM manipulation and move forward to having less buttons and more sleek DOM manipulation.
Good luck!
A very simple implementation is to use a form with a submit listener that cancels submission if all goes to plan. A user can enter text into the input and see the result in the textarea.
The textarea is disabled so users can't enter text into it but script can. Users can enter input then just press enter, or tab to the submit button and press enter, or click the submit button. The script runs on submit, and cancels it so they stay on the same page.
If scripting is disabled, the form will submit and you can handle things at the server.
<form onsubmit="go(); return false;">
<input id="input-textbox">
<textarea id="output-textbox" rows="20" cols="50" disabled></textarea>
<input type="submit" value="Ask question">
</form>
Related
I'm using UserWP plugin in Wordpress and on my registration page I have the form and the button which says "Submit Query" - not the best text. I'd much rather have "Register".
There's no option in the settings to change the button text so trying to utilise another method.
The HTML string for the button is:
<input type="submit" name="uwp_register_submit" class="form-control btn btn-primary btn-block text-uppercase uwp_register_submit">
So there is no "value" for the text.
My aim is to "inject" the value="Register" into the HTML string. I believe this can be done with a JavaScript snippet, but not being the best at JS, I'm struggling to achieve it.
Lots of googling found some JS code that finds a text string in the identifier and replaces it, however I cannot seem to get this working.
const button = document.querySelector('input');
button.addEventListener('click', updateButton);
function updateButton() {
if (button.value === '') {
button.value = 'Register';
}
}
I realise this would only take effect on click, so when the button is pressed. So tried something like:
const button = document.querySelector('input');
if (button.value === '') {
button.value = 'Register';
}
Again, no success.
And I also saw something about using jquery? So tried the following without success.
$('.btn').val('Register');
I simply want to target the class of the button and tell it to give a value of "Register" - I bet it's an easy solution for someone, but not me...
In general you can achieve that by getting the element and setting the value as you try.
But the line document.querySelector('input'); gives you back the first matching element back. See MDN Document.querySelector
So if there are more than one input fields, it will take the first input, which may not be your submit input.
An alternative would be to search for the specific name of the input field.
document.addEventListener("DOMContentLoaded", function(event) {
document.querySelector("[name='uwp_register_submit']").value = "Register";
});
If that field exists multiple times, use querySelectorAll and combine it with an loop.
In your specific case it would maybe the better way to change the default translation for english. Have a look at the documentation. It looks more complicated as it is.
This is a rather long question, as I've tried to include as much detail as I could. If you'd like to skip to the actual question, please see the very last paragraph.
I'm attempting to write a bot to take commands to roll a die like /r 1d20+2, evaluating, and sending the response in Javascript within a chat box on the website streamyard.com (as that's what my DM is using to stream D&D).
What I'm having trouble with is "typing" into the textarea field. Here's the HTML of the chat box on the page:
<div class="Chat__Wrap-eYhJOs AJLtK">
<ul class="Chat__Comments-dUewnW eqLtEG">
<li class="Comment_Wrap-lbwIWt klCgOs">
<div class="Comment_TextWrap-hSuVQ gHYXCH">
<p class="Text__StyledText-guhEiE bLDoWl" color="default">test</p>
</div>
</li>
</ul>
<form class="ChatInput__Form-eqBCnG iHgCda">
<div class="ChatInput__InputWithSmallGutter-fOaQzB dEaxxd Input__Wrap-kXBxwI iUPDqt">
<label>
<textarea class="sc-bdVaJa eFZRmf"></textarea>
</label>
</div>
<button class="Button_Wrap-ivpgWU dSirvr ButtonBase__WrapperButton-bsASeg cylsQk" type="submit" color="primary">
<span class="Button__InnerSpan-iZsIhM jVWFud">Send</span>
</button>
</form>
</div>
I'm able to get a handle to the text area with the following:
var textbox = document.getElementsByClassName("sc-bdVaJa eFZRmf")[1];
And I can insert text into it with the following:
textbox.value = 'test';
textbox.innerText = 'test';
Which causes the textarea to show the value (in this case "test") as being typed in (specifically the textbox.value command does this). However, when I go to "send" the message by using the following:
var button = document.getElementsByClassName("Button__Wrap-ivpgWU dSirvr ButtonBase__WrapperButton-bsASeg cylsQk");
button[1].click();
It doesn't send the chat message that I've "typed" in. It sends nothing at all and doesn't even clear out the textarea as if the button were clicked. Furthermore, if I manually click the button, the same thing happens. Now, if I manually click in the textarea and type anything into it, such as adding a space after the text I programmatically inserted into it, then execute the code above to click the button, it will send the message.
So, this makes me think that there's something it's detecting when the keyboard presses a button that I'm not accounting for by just setting the textarea value. After some Googling, I've found about triggering the onchange event. So, I've tried the following:
if ("createEvent" in document) {
var evt = document.createEvent("HTMLEvents");
evt.initEvent("change", false, true);
textbox.dispatchEvent(evt);
}
else {
textbox.fireEvent("onchange");
}
However, this simply results in the same as before. I've also tried simulating a key press in the textarea with code like the following:
textbox.dispatchEvent(new KeyboardEvent('keypress', {'key': 'a'}));
However, that also does not seem to work as the "Send" button does not seem to work (and the textarea doesn't seem to populate with the specified key of "a"). But once again, if I were to manually type something into the box, the "Send" button now works as it detected something being entered. I also tried dynamically importing jQuery in and using jQuery to simulate a keypress as seen below:
var e1 = jQuery.Event("keydown");
e1.which = 97;
$('textarea.sc-bdVaJa').last().trigger(e1);
var e2 = jQuery.Event("keyup");
e2.which = 97;
$('textarea.sc-bdVaJa').last().trigger(e2);
But that simply resulted in the same as above, the 'a' (decimal 97) didn't appear in the textarea, nor did the "Send" button work.
What I thought would be one of the simplest parts of this little project, sending a string of text to a textarea, is turning out to be a lot more difficult than I thought. What I'm looking for is, how do I go about getting a web page to register that new text has been entered into a textarea so that I may "click" a button and have it send the text to a chat?
While this doesn't directly solve the issue, this is what I did to get this working. Instead of using the textarea and Send button on the webpage, I decided to cut out the middleman and view the network traffic that's send when a post is made. I then use JavaScript to send a similar request to the server and it successfully posts the message. Here's how I did that.
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "/api/broadcasts/dug95avkgq/chat", true);
xhttp.setRequestHeader("content-type", "application/json");
xhttp.send('{"text":"<MESSAGE>","name":"<USERNAME>","clientId":"<ID>","color":"#22653f","csrfToken":"<TOKEN>"}');
I have a text field that should be filled before custom saving through HTML custom button.
When a user fills this field and tries to save through custom button, the text inside this field is null even if the user fills it.
Any suggestions Please?
Many Thanks for replying to my query. Actually, I am calling the below function from custom HTML button and I saw the result from alert message as NULL value until I leave the text box. Once I click some other Field then I am getting right value and saving the record successfully. I have posted my code below please have a look and suggest me how I can achieve it. So how to get the text value if a user doesn't leave the text box and click on the Save button?
function createRecord() {
var oDescription = Xrm.Page.getAttribute("new_description").getValue();
if (oDescription != null) {
var callentity = {};
var activityId;
var currentUserId = Xrm.Page.context.getUserId();
var oLeadId = Xrm.Page.getAttribute("new_lead").getValue()[0].id;
callentity.Subject = "Call Activity";
callentity.Description = oDescription ;
XrmSvcToolkit.createRecord({....Some more functions here...
})
}
HTML Button code for calling above function
<input id="SaveCall" onclick="parent.createRecord()" type="button" value="Save Phonecall"></p>
Xrm.Page.getAttribute(arg).getValue(val) won't return a value until focus is lost from the arg attribute (as you've found out).
Some options you could try:
document.getElementById('new_description_i')[0].value
Removing focus from "new_description" on click of your button.
I'm using on('submit') to detect when the form was submitted, but it only works when the user clicks on the submit button.
I use a <button> tag so I can put an image inside the button. I know I could use an input with type="submit" and use CSS it with the image, but I'd like to know the alternative jQuery way.
I was thinking doing an or comparison, for example on('submit') OR when user presses enter on any of the input field, but how should I do that?
$('#form').on('submit', function (e) {
e.preventDefault();
var email = $('#email').val();
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
});
<form id="form">
<input id="email" maxlength="64" name="EmailEDIT" type="text" width="100">
<button id="submitBtn"><img height="30" src="images/fx_demo_button.png" width="74"></button>
</form>
If the user presses enter in one of the field, the form will submit. It will trigger the same event as the button does. If this does not occur, something's up in your code.
You commented that your code doesnt work, but it does: http://jsfiddle.net/B5pZ4/
All I've added was alert(1); the rest is your code from this topic
You define your function in the eventhandler, might be better to seperate that, just in case you want to use that function again (or alter it a bit and use it in two situations).
If you seperate it in your code, it'll make more sense, I also think this is the problem you're having:
http://jsfiddle.net/B5pZ4/1/
You can actually make your code work with just one line. You create the function in your eventhandler (which, in this case, should be considered bad practice!), but you never call it. Either remove the function declaration, or add this under the function:
return validateEmail( email ); // THIS IS BAD PRACTICE AS FIX!
A tip: if you're working in html5, you can use this and the browser will do validating for you:
<input type="email" />
You need to insert an invisible input type submit for this to work.
Im just wondering how I go about catching the event when the user is typing into a text input field on my web application.
Scenario is, I have a contacts listing grid. At the top of the form the user can type the name of the contact they are trying to find. Once there is more than 1 character in the text input I want to start searching for contacts in the system which contain those characters entered by the user. As they keep typing the data changes.
All it is really is a simple type ahead type functionality (or autocomplete) but I want to fire off data in a different control.
I can get the text out of the input once the input has lost focus fine, but this doesnt fit the situation.
Any ideas?
Thanks
Use the keyup event to capture the value as the user types, and do whatever it is you do to search for that value :
$('input').on('keyup', function() {
if (this.value.length > 1) {
// do search for this.value here
}
});
Another option would be the input event, that catches any input, from keys, pasting etc.
Why not use the HTML oninput event?
<input type="text" oninput="searchContacts()">
I would use the 'input' and 'propertychange' events. They fire on cut and paste via the mouse as well.
Also, consider debouncing your event handler so that fast typists are not penalized by many DOM refreshes.
see my try:
you should put .combo after every .input classes.
.input is a textbox and .combo is a div
$(".input").keyup(function(){
var val = this.value;
if (val.length > 1) {
//you search method...
}
if (data) $(this).next(".combo").html(data).fadeIn(); else $(this).next(".combo").hide().html("");
});
$(".input").blur(function(){
$(this).next(".combo").hide();
});