Your code always looks for the button with the unique id
of checkBtn
. It is invalid to have multiple elements with the same id
(it defeats the purpose of id
) and so when jQuery goes looking for an element based on its id
, it stops after finding the first one (because there shouldn't be any other matches), so you always get the same answer.
Instead, just use the keyword this
(which is dynamic) to get a reference to the object that the event handler is currently running on:
$(':button').click(function () {
console.log(this.value); // Pure JavaScript way
console.log($(this).val()); // jQuery way
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type='submit' class='checkBtn' name='checkBtn' id='checkBtn1' value='apple'><i class='fa fa-check'></i></button>
<button type='submit' class='checkBtn' name='checkBtn' id='checkBtn2' value='linux'><i class='fa fa-check'></i></button>
<button type='submit' class='checkBtn' name='checkBtn' id='checkBtn3' value='windows'><i class='fa fa-check'></i></button>
Here's another post of mine that discusses this
and how it gets dynamically bound to various objects.
Now, I would argue that you should set up your HTML differently than you have it now because, semantically, submit buttons serve only to facilitate the submission of the other form data, not to convey form data themselves. Also, having multiple submit buttons can lead to accidental form submissions. So, for a cleaner and clearer UX, instead of 3 submit buttons that each carry a value to be submitted, I would create 3 radio buttons and have one submit button.
$('button').click(function () {
// Now, instead of "this", we just use a selector that finds the checked radio button
console.log(document.querySelector("input[name='checkBtn']:checked").value); // Pure JavaScript way
console.log($("input[name='checkBtn']:checked").val()); // jQuery way
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
<input type='radio' class='checkBtn' name='checkBtn' value='apple'><i class='fa fa-check'></i>Apple
</label>
<label>
<input type='radio' class='checkBtn' name='checkBtn' value='linux'><i class='fa fa-check'></i>Linux
</label>
<label>
<input type='radio' class='checkBtn' name='checkBtn' value='windows'><i class='fa fa-check'></i>Windows
</label>
<button type='submit'>Submit</button>