Kalif Vaughn
Kalif Vaughn

Reputation: 353

onclick submit button, check if an input is empty

I've searched and tried just about everything and nothing works. I'm just trying to have this happen:

onclick a submit button --> check to see if a text field is empty --> if it is, alert an error and do not advance to the next page (if not, advance but only if the values are between 0 - 100 numerically.

Here's what I've got right now (other code I've found that works):

<form name="agencytrial">
    <div class="textcenter">
        <input name="AgencyRating" id="AgencyField" type="text" value="" autocomplete="off" class="forceNumeric" onchange="handleChange(this)"; />
        <input class="button" id="FormSubmitButton" type="submit" value="Submit" onclick="checkField()";  />
    </div>
</form>

<script>
    function handleChange(input) {
        if (input.value < 0) alert("Value should be between 0 - 100");
        if (input.value > 100) alert("Value should be between 0 - 100");
    }
</script>

The above code works fine, and if someone types something into the field, and if it is not between 0 - 100, then it will alert and error and NOT advance the page.

But if no one types anything, they can just click the submit button and advance the page, and the above code does nothing to stop that. So I tried to use something like the following (one of many attempts):

<script type = "text/javascript">
    function checkField(){
        var x = document.getElementById("AgencyField");
        if (var x = ""){
            alert("Value should be between 0 - 100");
            return false;
        }else{
            return true;
        }
</script>

The above code fails, and they can just click the submit button and advance without typing anything into the field.

Any help would be majorly appreciated!

------------EDIT--------------

Based on everyone's comments, I've rewritten my code and it's very close. BUT HERE'S WHAT I DON'T GET:

When I input number > 100, it alerts message and DOES NOT ADVANCE.

When I leave it blank, it alerts message and ADVANCES.

Why the difference?

<form name="agencytrial">
    <div class="textcenter">
        <input name="AgencyRating" id="AgencyField" type="text" value=""   autocomplete="off" class="forceNumeric" onchange="handleChange(this)"/>
        <input class="button" id="FormSubmitButton" type="submit" value="Submit" onclick="handleChange()">
    </div>
</form>

<script>
  function handleChange(input){
  var x = document.getElementById("AgencyField").value;
    if (x < 0 || x > 100 || x === "") alert("Value should be between 0 - 100");
    }
</script>

-------EDIT #2--------

Here's all my code below. I am just using "form onsubmit" and the "onclick" codes now, as the onchange code was not going to stop the key or the button from being clicked with the form being empty (i.e., never modified).

I've got the alert popping up with either or the button being clicked, but the page always advances after I close the alert.

<?php
    $compTime = 8;                  // time in seconds to use for 'computer' timing
    if ($text === '') { $text = 'How likely was it that you caused the tone to occur?|Type your response on a scale from 0-100.'; }
    $texts = explode('|', $text);
    $mainText = array_shift($texts);
?>
<!DOCTYPE html>
<html>
<form onsubmit="return handleChange();">
    <div class="textcenter">
        <h3><?php echo $mainText; ?></h3>
        <?php
            foreach ($texts as $t) {
                echo '<p>' . $t . '</p>';
            }
        ?>
    </div>

    <div class="textcenter">
        <input name="AgencyRating" id="AgencyField" type="text" value="" autocomplete="off" class="forceNumeric"/>
        <input class="button" id="FormSubmitButton" type="submit" value="Submit" onclick="return handleChange()"/>
    </div>
</form>

<style type="text/css">
img {
    display: block;
    position: relative;
    bottom: -40px;
    left: -21px;
    max-width:520px;
    max-height:520px;
    width: auto;
    height: auto;
}
</style>

<body>
<img src="/tapa/Experiment/images/scale.jpg"</img>
</body>
</html>


<script type="text/javascript">
function handleChange(input) {
    var x = document.getElementById("AgencyField").value;
    if (x === "" || x < 0 || x > 100) {
        alert("Value should be between 0 - 100");
        return false;
    }
   return true;
}
</script>

*****EDIT*****

I have solved the problem using a new script. Thanks to everyone and the solutions provided would usually work, but just not in my case for reasons not entirely clear to me but not worth explaining.

Upvotes: 2

Views: 38737

Answers (6)

Spinstaz
Spinstaz

Reputation: 331

I used the following code to check:

<form action = "dashboard.php" onsubmit= "return someJsFunction()">
  <button type="submit" class="button"  id = "submit" name="submit" >Upload to live listing</button>
</form>
    <script type="text/javascript">

       function someJsFunction(){

        const input = document.getElementById('input1');

        if(input.value === ""){
          alert ("no input?"); // This will prevent the Form from submitting
          return false;                              
        }else{
          return true; // this will submit the form and handle the control to php.
        }
     }

</script>

Upvotes: 0

acdcjunior
acdcjunior

Reputation: 135862

Updated question:

When I input number > 100, it alerts message and DOES NOT ADVANCE.

When you input a number > 100 and click submit, it will trigger the onchange. It won't even trigger the submit button.

When I leave it blank, it alerts message and ADVANCES.

It advances because you don't tell it not to. To do that, you have to return false on the onclick event (see fix below).

Fix:

Add return to #FormSubmitButton's onclick:

<input class="button" id="FormSubmitButton" type="submit"
                                            value="Submit" onclick="return handleChange()">
                                                                    ^^^^^^-- add this

Add returns to the JavaScript function:

function handleChange(input) {
    var x = document.getElementById("AgencyField").value;
    if (x < 0 || x > 100 || x === "") {
        alert("Value should be between 0 - 100");
        return false;
    }
    return true;
}

Check updated demo fiddle here.


Original question

Several issues:

var x = document.getElementById("AgencyField");

This way, x only gets a reference to the #AgencyField element. You don't want that, you want its value: var x = document.getElementById("AgencyField").value;

Also, you are doing an assignment in your if, not a comparison:

if (var x = ""){

This line should be if (x === ""){.

Your function checkField() { also is missing an ending }.

Most important, and subttle, is:

<input class="button" id="FormSubmitButton" type="submit" value="Submit" onclick="checkField()"; />

You should have a return there (also remove that ;):

<input class="button" id="FormSubmitButton" type="submit" value="Submit" onclick="return checkField()"/>

All in all, check an updated working fiddle here. There are more changes, they all are shown below (in the comments).

Fixed JavaScript:

function handleChange(input) {
    if (input.value.length < 0) { // added .length
        alert("Value should be between 0 - 100");
        return false; // added this
    }
    if (input.value.length > 100-1) { // added .length AND added -1
        alert("Value should be between 0 - 100");
        return false; // added this
    }
    return true; // added this
}

function checkField() {
    var x = document.getElementById("AgencyField").value; // added .value
    if (x === "") { // if (var x = "") -> if (x === "")
        alert("Value should be between 0 - 100");
        return false;
    } else {
        return true;
    }
} // added this }

Fixed HTML:

<form name="agencytrial">
    <div class="textcenter">
        <input name="AgencyRating" id="AgencyField" type="text" value="" autocomplete="off" class="forceNumeric" onkeypress="return handleChange(this)" ; />
        <input class="button" id="FormSubmitButton" type="submit" value="Submit" onclick="return checkField()" />
    </div>
</form>
<!-- Changes to HTML elements:
#FormSubmitButton
- removed ; at the end
- added return to onclick
#AgencyField
- changed onchange to onkeypress
- added return
-->

Upvotes: 1

Rokt33r
Rokt33r

Reputation: 476

This is my solution.

            <form name="agencytrial" onsubmit="return checkField()">
            <div class="textcenter">
                <input name="AgencyRating" id="AgencyField" type="text" value="" autocomplete="off" class="forceNumeric" onchange="handleChange(this)">
                <input class="button" id="FormSubmitButton" type="submit" value="Submit">
            </div>
            </form>

            <script>
            function handleChange(input) {
              if (!(parseInt(input.value) >= 0 && parseInt(input.value) <= 100)) alert("Value should be between 0 - 100");
            }
            function checkField(){
              var input = document.getElementById("AgencyField");

              if (!(parseInt(input.value) >= 0 && parseInt(input.value) <= 100)) {
                alert("Value should be between 0 - 100")
                return false
              }
              return true
            }
            </script>
  1. I use onsubmit instead of onclick.
  2. onsubmit must return false if you want to do nothing.
  3. parseInt makes validation easy.

Have a nice day.

Upvotes: 0

user2575725
user2575725

Reputation:

Try onsubmit handler:

var validate = function(form) {
  var agency = +(form.AgencyField.value) || '';
  if (!agency) {
    alert('Agency has to numeric !');
    return false;
  } else if (0 > agency || 100 < agency) {
    alert('Agency must be between 0 - 100');
    return false;
  } else {
    return true;
  }
};
<form name="agencytrial" onsubmit="return validate(this);">
  <div class="textcenter">
    <input name="AgencyRating" id="AgencyField" type="text" value="" autocomplete="off" class="forceNumeric" />
    <input class="button" type="submit" value="Submit" />
  </div>
</form>

Upvotes: 0

user3720516
user3720516

Reputation:

You should be using the === sign (not the "=" sign). Right now you are conditionally setting x equal to an empty string, not checking if a value exists.

if (var x = ""){

But it should look like

if (x === ""){

Upvotes: 2

adrield
adrield

Reputation: 625

Try this:

<script>
    function handleChange(input) {
        if (input.value < 0 || input.value > 100 || isNaN(input.value)) {
           alert("Value should be between 0 - 100");
        }
    }
</script>

Why:

isNan() is a Javascript function that returns if given parameter is a number. If it's less than 0 OR more than 100 OR not a number, than the message shows up!

Upvotes: 0

Related Questions