How does Javascript interact with HTML via document.getElementById? - javascript

I hope that I'm not asking a question that has been answered before - I was unable to find anything regarding this subject specifically.
I've been tasked with creating a "Hangman" game via Javascript. My professor has given us an HTML markup of the game, as well as styled it with CSS. I have to write the Javascript to make the game work. The code is contained within an external file.
The HTML has a form that accepts the initial word for hangman:
<div id="enterWordContainer" align="center">
Enter a six letter word for hangman: <input id="hangManWord" type="text" value="" />
<input type="button" value="Submit" onclick="saveWord();"/> </div>
How do I begin to manipulate the text that I would input in my HTML document?
I've tried creating a variable that would contain the text:
var userGuess = document.getElementById("hangManWord").value;
Shouldn't this put the form's input into a Javascript variable?

When executed right after (or at) page load, the assignment userGuess = document.getElementById("hangManWord").value sets the variable userGuess to the empty string, because that’s what the value property is set to, due to the HTML attribute value="".
When the input control is used by the user to change the value, this will not change the value of the userGuess value.
Within the saveWord function, you can use document.getElementById("hangManWord").value to get the current value of the control. You cannot get the value before a value has been input, though. You can, if you wish, use e.g. var userGuess = document.getElementById("hangManWord"), creating a reference to the input element (a reference to the whole element node object, instead of just getting the current value of one property thereof) and then use userGuess.value later.

Yes it will put form's input into the userGuess variable. BUT you have to insert your code into form submit event handler and this is function "saveWord();" that i believe you have to implement.
What it will eventually do is get your input value only when it has been submitted.

Related

How to reset a input tag field after taking one input to take another one

I wanted to create a calculator using HTML and JavaScript. I have already written the code and it works. But the main problem is that I cannot reset the input tag after I have already taken one input(like a calculator). I have an input tag like this:
Enter First Number:
<input id = "num1" placeholder = "First Number"/>
In my JavaScript there are functions like sum() which requires two numbers and functions like sine() which requires one number. So I want the input tag to be reset for taking another input after the first one for the sum() function. How do I do that?
Do you use jQuery? Can you give us a little overview of your code?
Its hard to give you an advice when we dont know the code.
In case of jQuery you can empty the inputs value by
$("input").val("") //Replace input with the fitting selector
If you are not using jQuery you can use:
document.getElementById('num1').value="";
This will clear the current value of the element. You should make sure that you have saved off the current value before you do this though.

$scope.myObjectVariable value set to input attribute value

