skip to Main Content

I have page where I want to force user to input certain pre defined values in a text box and if he does not inout those chosen values, focus is shifted back to that text box till user chooses one of the values. My code looks like this

function onloadfunction() {
  alert("On Load!");
  var sourcDealerId = document.getElementById("dsatext");
  sourcDealerId.focus();
}

function getFocusBack() {
  alert("Welcome Back Focus!");
  var sourcDealerId = document.getElementById("dsatext");
  if ((sourcDealerId.value != "DEALER") || (sourcDealerId.value != "MARKET")) {
    alert("Text Box Values::" + sourcDealerId.value)
    alert("Valid Values are DEALER OR MARKET only")
    sourcDealerId = "";
    sourcDealerId.focus();
  }
}
<input type="text" id="dsatext" onfocusout="getFocusBack()" />
<input type="text" id="othertext" />

However when i run this code I encounter following errors

  1. Even when I input values like DEALER or MARKET, it still alerts the message Valid Values are DEALER OR MARKET only
  2. Fcous is not shifted to first text box when i input wrong values
  3. I get the message Uncaught TypeError: sourcDealerId.focus is not a function in console . It pertains to line of code inside getFocusBack() function

2

Answers


  1. Chosen as BEST ANSWER

    I modified the code and put the else condition

    if((sourcDealerId.value === "DEALER") || (sourcDealerId.value === "MARKET") ){
                                          //alert("Text Box Values::"+sourcDealerId.value)
                                          alert("Correct Value");      
                                 }
                                 else{
                                    alert("Valid Values are DEALER OR MARKET only");
                                    sourcDealerId.value="";
                                    sourcDealerId.focus();
                                 }


  2. sourcDealerId = "";
    sourcDealerId.focus();
    

    I get the message Uncaught TypeError

    Well, yeah. You set sourcDealerId to a string, and strings do not have a focus method. Perhaps you wanted

    sourcDealerId.value = "";
    

    although if I were the user, I would be positively enraged that the system was erasing my answer.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search