If input value is blank, assign a value of “empty” with Javascript

后端 未结 6 1364
庸人自扰
庸人自扰 2021-02-01 21:49

So I have an input field, if it\'s blank, I want its value to be the words \"empty\", but if there is any value inputted, I want the value to be the inputted value. I want to us

相关标签:
6条回答
  • 2021-02-01 22:36

    I think the easiest way to solve this issue, if you only need it on 1 or 2 boxes is by using the HTML input's "onsubmit" function.

    Check this out and i will explain what it does:

    <input type="text" name="val" onsubmit="if(this == ''){$this.val('empty');}" />
    

    So we have created the HTML text box, assigned it a name ("val" in this case) and then we added the onsubmit code, this code checks to see if the current input box is empty and if it is, then, upon form submit it will fill it with the words empty.

    Please note, this code should also function perfectly when using the HTML "Placeholder" tag as the placeholder tag doesn't actually assign a value to the input box.

    0 讨论(0)
  • 2021-02-01 22:48

    You can do this:

    var getValue  = function (input, defaultValue) {
        return input.value || defaultValue;
    };
    
    0 讨论(0)
  • 2021-02-01 22:49

    You can set a callback function for the onSubmit event of the form and check the contents of each field. If it contains nothing you can then fill it with the string "empty":

    <form name="my_form" action="validate.php" onsubmit="check()">
        <input type="text" name="text1" />
        <input type="submit" value="submit" />
    </form>
    

    and in your js:

    function check() {
        if(document.forms["my_form"]["text1"].value == "")
            document.forms["my_form"]["text1"].value = "empty";
    }
    
    0 讨论(0)
  • 2021-02-01 22:50

    If you're using pure JS you can simply do it like:

    var input = document.getElementById('myInput');
    
    if(input.value.length == 0)
        input.value = "Empty";
    

    Here's a demo: http://jsfiddle.net/nYtm8/

    0 讨论(0)
  • 2021-02-01 22:53

    I'm guessing this is what you want...

    When the form is submitted, check if the value is empty and if so, send a value = empty.

    If so, you could do the following with jQuery.

    $('form').submit(function(){
        var input = $('#test').val();
        if(input == ''){
             $('#test').val('empty');
        }    
    });
    

    HTML

    <form> 
        <input id="test" type="text" />
    </form>
    

    http://jsfiddle.net/jasongennaro/NS6Ca/

    Click your cursor in the box and then hit enter to see the form submit the value.

    0 讨论(0)
  • 2021-02-01 22:53

    This can be done using HTML5's placeHolder or using JavaScript. Checkout this post.

    0 讨论(0)
提交回复
热议问题