3

I have an problem with my site when I want to change the css style from the JavaScript it works but only for few seconds.

function validateForm() {
    var fname = document.getElementById('<%=UserFnameTextBox.ClientID%>');
    if (fname.value == "") {
        document.getElementById("WarnUserFnameTextBox").style.opacity = 1;
        document.getElementById('<%=UserFnameTextBox.ClientID%>').style.borderColor = "red";
        getElementById('<%=UserFnameTextBox.ClientID%>').focus;
    }
}

I'm using also Asp.net, that's why I wrote the ID like this

I want that the JS will save the style for as long that the user enter the textbox.

daedsidog
  • 1,732
  • 2
  • 17
  • 36
Mayli
  • 93
  • 9
  • 1
    You're submitting a form, and the page is reloaded as the server response. Notice, that the last line lacks `document` and `()`. – Teemu Dec 14 '18 at 09:47
  • 1
    Like @Teemu said: Your styles are triggering correctly, but as soon as you submit your form, your webpage reloads and falls back to the "default" values, as if the JS would've never been triggered (since it really didn't on that "lifetime"). If you want to make it permanent, I suggest you disable the submit button as long as there are errors. That way the styles will be available as long as there are errors. – DasSaffe Dec 14 '18 at 09:49
  • 1
    please set end of return false – Ravi Chauhan Dec 14 '18 at 09:51
  • 1
    For starters, never access data this way, always assign the return of getElementById to a temporary variable and check it, make sure its valid before trying to access it, your Id references are not valid at least the 2nd and 3rd are not. – SPlatten Dec 14 '18 at 09:52
  • 1
    @RaviChauhan Depending on how the validating function was called, returning false may or may not work. – Teemu Dec 14 '18 at 09:52
  • @SPlatten There's nothing wrong with the 2nd id, and aren't the rest of the ids filled in at the serverside before sending the page? – Teemu Dec 14 '18 at 09:55
  • @Teemu, the return should be checked before use! – SPlatten Dec 14 '18 at 10:24
  • @SPlatten Not sure what you mean, but `return false` can be used to prevent the submission only when the function is called from an online submit event handler, which returns the return value of this function. – Teemu Dec 14 '18 at 10:29
  • @Teemu, using the return of a function without checking the return can cause an exception because you could be try to de-reference undefined or null. – SPlatten Dec 15 '18 at 15:28

2 Answers2

3

Multiple things here: I suggest that your validateForm() function triggers in an onClick on your submit-button, right? Does your button look somewhat like this?

<input type="submit" value="submit" onClick="validateForm()">

If this is the case, the reason why your styles work only for few seconds is simply that the website reloads. The styles are in effect, but the form is also triggering and send to the site, which you added in your <form action>. After reloading, the website will fall back to its default style, as if the errors never occured... which is correct on that instance of the site.

If you want to have it permanent, you have to disable the submit-button as long as there are invalid fields. You can make use of the required attribute for form elements as well, since the form won't submit as long as there are invalid fields. These can be styled as well.

Have a look at these CSS rules for that:

/* style all elements with a required attribute */
:required {
    background: red;
}

You can make use of jQuery as well and disable the form-submit with preventDefault. You can take care of every style and adjust accordingly, as long as there empty / non-valid characters in your input-fields. I suggest combining this with the onKeyUp-function. This way you check everytime the users releases a key and can react as soon as your input is valid.

As an example with jQuery:

var $fname   = $('#<%=UserFnameTextBox.ClientID%>');
var $textBox = $('#WarnUserFnameTextBox');

$fname.on("input", function() {
    var $this = $(this);
    if($this.val() == "") {
        $textBox.show();
        $this.focus().css("border", "1px solid red");
    }
}); 

(thanks for pointing out my errors and optimizing the code, @mplungjan!).

To "disable" the actual form-submission, refer to this answer: https://stackoverflow.com/a/6462306/3372043

$("#yourFormID").submit(function(e){
    return false;
});

This is untested, feel free to point out my mistake, since I can't check it right now. You can play around on how you want to approach your "errorhandling", maybe switch to onKeyDown() or change(), that kind of depends on your needs / usecase.

Since your question isn't tagged with jQuery, have a look at this answer given by mplungjan as well, since it uses native JS without any framework. https://stackoverflow.com/a/53777747/3372043

DasSaffe
  • 2,080
  • 1
  • 28
  • 67
  • 1
    you want `var $fname = $('#<%=UserFnameTextBox.ClientID%>') ` and `$fname.on("input", function() { if($(this).val() == "") {` - not keyup - and not tagged jQuery – mplungjan Dec 14 '18 at 10:21
  • 1
    You keep making jQuery object from jQuery object. Not needed – mplungjan Dec 14 '18 at 10:24
  • 1
    Thanks for pointing that out @mplungjan! Appreciated. Credit where credit is due. Also you are right with no jQuery tag. I'll link to your answer as well – DasSaffe Dec 14 '18 at 10:25
  • 1
    `var $fname = $('#<%=UserFnameTextBox.ClientID%>'), $textBox = $('#WarnUserFnameTextBox'); $fname.on("input", function() { var $this = $(this); if ($this.val() == "") { $textBox.show(); $this.focus().css("border", "1px solid red"); } }) ` - or better toggle the textbox – mplungjan Dec 14 '18 at 10:27
1

This is likely what you want. It will stop the form from being submitted and is reusing the field and resetting if no error

It assumes <form id="myForm"

window.addEventListener("load", function() {
  document.getElementById("myForm").addEventListener("submit", function(e) {
    var field = document.getElementById('<%=UserFnameTextBox.ClientID%>');
    var error = field.value.trim() === "";
    document.getElementById("WarnUserFnameTextBox").style.opacity = error ? "1" : "0"; // or style.display=error?"block":"none";
    field.style.borderColor = error ? "red" : "black"; // reset if no error
    if (error) {
      field.focus();
      e.preventDefault();
    }
  });
});
mplungjan
  • 169,008
  • 28
  • 173
  • 236