Reputation: 640
I am trying to get a label to describe an input field. I have something like this (this code is in a <c:foreach/>
)
<label for="some_input-${someCounter.index}">
The value in the associated input is: ${ $('#some_input-'+${someCounter.index}).val() }
</label>
<input id="some_input-${comeCounter.index}"/>
I am having problems trying to get the value from an input field using jQuery. The fact that the id for the input is set using the .index which changes depending on the iteration of the loop is giving me problems. I will have multiple inputs each with their own label. Eventually these labels will be hidden for 508. That is the main reason why I need to get the value from the input.
Edit for clarification: I would like to use a jQuery selector to get the value from the input field and display this value in the label that is connected to it by the dynamic ID.
Thanks.
Upvotes: 0
Views: 652
Reputation: 2629
To get the value from the input fields, you can do the following:
Updated JSP:
<label for="some_input-${someCounter.index}">
The value in the associated input is: ${ $('#some_input-'+${someCounter.index}).val() }
</label>
<input id="some_input-${comeCounter.index}" class="some-class" />
JavaScript Sample:
$(".some-class").each(function() {
var $input = $(this);
// Now you can get the value of the input and do with it as you please.
console.log($input.val());
});
Update after clarification:
No, you cannot do it all in JSP as you depend on the user's input; you'll need to bind to the change event to update that element. Here's one way to do that:
JSP:
<label for="some_input-${someCounter.index}">
The value in the associated input is: <output></output>
</label>
<input id="some_input-${comeCounter.index}" class="some-class" />
JavaScript:
$(".some-class").on("change propertychange click keyup input paste", function() {
var $input = $(this),
id = $input.prop("id"),
$target = $('label[for="' + id + '"]').find("output") // Get the target element
// Update the target element
$target.text($input.val());
});
That should do the trick. You can use any element as the target, it does not need to be an output
element.
Note: I've updated the listener to pick up on multiple events in order to detect any change on the input field right away (instead of waiting for the input to go out of focus).
Upvotes: 1