Reputation: 3789
I am trying to get the html as a variable of the first input in an input group when an "addInput" link is clicked:
$(".addInput").click(function() {
var input = $(this).closest(".input-group").children().first().html();
alert(input);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label for="phone">Phone</label>
<div class="input-group">
<input type="tel" class="form-control" id="phone" pattern="\d{3}[\-]\d{3}[\-]\d{4}" placeholder="Format: 555-555-5555" name="phone" value="419-555-1212" disabled required>
<div class="input-group-addon"><a href="#" class="addInput"><span class="fa fa-plus"></span></a></div>
<div class="input-group-addon"><a href="#" class="deleteInput"><span class="fa fa-minus"></span></a></div>
</div>
</div>
Upvotes: 1
Views: 656
Reputation: 533
Just add a id to the input element and get the value of that
<div class="form-group">
<label for="phone">Phone</label>
<div class="input-group">
<input id="your-id-here" type="tel" class="form-control" id="phone" pattern="\d{3}[\-]\d{3}[\-]\d{4}" placeholder="Format: 555-555-5555" name="phone" value="419-555-1212" disabled required>
<div class="input-group-addon"><a href="#" class="addInput"><span class="fa fa-plus"></span></a></div>
<div class="input-group-addon"><a href="#" class="deleteInput"><span class="fa fa-minus"></span></a></div>
</div>
and in JS
//add input fields
$(".addInput").click(function() {
var input = $('your-id-here').val();
alert(input);
});
Upvotes: 0
Reputation: 337560
Needing to get the HTML of an element at runtime is a little odd. From the context of the code, it seems as though you're trying to add another input when the .addInput
is clicked? If so, use clone()
, then you can insertAfter()
to place the new input directly after the original:
$(".addInput").click(function() {
var original = $(this).closest(".input-group").find('input:first');
original.clone().insertAfter(original);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label for="phone">Phone</label>
<div class="input-group">
<input type="tel" class="form-control phone" pattern="\d{3}[\-]\d{3}[\-]\d{4}" placeholder="Format: 555-555-5555" name="phone" value="419-555-1212" disabled required>
<div class="input-group-addon"><a href="#" class="addInput"><span class="fa fa-plus">+</span></a></div>
<div class="input-group-addon"><a href="#" class="deleteInput"><span class="fa fa-minus">-</span></a></div>
</div>
</div>
Two things to note, though. Firstly I removed the id="phone"
on the element to be cloned. If you don't do this you'll end up with multiple elements charing an id
which is invalid. You can use a class
instead.
Secondly, that if you want to clear the value of the clone, use val('')
.
Upvotes: 1