Reputation: 368
Im trying to alert the current value that is in the input box depending on which button you click on. So if the first grid-2 button is selected it would alert 1 and if the second button with the input value of 2 was to be clicked on instead it would alert that number etc.
<div class='grid-2'>
<input class="photo1" value="1">
<a class='remove-photo' href='#'>Remove Now</a>
</div>
<div class='grid-2'>
<input class="photo1" value="2">
<a class='remove-photo' href='#'>Remove Now</a>
</div>
<div class='grid-2'>
<input class="photo1" value="3">
<a class='remove-photo' href='#'>Remove Now</a>
</div>
<div class='grid-2'>
<input class="photo1" value="4">
<a class='remove-photo' href='#'>Remove Now</a>
</div>
<script type="text/javascript">
$(document).ready(function() {
$(".remove-photo").click(function() {
var current_selected_photo_num = $(".photo1").val();
alert(current_selected_photo_num);
});
});
</script>
Upvotes: 3
Views: 3817
Reputation: 54618
I'm not a fan of any listed answer so far, they are all tightly coupled to html which makes your javascript fragile. A simple HTML change could prevent most other answers from working as expected.
Instead I would suggest changing your HTML:
<input class="photo1" value="1" id="photo-1-1">
<a class='remove-photo js-remove-photo' href='#' data-alert-target="#photo-1-1">Remove Now</a>
<input class="photo1" value="1" id="photo-1-2">
<a class='remove-photo js-remove-photo' href='#' data-alert-target="#photo-1-2">Remove Now</a>
<input class="photo1" value="1" id="photo-1-3">
<a class='remove-photo js-remove-photo' href='#' data-alert-target="#photo-1-3">Remove Now</a>
<input class="photo1" value="1" id="photo-1-4">
<a class='remove-photo js-remove-photo' href='#' data-alert-target="#photo-1-4">Remove Now</a>
Javascript
$(".js-remove-photo").click(function() {
var target = $(this).data('alert-target');
var value = $(target).val();
alert(value);
});
I'd also recommend reading Decoupling Your HTML, CSS, and JavaScript - Philip Walton (Engineer at Google).
Upvotes: 1
Reputation: 140
Using jQuery's .siblings() you can get the siblings of the element as the selector and specify a class or ID that the sibling should have. Then it's just a matter of getting the value of the sibling and alerting it.
$(".remove-photo").on("click", function(){
var inputValue = $(this).siblings(".photo1").val();
alert(inputValue);
});
Upvotes: 0
Reputation: 700252
You can locate the surrounding div
and find the input
in it:
$(".remove-photo").click(function() {
var num = $(this).closest('div').find(".photo1").val();
alert(num);
});
Upvotes: 0
Reputation: 1223
Use the .prev()
function to go upwards through siblings
$(".remove-photo").click(function() {
var current_selected_photo_num =
$(this).prev('.photo1').val();
alert(current_selected_photo_num);
})
Upvotes: 3