TL;DR: You’re using the wrong operator.
Your condition provides that if the URL field is empty or if the URL field is empty the code will be executed. This means that:
- If the file field is empty, the alert will be displayed (even if the URL is valid);
- If the URL field is empty, the alert will be displayed (even if the file is valid);
- If both fields are empty.
What you want is to check if the two fields are empty. In this case, what you need is the logical operator and (&&
):
$('form').on('submit', function(event) {
event.preventDefault();
const $nameField = $('[name="name"]');
const $ageField = $('[name="age"]');
if ($nameField.val() === '' && $nameField.val() === '') {
alert('Inválido!');
return;
}
alert('Válido!');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input type="text" name="name" placeholder="Nome" />
<input type="text" name="age" placeholder="Idade" />
<br />
<button type="submit">Enviar</button>
</form>
PS: In relation to if
, it is not necessary to compare empty in an empty string. So you can swap:
$nameVal.val() === ''
For:
!$nameVal.val()
Staying:
$('form').on('submit', function(event) {
event.preventDefault();
const $nameField = $('[name="name"]');
const $ageField = $('[name="age"]');
if (!$nameField.val() && !$nameField.val()) {
alert('Inválido!');
return;
}
alert('Válido!');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input type="text" name="name" placeholder="Nome" />
<input type="text" name="age" placeholder="Idade" />
<br />
<button type="submit">Enviar</button>
</form>
This happens because empty strings (''
) are considered values falsey in Javascript.
What’s the problem you’re having? I ran the tests here with your code and it’s working normal.
– Victor Carnaval
@Victorcarnaval Ta demanding both camps.
– Tiago
Yes, you are using the logical operator
||
(OR / OR ), that is, when one of the cases is equal totrue
theif
will be executed. If you want to executeif
only when the two fields are empty, change the operator||
for&&
(And / AND ).– Victor Carnaval
@James Is demanding the two fields, as expected by
if
that you posted. The||
implies that if one of the conditions is true, theif
.– Ronaldo Araújo Alves
@Victorcarnaval This is my intention. Let it be filled either the input file or url or both.
– Tiago