简体   繁体   中英

jQuery .val() always returns true even when false

I'm trying to do a boolean based on the value of an input inside a form, but I always keep ending up with either true or undefined . Where am I going wrong, and how do I get this right?

The value for name=locations will either be '' if there are no locations, or a json array like ['SFO','SJO','LA'] etc.

<form id="locale">
    <input name="locations[]" value=''/>
</form>

if($("#locale input[name=locations]").val() !== '') {
    alert ($("#locale input[name=locations]").val());
} else {
    alert ('No locations for this item!');
}

Name of the input is locations[] not locations

$('#locale input[name="locations[]"]').val()

so

var value = $('#locale input[name="locations[]"]').val();
if (value !== '') {
    alert(value);
} else {
    alert('No locations for this item!');
}

The removal of the brackets is for input names is PHP behaviour. As far as the client and the front end is concerned, if the input name has brackets, then the input name has brackets.

if($("#locale input[name='locations[]']").val() !== '') {

您可以使用匹配开头: [name^=locations]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM