Reputation: 1011
I'm looking for a method to give the same value to a collection of inputs when i type something on them, lets say we have 10 of them,and i type the word "dog" to one of them,then all of them get the word "dog",then i type the word "cat" to an other one,every one gets the word "cat".
Something like this,which is not valid,but i just want to explain the logic :
$(document).on('input', 'input', function () {
$("#main input").each(function() {
$(this).val($(this).val())
});
});
Any ideas?
input{
position:relative;
float:left;
clear:both;
margin-bottom:1px;
width:85px;
text-align:center;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</head>
<body>
<div id="main">
<input>
<input>
<input>
<input>
<input>
<input>
<input>
<input>
<input>
<input>
</div>
</body>
</html>
Upvotes: 0
Views: 101
Reputation: 6313
Off the top of my head I'd do it like this but then again I haven't written jQuery for a while.
Since I assume you might have other input fields on the page I created a data attributed called data-copy
to attach our event listener. I was not inclined to do this via a class which is also totally valid mostly because its too easy to attach styles to those classes and then mix functionality and styling.
Read more about attribute selectors here: https://api.jquery.com/category/selectors/attribute-selectors/
If you want to do it without attributes you can change the selector to something like this but I would caution you to make it specific to avoid side effects.
$(function() {
$('#main input').on('keyup', function() {
const val = $(this).val();
$('#main input').not(this).val(val);
});
});
$(function() {
$('[data-copy]').on('keyup', function() {
const val = $(this).val();
$('[data-copy]').not(this).val(val);
});
});
input {
position: relative;
float: left;
clear: both;
margin-bottom: 1px;
width: 85px;
text-align: center;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</head>
<body>
<div id="main">
<input data-copy type="text">
<input data-copy type="text">
<input data-copy type="text">
<input data-copy type="text">
<input data-copy type="text">
<input data-copy type="text">
<input data-copy type="text">
<input data-copy type="text">
<input data-copy type="text">
<input data-copy type="text">
</div>
</body>
</html>
Upvotes: 1