⚠️ 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

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.