I have a button. When I click on it, I'd like to see in the console the current input number that is right before my button element (this is not the final goal but if I can do that the rest won't be a problem).
All I get using my code is undefined
. Can someone explain to me what's wrong and how to do?
$(".ajoutPanier").click(function() {
var nb = $(this).prev(".inputNbArt").val();
console.log(nb);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="nbArticles">
<input class="inputNbArt" type="number" max="10" min="1" value="1">
</form>
<a href="#openModal">
<button class="ajoutPanier">Ajouter Au panier</button>
</a>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
There's two issues here. Firstly having a button
element inside an a
element is invalid HTML. I'd suggest removing the button
and placing the class
it had on the a
instead. You can then use CSS to style the a
element as needed.
Secondly, the DOM traversal method you're using isn't quite right. The .inputNbArt
element is a child of the form
, not a sibling to the clicked .ajoutPanier
. To correct that, use prev()
to get the sibling form
, and then find()
. Try this:
$(".ajoutPanier").click(function() {
var nb = $(this).prev('.nbArticles').find('.inputNbArt').val();
console.log(nb);
});
/* example button styling */
a.ajoutPanier {
background-color: #CCC;
display: inline-block;
padding: 5px 10px;
margin: 5px 0;
border-radius: 5px;
box-sizing: border-box;
text-decoration: none;
color: #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="nbArticles">
<input class="inputNbArt" type="number" max="10" min="1" value="1">
</form>
<a href="#openModal" class="ajoutPanier">Ajouter Au panier</a>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
Because your HTML is invalid (see comment, we can't be sure what the DOM will look like in any given browser, since they can do whatever they need to to make the structure valid.
When you click the button, this
inside the handler will be that button
element. prev
only finds previous siblings, but the element you're looking for isn't a sibling, it's a child of the button's parent's previous sibling (if the browser doesn't relocate the button
, which it very well might).
You could use:
$(this).parent().prev().find(".inputNbArt")
but it's fairly fragile. Instead, consider putting this entire structure in a parent element and then:
$(this).closest("selector-for-parent-element").find(".inputNbArt")