Reputation: 109
If you type in the first item's input, you see it expands and that it's width was determined by the length of the value.
How do I iterate this for every item where the input width matches each item's value width?
$(".item").each(function() {
$(".input--span").text($(".input--item").val());
$(".input--item").width($(".input--span").width());
$(".item").on("input", function() {
$(".input--span").text($(".input--item").val());
$(".input--item").width($(".input--span").width());
});
});
.input--item,
.input--span {
font: inherit;
margin: 0;
padding: 0;
background: green;
color: white;
}
.input--item {
border: none;
min-width: 10px;
}
.input--span {
display: none;
white-space: pre;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="item">
<span class="input--span"></span>
<input class="input--item" type="text" name="name" value="Item 1 Long Text" autocomplete="off" />
</p>
<p class="item">
<span class="input--span"></span>
<input class="input--item" type="text" name="name" value="Item 2" autocomplete="off" />
</p>
<p class="item">
<span class="input--span"></span>
<input class="input--item" type="text" name="name" value="I3" autocomplete="off" />
</p>
Upvotes: 0
Views: 36
Reputation: 24001
[1] No need to use .each()
because in this case the loop will repeat the input
event by the number of item
elements .. it's unseen but if you console.log
anything in the input
event in .each
it will be repeated
[2] While you use input
event for input you can use $(".item .input--item")
instead of just $(".item")
[3] To catch the previous span of the desired input you can use .prev()
.. There're more selectors for that but in this case prev()
will be the easiest one
[4] To run the code onload you can trigger the input event by use .trigger('input')
you can remove it and see the deference
$(".item .input--item").on("input", function() {
$(this).prev(".input--span").text($(this).val());
$(this).width($(this).prev(".input--span").width());
}).trigger('input');
.input--item,
.input--span {
font: inherit;
margin: 0;
padding: 0;
background: green;
color: white;
}
.input--item {
border: none;
min-width: 10px;
}
.input--span {
display: none;
white-space: pre;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="item">
<span class="input--span"></span>
<input class="input--item" type="text" name="name" value="Item 1 Long Text" autocomplete="off" />
</p>
<p class="item">
<span class="input--span"></span>
<input class="input--item" type="text" name="name" value="Item 2" autocomplete="off" />
</p>
<p class="item">
<span class="input--span"></span>
<input class="input--item" type="text" name="name" value="I3" autocomplete="off" />
</p>
Upvotes: 1