Reputation: 3
I want to show the value of a text input in another element. There are multiple instances of this code on the page, so I want to select the items using classes rather than ID.
Problem is I can't select the h2 using this
.
Here is a simplified version:
HTML:
<div class="block">
<h2>Text to be replaced</h2>
<div class="block__content">
<div class="form-group">
<label for="candidate-name">Name of Candidate</label>
<input type="text">
</div>
</div>
</div>
JQUERY:
$('input').on("input", function() {
$(this).closest('h2').text($(this).val());
});
It works if I take out this
, so I know the rest of the function is correct, so I think it's a problem with this
:
$('input').on("input", function() {
$('h2').text($(this).val());
});
But I want to select the nearest h2 so I don't affect all the others.
Is something wrong with how I am using this
?
Thanks
Upvotes: 0
Views: 1202
Reputation: 806
I am not sure this works for accessibility.
Also the nested divs will be annoying to remove when you style your form with CSS Grid.
Make sure the form makes sense semantically and consider using a different element for the heading, unless it really is a heading don't use it. Forms have fieldsets and legends if you want to mark them up. H2 might not be the heading level really desired.
But you want your form to be pretty. What you can do is use pseudo-selectors and put them together in javascript to have contents equal to the heading you want to show. Forms - even big forms should be simple and normally a sign of it getting hacky is a sign that the UX is going wrong.
It is okay to markup the form with labels that are hidden on some screen sizes. If you are using HTML 5 form elements with placeholders then this is fine. The assistive technology folks still get their labels.
So, not the answer you wanted, but, keep the form simple and easy to maintain. Style it responsively with CSS Grid. Use pseudo-selectors for decorative elements. Make sure it is accessible (and simple). You will then find the scripting easier, not even needing jQuery but just selectors in vanilla JS.
Upvotes: 0
Reputation: 5967
.closest()
gets you the closest parent. the h2
element you're trying to select isn't a direct parent of the input, but a sibling of a parent.
You could get the closest .block
element and then access the h2
child.
e.g.
$('input').on("input", function() {
$(this).closest('.block').children('h2').text($(this).val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="block">
<h2>Text to be replaced</h2>
<div class="block__content">
<div class="form-group">
<label for="candidate-name">Name of Candidate</label>
<input type="text">
</div>
</div>
</div>
Upvotes: 1