Good evening,
I am writing an application using AngularJS and I require for the application to send data with a POST request to the nodejs server.
My data is structured like as a json object and it has data binding thanks to the AngularJS framework.
As of now, a function is dynamically trying to create possible values that the user might like inside of some input tags. An example:
<button ng-click="generateFoodAndBeverages(row)>Generate</button>
<input type="text" ng-model="row.service.day.beverage" placeholder="beverage" />
<input type="text" ng-model="row.service.day.food" placeholder="food" />
The two input values can be set by the user by typing in the value they would like (e.g. "Cola", "Hamburger"), but above the input tags is a button that can generate the input values for the user.
The function that generates the values takes them from an array and then at the end of the function returns two possible values, one for beverages and one for food.
When it has the two returning values it changes the attribute value of both inputs, setting them to the two possibilities generated by the function:
jQuery("#input1").attr("value", generateFoodAndBeverages(row)[0]);
jQuery("#input2").attr("value", generateFoodAndBeverages(row)[1]);
This is not perfect nor elegant but it's working. The function populates and dynamically changes the value attribute of those two input elements each time the user requests for automatic generation of food and beverages so the values are actually set and do exist.
Even so, even if I see them on screen as text inside the input fields, my POST request does not recognize the fact that the ng-model actually changed. The only way the ng-model registers the changes to the value attribute of the input fields is if the user types something with his keyboard, manually changing the value attribute. Another example:
<input type="text" value="generateValue()" ng-model="row.service.info" />
The one up here does not change the ng-model value at all.
<input type="text" value="User Typed Value" ng-model="row.service.info" />
This other one instead does change the ng-model value and as it changes and exists, it is passed to the $scope that can later be sent as a POST request to the server.
Any ideas as to why the "automatically and dynamically generated" value of the input field does not get registered by the ng-model while the user typed value does?
Thanks in advance!
[EDIT]
Apparently the problem comes with the ng-model not changing. I tried to debug the problem by applying an ng-change in the input. If the change is done by javascript, it is not registered with the ng-model and the ng-change function does not fire because the ng-model was not changed even tho' I can clearly see the new value set by javascript for the input tag. If I change the value of the input tag by hand the ng-change is fired and the console logs the change.
I could apply the changes directly to the ng-model if it weren't so different for each row.
Having the ng-model like this:
<input ng-model="row.serviceInfo.DayObject[dayString].food" />
<input ng-model="row.serviceInfo.DayObject[dayString].beverage" />
How would I be able to apply the changes directly to the ng-model given how dynamic the model is. As an example, I could have 1000 rows, each with their own serviceInfo object. I don't know how I could change the model for each of those rows with the dynamically generated values.
[EDIT]
The problem was indeed with ng-model not changing. The solution consisted in applying the changes to the ng-model for each element inside the dynamically generated values function. Thanks everyone for the input. I'll leave this piece of code here if anyone ever comes across the same problem! Thanks again!
let foodEl = angular.element(the row element food input);
let beverageEl = angular.element(the row element beverage input);
$scope.displayedCollection[i].serviceInfo = {
"day" : {
"food" : generatedValuesFood(el, day),
"beverage" : generatedValuesBeverage(el, day)
}
};
foodEl.val($scope.displayedCollection[i].serviceInfo.day.food);
beverageEl.val($scope.displayedCollection[i].serviceInfo.day.beverage);
I think that your problem is quite simple. As #ssougnez said, don't mixed jquery with angularjs. Angularjs use data-binding concept, don't use jquery style to change the input value instead use the ng-model directive to bind data from the model to the view on HTML controls (input, select, textarea). In your generateFoodAndBeverages function just set the ng-model value according to which row for eg:
var generateFoodAndBeverages = function () {
$scope.row.service.day.beverage = array[0];
$scope.row.service.day.food = array[1];
};

How can I change this input's value?

I want to change the input of a text field that stores the subject line in the Outlook Web App using JavaScript:
This subject text field is defined as:
<input tabindex="0" class="_f_ql _f_rl textbox allowTextSelection placeholderText" role="textbox" aria-labelledby="MailCompose.SubjectWellLabel" autoid="_f_B2">
I have tried the following using my JavaScript code:
textFieldElement.value = "Example";
textFieldElement.innerHTML = "Example";
textFieldElement.innerText = "Example";
These work to set the value as far as the user interface is concerned:
But they don't modify the "real" value of the subject that gets posted when you hit Send. Once you hit the Send button, the subject takes on no value (and shows up as (no subject) in an email). I can see from the POST request that unless I manually click on the element, focus it, and manually type in what I want it to display, physically with the keyboard, it won't send the subject argument in its JSON object.
How can I modify the "real" subject value that this control is expected to handle? I'm guessing this is an MVC control or some other type of ASP.NET control...and I am trying to modify the .aspx page, with JavaScript, to edit this value.
------------------------------------------------------------------------------------------------------------------------------------------------
Edit: I have only been able to set the subject line in one specific case. First, I need to physically click on the subject element. I've noticed this has a strange behavior of setting the class on this element from this:
<input class="_f_ql _f_rl textbox allowTextSelection placeholderText" autoid="_f_B2" role="textbox" tabindex="0" aria-labelledby="MailCompose.SubjectWellLabel">
To this:
<input class="_f_ql _f_rl textbox allowTextSelection" autoid="_f_B2" role="textbox" tabindex="0" aria-labelledby="MailCompose.SubjectWellLabel" maxlength="255">
Once it is in the non-placeholderText state with maxlength = "255", I am able to successfully change the innerText on it using textFieldElement.innerText = "Example";, and on submit, this gets sent correctly.
However, I cannot assume that the Subject element will ever be clicked, so I must work with the placeholderText version of the subject element first and somehow get it to reproduce this behavior where it goes into the other state. So far, I have tried the following without success:
Focusing the placeholderText subject element, then setting its innerText.
Changing the placeholderText subject element's attributes to match the non-placeholderText version of it, then setting its innerText.
http://msdn.microsoft.com/en-us/library/office/fp161027(v=office.1501401).aspx
Looks like you need to use
Office.context.mailbox.item.subject to set the subject. Outlook uses an API, so you need to use the API methods.

