Reputation: 949
I got this code, that live-update text in a div when user type in a text area. I'm not sure how to edit it, so i can re-use it for several matching div/input.
Is it possible to use some kind of wildcard?
My working code:
<textarea id="input-address" name="address" rows="5" class="form-control">{{ Auth::user()->address }}</textarea>
<div id="output-address">{{ Auth::user()->address }}</div>
$(function() {
$source=$("#input-address");
$output=$("#output-address");
$source.keyup(function() {
$output.text($source.val());
});
});
I was thinking about something like this, but not sure how to handle it:
<input type="text" id="input-first_name" name="first_name" class="form-control" value="{{ Auth::user()->first_name }}" required>
<textarea id="input-address" name="address" rows="5" class="form-control">{{ Auth::user()->address }}</textarea>
<div id="output-first_name">{{ Auth::user()->first_name}}</div>
<div id="output-address">{{ Auth::user()->address }}</div>
<script type="text/javascript">
$(function() {
$source=$("#input-[name-match]");
$output=$("#output-[name-match]");
$source.keyup(function() {
$output.text($source.val());
});
});
</script>
Upvotes: 2
Views: 947
Reputation: 269
Hope this will help to solve your problem.
$('#input-address').keyup(function() {
var address= $('#input-address').val();
$('#output-address').html(address);
});
Upvotes: 0
Reputation: 67525
Yes you could use it as you described above, but you should attach a common dynamic input
event like :
$(function() {
//Attach 'input' event to all elements that have an 'id' start with 'input-'
$('[id^="input-"]').on('input', function(){
var source_name = $(this).attr('name');
//Change the element that have 'id' equal to 'output-source_name'
$('#output-'+source_name).text( $(this).val() );
});
});
Hope this helps.
$(function() {
$('.input').on('input', function(){
var source_name = $(this).attr('name');
$('#output-'+source_name).text( $(this).val() );
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="first_name" class="form-control input" value="first_name from controller" required>
<br>
<textarea name="address" rows="5" class="form-control input">address from controller</textarea>
<div id="output-first_name">first_name from controller</div>
<div id="output-address">address from controller</div>
Upvotes: 2
Reputation: 163
$(document).ready(function () {
$(":text").keyup(function () {
$("p").text($(":text").val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<form>
User Name: <br>
<input type="text" >
<input type="submit" value="Submit">
</form>
<br>
<p>
</p>
Upvotes: 2