简体   繁体   中英

required message not a alert in the javascript

How can i write something a message not a alert when the input is empty.

Here in my code it is not preventing to submit the value when it is null, but how can i show a message like an required message that you need to insert something to search

if ( $( "#nameSearch" ).val().length === 0 ) {
    // some message that please insert something to search not an alert
    // required data-fv-notempty-message="This is required"
    event.preventDefault();
    } else {

below the input field, add a span like this

<span class="error" id="name-error"></span>

in script

if ( $( "#nameSearch" ).val().length === 0 ) {
$("#name-error").html("This is required");
event.preventDefault();
} else {

}

for class error, give any required style like colour as red, etc.

If you don't want an alert() put a <span> in your html and write your message in it.

<span id="msg"></span>    

Using your code:

if ( $( "#nameSearch" ).val().length === 0 ) {
    $('#msg').html("Please insert something to search");
event.preventDefault();
} else {

1) You can use the required attribute on your input.

<input type="text" name="password" value="" required />

2) You can process the error server side and return the errors found and create a custom message listing the errors.

3) You can use onsubmit on the form and then use javascript to check all the required fields, then using an id you can highlight the required fields that haven't been field.

I could go on. There are many ways of doing this, unless you want a more specific way of doing it?

<form method="post" onsubmit="return validate()">
<span class="error" id="name-error"></span>
<input type="text" name="nameSearch" id="nameSearch" >
<input type="submit" name="submit" value="submit" >
</form>

function validate()
{
    if ( $( "#nameSearch" ).val().length === 0 ) {
        $("#name-error").html("This is required");
        return false;
    } else {
        return true;
    }
}

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