简体   繁体   中英

How to check input values in javascript

function checkNullSearch(e) {
    if ($('#searchInput').val() === "") {
        $('#searchInput').attr("value", "null");
    }
}

script.js

<form role="form" id="form-arya">
    <div class="form-group">
        <div class="panel panel-primary searchPanel">
            <div class="input col-sm-12">
                <input type="text" class="form-control" id="searchInput"
                       name="searchInput"
                       aria-describedby="Not Null"
                       placeholder="Search"
                       required>                    
            </div>
            <div class="inputAndButtons">
                <div class="standartSearch">
                    <button class="btn btn-arya btn-success" type="submit" name="ara"
                            value="standart">
                        <i class="glyphicon glyphicon-search" aria-hidden="true" onclick="checkNullSearch(this)"></i>
                        Search
                    </button>
                </div>
            </div>
        </div>
    </div>
</form>

xxx.html

Sometimes it works, sometimes it doesn't work I want to on the input control to do. I want return "null" if input is empty value's

Change your button code like below:-

<button class="btn btn-arya btn-success" type="submit" name="ara" value="standart" onclick="checkNullSearch(this)"><i class="glyphicon glyphicon-search" aria-hidden="true"></i>Search</button>

And use $.trim() in your jQuery code

function checkNullSearch(e) {
    if ($.trim($('#searchInput').val()) == "") {
        $('#searchInput').attr("value", "null");
    }
}

检查输入的空白​​字符。即使输入似乎为空,也可能会有空白字符。请尝试使用trim()方法删除这些空白

you can use this code to get input value

function getInputValue(id) {
return document.getElementById(id).value.trim();
}

use

getInputValue("searchInput")

Your way is not wrong. You are using JQuery hence if you import jquery file in your page, It will work everytime. But instead of this code

$('#searchInput').attr("value", "null");

You have to use like this.

$('#searchInput').val('');

And if you want to use javascript you can check following

document.getElementById("#searchInput").value

before check null, you need to remove white space in input text. So you can use trim function

 var str = " Hello World! "; alert(str.trim()); 

if the browser does not support trim function, use following way

 function myTrim(x) { return x.replace(/^\\s+|\\s+$/gm,''); } function myFunction() { var str = myTrim(" Hello World! "); alert(str); } 

This worked for me.

function checkNullSearch() {
   if ($(#searchInput').val().trim() == "") {
     // it's empty
   }
 }

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