Skip to content
Advertisement

Check if value is empty javascript

After submitting I want the redirect the users to a different page with the value of the input in the url. Now, when there is no value I want that it does nothing (return false). How can I do this?

My current code:

<form action="" method="post" class="searchInput">
    <input type="text" placeholder="Search anything you want..." name="search" id="search" />

    <button name="btnsearch" id="btnsearch" onclick=" window.location = '<?php echo base_url("index.php/search/index")?>/'+document.getElementById('search').value; return false;">
        Search</button>
</form>

Advertisement

Answer

You have two ways to do that. With JavaScript:

function validateForm() {
    var x = document.forms["myForm"]["nameField"].value;
    if (x == null || x == "") {
        alert("Name must be filled out");
        return false;
    }
}
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
Name: <input type="text" name="nameField">
<input type="submit" value="Submit">
</form>

Or you can use the HTML5 required attribute:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>HTML 5 Form Validation</title>
</head>
<body>
<form action="">
  Username: <input type="text" name="username" required>
  <input type="submit">
</form>
</body>
</html>

Now its up to you! 😀

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement