Reputation: 15703
I'm trying to check which of four submit buttons was pressed, using jQuery 1.7.2 If any of three of them are clicked, I want to show an alert box with the value of the button. Here is the html code:
<body>
<table>
<tr>
<td>
<input type="submit" id="cancel" value="Cancel">
</td>
</tr>
<tr>
<td>
<input type="submit" id="find" value="Find">
</td>
</tr>
<tr>
<td>
<input type="submit" id="save" value="Save">
</td>
</tr>
<tr>
<td>
<input type="submit" id="update" value="Update">
</td>
</tr>
</table>
</body>
Here is the jQuery function code:
<script>
$(function(){
$(':submit').click(function(){
var value = $(this).val();
//alert(value);
if($(this).val() == "Save" || "Find" || "Clear") {
//if($(this).val() == "Update") {
alert('The value is: ' + value);
}
});
});
</script>
If I click on any of the three buttons I get the value displayed, but if I then click on the Update button it is also displayed. I thought my if block would prevent that from happening?
If I comment out that line and use this code instead:
if($(this).val() == "Update") {
alert('The value is: ' + value);
}
Then only when I click on the Update button will the alert fire. What is wrong with the code here when I'm checking for multiple submit buttons?
Upvotes: 1
Views: 1849
Reputation: 268344
Your if-statement is not correct:
if( $(this).val() == "Save" || "Find" || "Clear" )
Though the operator is commonly assumed to work like this, this is not how it works. If you wanted to test whether the value is equal to one of these strings, you should probably use $.inArray
instead:
if ( $.inArray( $(this).val(), [ "Save", "Find", "Clear" ] ) > -1 );
As a bit of extra-credit, the ||
operator evaluates two expressions (one to the left of it, and one to the right of it) and evaluates to true
if either of the two expressions is truthy.
if ( true || false ) // Evalutes to true, since one of the two was true
In your attempt, you wanted to see if the value was equal to any of these strings. If you wanted to use ||
, you would have to create several comparisons:
var myVal = $(this).val();
if ( ( myVal == "Save" ) || ( myVal == "Find" ) || ( myVal == "Clear" ) )
This condition will evaluate to true
if any of the conditions are met. You can see how this will quickly become rather verbose.
Upvotes: 4