Wasim Wani
Wasim Wani

Reputation: 555

Javascript onfocusout Uncaught TypeError

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

Upvotes: 0

Views: 49

Answers (2)

Wasim Wani
Wasim Wani

Reputation: 555

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();
                             }

Upvotes: 0

Michael Lorton
Michael Lorton

Reputation: 44426

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.

Upvotes: 2

Related Questions