<! DOCTYPE html> <Html> <Head> <Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8"/> <Title> one JavaScript instance per day-detect form data </title> <Style> [Role = "alert"] { Background-color: # fcc; Font-weight: bold; Padding: 5px; Border: 1px dashed #000; } Div { Margin: 10px 0; Padding: 5px; Width: 400px; Background-color: # fff; } </Style> <Script> Window. onload = function (){ Document. getElementById ("thirdfield"). onchange = validateField; Document. getElementById ("firstfield"). onblur = mandatoryField; Document. getElementById ("testform"). onsubmit = finalCheck; } Function validateField (){ RemoveAlert (); If (! IsNaN (parseFloat (this. value ))){ ResetField (this ); } Else { BadField (this ); GenerateAlert ("You entered an invalid value in Third Field. only numeric values such as 105 or 3.45 are allowed "); } } Function removeAlert (){ Var msg = document. getElementById ("msg "); If (msg ){ Document. body. removeChild (msg ); } } Function resetField (elem ){ Elem. parentNode. setAttribute ("style", "background-color: # fff "); Var valid = elem. getAttribute ("aria-invalid "); If (valid) elem. removeAttribute ("aria-invalid "); } Function badField (elem ){ Elem. parentNode. setAttribute ("style", "background-color # attributes "); Elem. setAttribute ("aria-invalid", "true "); } Function generateAlert (txt ){ Var txtNd = document. createTextNode (txt ); Msg = document. createElement ("div "); Msg. setAttribute ("role", "alert "); Msg. setAttribute ("id", "msg "); Msg. setAttribute ("class", "alert "); Msg. appendChild (txtNd ); Document. body. appendChild (msg ); } Function mandatoryField (){ RemoveAlert (); If (this. value. length> 0 ){ ResetField (this ); } Else { BadField (this ); GenerateAlert ("You must enter a value into First Field "); } } Function finalCheck (){ // Console. log ("aaa "); RemoveAlert (); Var fields = document. querySelectorAll ('input [aria-invalid = "true"] '); // Var fields = document. querySelectorAll ("input [aria-invalid = 'true']"); // Error !!! Console. log (fields ); If (fields. length> 0 ){ GenerateAlert ("You have incorrect fields entries that must be fixed before you can submit this form "); Return false; } } </Script> </Head> <Body> <Form id = "testform"> <Div> <Label for = "firstfield"> * first Field: </label> <br/> <Input id = "firstfield" name = "firstfield" type = "text" aria-required = "true"/> </Div> <Div> <Label for = "secondfield"> Second Field: </label> <br/> <Input id = "secondfield" name = "secondfield" type = "text"/> </Div> <Div> <Label for = "thirdfield"> Third Field (numeric): </label> <br/> <Input id = "thirdfield" name = "thirdfield" type = "text"/> </Div> <Div> <Label for = "fourthfield"> Fourth Field: </label> <br/> <Input id = "fourthfield" name = "fourthfield" type = "text"/> </Div> <Input type = "submit" value = "Send Data"/> </Form> </Body> </Html> |