Курсы javascript
Выходит: Инпут 1, Инпут 2, Инпут 3.
Всё норм.
Но если на странице изменить в значениях инпута текст и попытаться снова его вывести в логи, то выводится старые значения, а не то что мы ввели.
Как исправить эту проблему?
Последний раз редактировалось erilar, 13.01.2021 в 03:23 .
13.01.2021, 04:06
Интересующийся
Регистрация: 07.01.2015
Сообщений: 11
Мда. Кодить в 3 часа ночи явно не нужно. Сам создал себе глупую ошибку.
valInput.push(inputs[index].defaultValue);
записывает изначальное значение.
Чтобы получить то, что мы вписываем в инпут нужно написать это:
valInput.push(inputs[index].value);
Спасибо всем за ответы и глупые вопросы «А зочем ето тебе нужна?», «А зочем тебе достоват из инпута валуе?»
Вопрос решен!
Последний раз редактировалось erilar, 13.01.2021 в 04:09 .
13.01.2021, 08:25
Регистрация: 27.05.2010
Сообщений: 33,011
erilar,
Untitled
Getting the value from element in typescript
I’m currently trying to get the values a user would insert into an input form. In vanilla javascript, I can just target the element by id or class, etc, and then I can just use the .value method to actually get in use that method. For some reason, typescript cannot do that, which I do not understand because typescript is a superset of javascript. Is there a specific way to get a value from an input element in pure typescript or do I have to use angular or something? Typescript code:
interface IUserFoodOptions < food: string; calories: number; foodDate: any; >class Food implements IUserFoodOptions < food: string; calories: number; foodDate: any; // store all the calories in an array and calculate the total amount of calories caloriesArray: number[] = []; // constructor constructor(food: string, calories: number, foodDate: any) < this.food = food; this.calories = calories; this.foodDate = foodDate; >> // event listener for when the add food button is clicked let addFood = document.getElementById("add-food-button").addEventListener("click", () => < // get the values from inputs and store them in an array let foodName = document.getElementById("food-name-val"); let foodCalories = document.getElementById("calories-val"); let dateVal = document.getElementById("date-val"); // store these values in a list and display them below // user will have the ability to edit and delete them // am I create event listeners within event listeners >);
asked Oct 30, 2018 at 19:46
AfternoonTiger AfternoonTiger
357 1 1 gold badge 4 4 silver badges 11 11 bronze badges
Using as HTMLInputElement worked for me: stackoverflow.com/a/52495421/470749
Apr 11, 2020 at 15:34
4 Answers 4
If you are using an editor like VSCode to write Typescript, I’ve found the ability to inspect code very valuable in learning more about what’s occurring in the typing system. In VSCode you can right click on the method(or type) and choose Go to definition .
Inspecting the method in your question, getElementById , you can see it returns an HTMLElement . This type doesn’t have a value property on it. This makes sense as getElementById can return any HTMLElement on the page as long as it has an id attribute. Not every HTMLElement though has a value property(for instance a div / span / p , etc).
Since you know what type you are expecting, but the type system can’t, to get this to work, you have to tell Typescript what type of element you expect to be selecting. You would do that through casting the type of the selected element as follows: const inputElement = document.getElementById(«food-name-val»); or const inputElement = document.getElementById(«food-name-val») as HTMLInputElement;
Now, since Typescript recognizes the selected element as an HTMLInputElement , it won’t error when you access the value property on it.
In your case that would look like: let foodName = (document.getElementById(«food-name-val») as HTMLInputElement).value;
Курсы javascript
Всегда получаю [undefined] или [null], якобы «is not an object.»
Если убираю .value, и получаю элемент в переменную, то вроде не ругается, но добавив к элементу .value опять же получаю null. В чем косяк?
Последний раз редактировалось Zhiganov, 26.04.2011 в 17:42 .
26.04.2011, 17:00
Регистрация: 30.03.2010
Сообщений: 1,813
потому что вы пытаетесь получить значение value элемента которого нет ещё на странице
заметьте разницу этого
__________________
.
26.04.2011, 17:41
Интересующийся
Регистрация: 25.10.2010
Сообщений: 10
Skipp, неее, я код примерно привел, сам скрипт у меня висит в header’e и вызывается на window.onload, так что дело не в этом
The «value» binding
The value binding links the associated DOM element’s value with a property on your view model. This is typically useful with form elements such as , and .
When the user edits the value in the associated form control, it updates the value on your view model. Likewise, when you update the value in your view model, this updates the value of the form control on screen.
Note: If you’re working with checkboxes or radio buttons, use the checked binding to read and write your element’s checked state, not the value binding.
Example
Login name:
Password:
Parameters
- Main parameter KO sets the element’s value property to your parameter value. Any previous value will be overwritten. If this parameter is an observable value, the binding will update the element’s value whenever the value changes. If the parameter isn’t observable, it will only set the element’s value once and will not update it again later. If you supply something other than a number or a string (e.g., you pass an object or an array), the displayed text will be equivalent to yourParameter.toString() (that’s usually not very useful, so it’s best to supply string or numeric values). Whenever the user edits the value in the associated form control, KO will update the property on your view model. KO will always attempt to update your view model when the value has been modified and a user transfers focus to another DOM node (i.e., on the change event), but you can also trigger updates based on other events by using the valueUpdate parameter described below.
- Additional parameters
- valueUpdate If your binding also includes a parameter called valueUpdate , this defines additional browser events KO should use to detect changes besides the change event. The following string values are the most commonly useful choices:
- «input» — updates your view model when the value of an or element changes. Note that this event is only raised by reasonably modern browsers (e.g., IE 9+).
- «keyup» — updates your view model when the user releases a key
- «keypress» — updates your view model when the user has typed a key. Unlike keyup , this updates repeatedly while the user holds a key down
- «afterkeydown» — updates your view model as soon as the user begins typing a character. This works by catching the browser’s keydown event and handling the event asynchronously. This does not work in some mobile browsers.
Note 1: Getting value updates instantly from inputs
If you are trying to bind an or to get instant updates to your viewmodel, use the the textInput binding. It has better support for browser edge cases than any combination of valueUpdate options.
Note 2: Working with drop-down lists (i.e., elements)
Knockout has special support for drop-down lists (i.e., elements). The value binding works in conjunction with the options binding to let you read and write values that are arbitrary JavaScript objects, not just string values. This is very useful if you want to let the user select from a set of model objects. For examples of this, see the options binding or for handling multi-select lists, see the documentation for the selectedOptions binding.
You can also use the value binding with a element that does not use the options binding. In this case, you can choose to specify your elements in markup or build them using the foreach or template bindings. You can even nest options within elements and Knockout will set the selected value appropriately.
Using valueAllowUnset with elements
Normally, when you use the value binding on a element, it means that you want the associated model value to describe which item in the is selected. But what happens if you set the model value to something that has no corresponding entry in the list? The default behavior is for Knockout to overwrite your model value to reset it to whatever is already selected in the dropdown, thereby preventing the model and UI from getting out of sync.
However, sometimes you might not want that behavior. If instead you want Knockout to allow your model observable to take values that have no corresponding entry in the , then specify valueAllowUnset: true . In this case, whenever your model value cannot be represented in the , then the simply has no selected value at that time, which is visually represented by it being blank. When the user later selects an entry from the dropdown, this will be written to your model as usual. For example:
Select a country:
In the above example, selectedCountry will retain the value ‘Latvia’ , and the dropdown will be blank, because there is no corresponding option.
If valueAllowUnset had not been enabled, then Knockout would have overwritten selectedCountry with undefined , so that it would match the value of the ‘Choose one. ‘ caption entry.
Note 3: Updating observable and non-observable property values
If you use value to link a form element to an observable property, KO is able to set up a 2-way binding so that changes to either affect the other.
However, if you use value to link a form element to a non-observable property (e.g., a plain old string, or an arbitrary JavaScript expression), KO will do the following:
- If you reference a simple property, i.e., it is just a regular property on your view model, KO will set the form element’s initial state to the property value, and when the form element is edited, KO will write the changes back to your property. It cannot detect when the property changes (because it isn’t observable), so this is only a 1-way binding.
- If you reference something that is not a simple property, e.g., the result of a function call or comparison operation, KO will set the form element’s initial state to that value, but it will not be able to write any changes back when the user edits the form element. In this case it’s a one-time-only value setter, not an ongoing binding that reacts to changes.
First value:
Second value:
Third value: 8" />
Note 4: Using the value binding with the checked binding
The checked binding should be used to bind a view model property against the value of a checkbox ( ) or radio button ( ). If you do include the value binding with the checked binding on one of these elements, then the value binding acts similarly to the checkedValue option that can be used with the checked binding and will control the value that is used for updating your view model.
Note 5: Interaction with jQuery
Knockout will use jQuery, if it is present, for handling UI events such as change . To disable this behavior and instruct Knockout to always use native event handling, you can set the following option in your code before calling ko.applyBindings :
ko.options.useOnlyNativeEvents = true;Dependencies
None, other than the core Knockout library.
- valueUpdate If your binding also includes a parameter called valueUpdate , this defines additional browser events KO should use to detect changes besides the change event. The following string values are the most commonly useful choices:
