0

I am trying to create some simple validation for input. If the input has a value of "abc" I want to add a class red to the input and change text color to red. And somehow I want to stop submit the form.

Here is my code so far:

$(document).ready(function () {
    $('#inputname').click(function () {
        if ($("#inputname").val('abc') {
            $("#inputname").addClass(red);
        } else {
            $("#inputname").removeClass(red);
        }
        });
    });

HTML:

<input type="text" value="abc" name="inputname" id="inputname" class="inputname"
  onblur="if (this.value == ``) {this.value = `abc`;}"
  onfocus="if (this.value == `abc`) {this.value = ``;}" />

CSS:

.red { color: #FF0000;}

JSFiddle: https://jsfiddle.net/n5x4q0bp/

3 Answers 3

1

$(document).ready(function() {
  $('#inputname').focusout(function() {
    if ($("#inputname").val() == 'abc') {
      $("#inputname").addClass('red');
      $('#submit_button').attr('onclick', 'return false;');

    } else {
      $("#inputname").removeClass('red');
      $('#submit_button').removeAttr('onclick');
    }
  });
});
<input type="text" value="" name="inputname" id="inputname" class="inputname" onblur="if (this.value == '') {this.value = 'abc';}" onfocus="if (this.value == 'abc') {this.value = '';}" />
<input type="submit" id="submit_button" />

Sign up to request clarification or add additional context in comments.

2 Comments

I had to change $("#inputname").val() == 'abc') to $("#inputname").val() == '') otherwise it was wrong with firefox. but now is all good! Thank you!
Why should the OP "try this"? A good answer will always have an explanation of what was done and why it was done that way, not only for the OP but for future visitors to SO.
1

.val() is a method to set value. You need to get current value and check it

     if ($("#inputname").val()=='abc') {
        $("#inputname").addClass('red');
    } else {
        $("#inputname").removeClass('red');
    }

Comments

1

here is the running code

  $(document).ready(function () {

    $('#inputname').focusout(function () {

        if ($("#inputname").val()=="abc") {
            alert("value");
            $("#inputname").css("color", "RED");

        } else {
            $("#inputname").css("color", "black");
            // your form submit code here
        }
        });


    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.