nina_berlini nina_berlini - 2 months ago 8
HTML Question

Print the labels and values of textareas/inputs which are in a spezific area of a form

I want to get the label and values of some of my textareas and input-tags, which I have on my website. There are many inputs/textereas and I dont want to have all of them, only the textareas/inputs in a spezific area. For example in the following case, I only want to have all values that came after the texterea with the name b:



var inputs;

$('textarea').each(function(){
var name= $(this).attr('name');
inputs += name+': '+$(this).val()+'<br>';

})

document.write(inputs);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="form" method='post' action="/form">
<div class="form-group">
<label class="control-label">label_a</label>
<textarea name="a" class="form-control" rows="1"></textarea>
</div>
<div class="form-group">
<label class="control-label">label_b</label>
<textarea name="b" class="form-control" rows="1"></textarea>
</div>
<div class="form-group">
<label class="control-label">label_c</label>
<textarea name="c" class="form-control" rows="1"></textarea>
</div>
<div class="form-group">
<label class="control-label">label_d</label>
<textarea name="d" class="form-control" rows="1"></textarea>
</div>
</form>





But that is not the whole problem. Instead of the name, I want to have the lable of the input/textarea. Have I to add a for-attribut to each control and label to do that or is there a easier way to do that?

Can sombody say, why it first print "undefined"?

I would be very lucky if somebody can help me :)

Answer

First initialize inputs, then check if the name is after 'b' if you only want sections after that, and to get the label text use $(this).prev().text()

var after='b';
var inputs='';
var found=false;

$('textarea').each(function(index){
  if(found){
var name= $(this).prev().text();
inputs += name+': '+$(this).val()+'<br>';
  }
  if($(this).attr('name')==after)
found=true;
});

document.write(inputs);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="form" method='post' action="/form">
	<div class="form-group">
		<label class="control-label">label_a</label>
		<textarea  name="a" class="form-control" rows="1">this is content of a</textarea>
	</div>
	<div class="form-group">
		<label class="control-label">label_b</label>
		<textarea name="b"  class="form-control" rows="1">this is content of b</textarea>
	</div>									
	<div class="form-group">
		<label class="control-label">label_c</label>
		<textarea  name="c" class="form-control" rows="1">this is content of c</textarea>
	</div>								
	<div class="form-group">
		<label class="control-label">label_d</label>
		<textarea  name="d" class="form-control" rows="1">this is content of d</textarea>
	</div>
</form>

Comments