Sebastian
Sebastian

Reputation: 4811

reset textbox value on change event using jquery

I have a textbox and i am doing a validation on its data on input change event. I am checking the existence of a specific word in the text field and if this keyword is present proceed further otherwise i am showing an alert and i want to reset the value at this point

    <input type="text" value="$name$" id="text_messageinput" />

the input box will loaded with value $name$ and if user tries to edit this part of the text i have to prevent that For doing so i tried this code

    $("#text_messageinput").on('input', function () {
        var input_value = $(this).val();
        if (input_value) {
            var inputs_ok = true;
            var selected_name = $("#chk_addname").is(":checked");
            if (selected_name == true) {
                var text_input = $("#text_messageinput").val();
                if (text_input.indexOf("$name$") === -1) {
                    alert("$name$ should be in message");
                    inputs_ok = false;
                    //i have to reset textbox value to prev value
                }
            }
        }
    });

So how can i reset the value back when validation error occurs

Upvotes: 1

Views: 1020

Answers (1)

Deep
Deep

Reputation: 9794

Something like this will help. save the old value manually and use this to reset value.

$("#text_messageinput").on('input', function () {
        var input_value = $(this).val();
        if (input_value) {
            var inputs_ok = true;
            var selected_name = $("#chk_addname").is(":checked");

                var text_input = $("#text_messageinput").val();
          
                if (text_input.indexOf("$name$") === -1 || text_input == "") {
                    alert("$name$ should be in message");
                    inputs_ok = false;
                                    $("#text_messageinput").val($("#text_messageinput").attr('data'));
                }
                else
                {
                  $("#text_messageinput").attr('data',text_input);
                }
        }
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" data="$name$" value="$name$" id="text_messageinput" />

Upvotes: 1

Related Questions