⚠️ This lesson is retired and might contain outdated information.

Extract a Value from an Stimulus Target Input

Ian Jones
InstructorIan Jones
Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 2 years ago

We will use data-target to tell our controller which input element we are getting our value from.

We need to declare static targets = ['name'] in our controller to tell which element we are referencing. We then reference the value in the input element with this.nameTarget.value.

Instructor: [0:00] Here we have an app. Right now, when you click Greet, it logs Hello. If we want to get the value of this input, the first thing that we need to do is go to our example_controller.

[0:15] The first thing we need to do is give our controller a target. We'll call this target name. Inside of our greet method, we need to grab the element off of our target. Stimulus creates this method for you when you have a target in here. This name isn't special, so if you call it foo, it would be foo target, or whatever you want to name it.

[0:57] Next, we need to get the value off of this target. Now that we have the name, we can log it out.

[1:21] When you go over and reload, you can see that we're getting this error. This is because we need to wire up our target that's in our controller to our html.

[1:35] This input is the target that we want to get the value from. Add a data-target attribute with the controller name, so example, and the target name, which is name in this case. When we reload and we go Ian, we get Hello Ian.

[2:02] To wrap up, the first thing we did was we added a static target, which is an array of strings. We then got the element of this target, and then the value off of that element.

[2:20] The next thing we did was we wired up that name target to this html input.

egghead
egghead
~ 2 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today