How do I access form data submitted by a user in Javascript?

I'm relatively new to programming, but understand the basics of HTML, CSS, and Javascript (including jQuery). Due to my greenness, I'd appreciate it if answers contained both a simple solution and a reason as to why the solution works. Thanks!
So I've got a form, with a text input and a submit button:
<form>
<input type="text">
<button type="submit">Submit</button>
</form>
When the user types data into the text field and clicks submit, how do I gain access to this data? If a user inputs their name, how do I grab that information? I don't intend to store it or write it anywhere, just to hold onto it as a variable in javascript, which I'll assign to a jQuery cookie.
So how do I access the data that the user has submitted, preferably using only Javascript (with jQuery)? Thanks for the help!
You access the data on the server side (in PHP via $_POST['username'] for example). The form sends data to your sever for any named input, so you would probably have to change the input to:
<input type=text name=username>
If you want to access it on the client side (with JavaScript), you can do that too, but you have to prevent the form from submitting:
$("form").on('submit', function (e) {
$.cookie('username', $(this).find('[name=username]').val());
//stop form from submitting
e.preventDefault();
});
say you had an html input tag such as:
<input id="textfield" type="text">
using javascript, you can store the value of that field in a variable like this:
var inputvalue = $('#textfield').val();
of course, you'll need something to run the script.
the reason this works is that the the textfield is an object. you might think of it as a tree trunk with different branches coming out. one of these "branches" is the value contained inside of it. since you know jquery, you know that $('#textfield') gets the element by a selector. the period says we're getting one of the branches, and "value" says we want the branch that tells what's in the textfield.
hope this helps.

Why does jQuery .html(string) shift the type attribute to the end of the input?

I have a form with three different inputs; two text and one submit. The html for this form is stored in a javaScript variable var form. When the user clicks a button, the following code is executed:
$('#content').html(form);
This works as expected. Then, when the user clicks the button again, it compares the html of the #content element with var form. You would expect it to return true since I just set the element to contain the contents of form, yet it returns false.
I found that when I retrieve the html from the #content element, it's slightly different than it was when I inserted it. For each of the input tags, the type attribute is moved from the beginning to the end. That is:
<input type="text"... /> --> <input ...type="text" />
So understandably when I try to compare them, it returns false. However, that begs the question of why it isn't inserting the html exactly as it is in the variable?
This is likely not due to jQuery; this is the browser. Once text/html is turned into DOM nodes, turning those nodes back into text is browser-dependent and not defined by a spec.
If you want to compare if the contents of the <form> tag are the same as when you created it you can't compare its text form. After all, <form class="foo" id="bar"> and <form id="bar" class="foo"> would yield identical DOM nodes once parsed by a browser.
You should compare only the attributes you expect to change and have well-defined states, like the value of input elements.
When .html(form) is executed, the browser makes changes to its underlying Document Object Model (DOM). It does not keep a record of the HTML that was passed as an argument.
Exactly the same is true of the HTML that forms a web page - after it has been interpreted into DOM nodes, the HTML itself plays no further part in the life of the page unless the page is refreshed.
The string string returned by .html() is totally synthetic.
So no, you would not expect the string returned by .html() to be identical to your original form variable.

Categories

Resources