Best JavaScript code snippet using playwright-internal
register.js
Source:register.js
1$(document).ready(function() {2 var errorStatusHandle = $('#message_line');3 var elementHandle = new Array();4 elementHandle[0] = $('[name="program"]');5 elementHandle[1] = $('[name="fname"]');6 elementHandle[2] = $('[name="lname"]');7 elementHandle[3] = $('[name="mname"]');8 elementHandle[4] = $('[name="nickname"]');9 elementHandle[5] = $('[name="dob"]');10 elementHandle[6] = $('[name="email"]');11 elementHandle[7] = $('[name="gender"]');12 elementHandle[8] = $('[name="photo"]');13 elementHandle[9] = $('[name="relationship"]');14 elementHandle[10] = $('[name="pfname"]');15 elementHandle[11] = $('[name="plname"]');16 elementHandle[12] = $('[name="pmname"]');17 elementHandle[13] = $('[name="pemail"]');18 elementHandle[14] = $('[name="address1"]');19 elementHandle[15] = $('[name="address2"]');20 elementHandle[16] = $('[name="city"]');21 elementHandle[17] = $('[name="state"]');22 elementHandle[18] = $('[name="zipcode"]');23 elementHandle[19] = $('[name="home_phone_area"]');24 elementHandle[20] = $('[name="home_phone_prefix"]');25 elementHandle[21] = $('[name="home_phone"]');26 elementHandle[22] = $('[name="cell_phone_area"]');27 elementHandle[23] = $('[name="cell_phone_prefix"]');28 elementHandle[24] = $('[name="cell_phone"]');29 elementHandle[25] = $('[name="medical_conditions"]');30 elementHandle[26] = $('[name="special_req"]');31 elementHandle[27] = $('[name="ename"]');32 elementHandle[28] = $('[name="emer_cell_phone_area"]');33 elementHandle[29] = $('[name="emer_cell_phone_prefix"]');34 elementHandle[30] = $('[name="emer_cell_phone"]');35 function handleAnswer(answer) {36 if($.trim(answer) == "OK") {37 var params = $('form').serialize();38 send_file_parent();39 }40 else if ($.trim(answer) == "PDUP") {41 var params = $('form').serialize();42 send_file_child();43 } 44 else if ($.trim(answer) == "CDUP")45 $('#status').html("ERROR, Duplicate");46 else47 $('#status').html("Database error"); 48 }49 function handleAjaxPost(answer) {50 $('#status').html(answer);51 } 52 function send_file_parent() { 53 var form_data = new FormData($('form')[0]); 54 form_data.append("image", document.getElementById("photo").files[0]);55 $.ajax({56 url: 'ajax_file_upload.php', 57 dataType: 'text', 58 cache: false,59 contentType: false,60 processData: false,61 data: form_data, 62 type: 'post',63 success: function(response) {64 $('#pic').html("");65 if(response == 'File is not an image.') {66 $('#status').html("File is not an image.");67 }68 else if (response == 'Sorry, file already exists.') {69 $('#status').html("Sorry, choose a different image file name.");70 }71 else if (response == 'Sorry, your file is too large.') {72 $('#status').html("Sorry, your file is too large.");73 }74 else if (response == 'Sorry, only JPG, JPEG, PNG & GIF files are allowed.') {75 $('#status').html("Sorry, only JPG, JPEG, PNG & GIF files are allowed.");76 }77 else if (response == 'Sorry, your file was not uploaded.') {78 $('#status').html("Sorry, your file was not uploaded.");79 }80 else if (response == 'Sorry, there was an error uploading your file.') {81 $('#status').html("Sorry, there was an error uploading your file.");82 }83 else if (response == 'The file has been uploaded.') {84 $('#status').html("The file has been uploaded.");85 var fname = $("#photo").val();86 var toDisplay = "<img src=\"/~jadrn042/proj2-b/uplo_ds/" + fname + "\" />"; 87 $('#pic').html(toDisplay);88 var params = 89 "relationship=" + $("[name='relationship']").val() +90 "&pfname=" + $("[name='pfname']").val() +91 "&pmname=" + $("[name='pmname']").val() +92 "&plname=" + $("[name='plname']").val() +93 "&pemail=" + $("[name='pemail']").val() +94 "&address1=" + $("[name='address1']").val() +95 "&address2=" + $("[name='address2']").val() +96 "&city=" + $("[name='city']").val() +97 "&state=" + $("[name='state']").val() +98 "&zipcode=" + $("[name='zipcode']").val() +99 "&home_phone_area=" + $("[name='home_phone_area']").val() +100 "&home_phone_prefix=" + $("[name='home_phone_prefix']").val() +101 "&home_phone=" + $("[name='home_phone']").val() +102 "&cell_phone_area=" + $("[name='cell_phone_area']").val() +103 "&cell_phone_prefix=" + $("[name='cell_phone_prefix']").val() +104 "&cell_phone=" + $("[name='cell_phone']").val() +105 "&program=" + $("[name='program']").val() +106 "&fname=" + $("[name='fname']").val() +107 "&mname=" + $("[name='mname']").val() +108 "&lname=" + $("[name='lname']").val() +109 "&nickname=" + $("[name='nickname']").val() +110 "&dob=" + $("[name='dob']").val() +111 "&gender=" + $("input[name=gender]:checked").val() +112 "&photo=" + $("[name='photo']").val() +113 "&medical_conditions=" + $("[name='medical_conditions']").val() +114 "&special_req=" + $("[name='special_req']").val() +115 "&ename=" + $("[name='ename']").val() +116 "&emer_cell_phone_area=" + $("[name='emer_cell_phone_area']").val() +117 "&emer_cell_phone_prefix=" + $("[name='emer_cell_phone_prefix']").val() +118 "&emer_cell_phone=" + $("[name='emer_cell_phone']").val(); 119 params = encodeURI(params);120 $.post('ajax_process_request.php', params,handleAjaxPost);121 }122 },123 error: function(response) {124 alert(response);125 $('#status').css('color','red');126 $('#status').html("Sorry, an upload error occurred, "+response.statusText);127 }128 });129}130function send_file_child() { 131 var form_data = new FormData($('form')[0]); 132 form_data.append("image", document.getElementById("photo").files[0]);133 $.ajax({134 url: 'ajax_file_upload.php',135 dataType: 'text', 136 cache: false,137 contentType: false,138 processData: false,139 data: form_data, 140 type: 'post',141 success: function(response) {142 $('#pic').html("");143 if(response == 'File is not an image.') {144 $('#status').html("File is not an image.");145 }146 else if (response == 'Sorry, file already exists.') {147 $('#status').html("Sorry, file already exists.");148 }149 else if (response == 'Sorry, your file is too large.') {150 $('#status').html("Sorry, your file is too large.");151 }152 else if (response == 'Sorry, only JPG, JPEG, PNG & GIF files are allowed.') {153 $('#status').html("Sorry, only JPG, JPEG, PNG & GIF files are allowed.");154 }155 else if (response == 'Sorry, your file was not uploaded.') {156 $('#status').html("Sorry, your file was not uploaded.");157 }158 else if (response == 'Sorry, there was an error uploading your file.') {159 $('#status').html("Sorry, there was an error uploading your file.");160 }161 else if (response == 'The file has been uploaded.') {162 $('#status').html("The file has been uploaded.");163 var fname = $("#photo").val();164 var toDisplay = "<img src=\"/~jadrn042/proj2-b/uplo_ds/" + fname + "\" />"; 165 $('#pic').html(toDisplay);166 var params = "relationship=" + $("[name='relationship']").val() +167 "&pfname=" + $("[name='pfname']").val() +168 "&pmname=" + $("[name='pmname']").val() +169 "&plname=" + $("[name='plname']").val() +170 "&pemail=" + $("[name='pemail']").val() +171 "&address1=" + $("[name='address1']").val() +172 "&address2=" + $("[name='address2']").val() +173 "&city=" + $("[name='city']").val() +174 "&state=" + $("[name='state']").val() +175 "&zipcode=" + $("[name='zipcode']").val() +176 "&home_phone_area=" + $("[name='home_phone_area']").val() +177 "&home_phone_prefix=" + $("[name='home_phone_prefix']").val() +178 "&home_phone=" + $("[name='home_phone']").val() +179 "&cell_phone_area=" + $("[name='cell_phone_area']").val() +180 "&cell_phone_prefix=" + $("[name='cell_phone_prefix']").val() +181 "&cell_phone=" + $("[name='cell_phone']").val() +182 "&program=" + $("[name='program']").val() +183 "&fname=" + $("[name='fname']").val() +184 "&mname=" + $("[name='mname']").val() +185 "&lname=" + $("[name='lname']").val() +186 "&nickname=" + $("[name='nickname']").val() +187 "&dob=" + $("[name='dob']").val() +188 "&gender=" + $("input[name=gender]:checked").val() +189 "&photo=" + $("[name='photo']").val() +190 "&medical_conditions=" + $("[name='medical_conditions']").val() +191 "&special_req=" + $("[name='special_req']").val() +192 "&ename=" + $("[name='ename']").val() +193 "&emer_cell_phone_area=" + $("[name='emer_cell_phone_area']").val() +194 "&emer_cell_phone_prefix=" + $("[name='emer_cell_phone_prefix']").val() +195 "&emer_cell_phone=" + $("[name='emer_cell_phone']").val(); 196 params = encodeURI(params);197 $.post('ajax_process_request_child.php', params,handleAjaxPost);198 }199 },200 error: function(response) {201 $('#pic').html("");202 $('#status').css('color','red');203 $('#status').html("Sorry, an upload error occurred, "+response.statusText);204 }205 });206}207function isEmpty(fieldValue) {208 return $.trim(fieldValue).length == 0; 209}210 // Check for valid date211 // Code from : http://www.jquerybyexample.net/2011/12/validate-date-using-jquery.html212 function isDate(txtDate)213 {214 var currVal = txtDate;215 if(currVal == '')216 return false;217 218 //Declare Regex 219 var rxDatePattern = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/; 220 var dtArray = currVal.match(rxDatePattern); // is format OK?221 if (dtArray == null)222 return false;223 224 //Checks for mm/dd/yyyy format.225 dtMonth = dtArray[1];226 dtDay= dtArray[3];227 dtYear = dtArray[5];228 if (dtMonth < 1 || dtMonth > 12)229 return false;230 else if (dtDay < 1 || dtDay> 31)231 return false;232 else if ((dtMonth==4 || dtMonth==6 || dtMonth==9 || dtMonth==11) && dtDay ==31)233 return false;234 else if (dtMonth == 2)235 {236 var isleap = (dtYear % 4 == 0 && (dtYear % 100 != 0 || dtYear % 400 == 0));237 if (dtDay> 29 || (dtDay ==29 && !isleap))238 return false;239 }240 return true;241}242 // ------------End of function--------------243 // ------------Check if age>12 and <18 -----244 function isAge(value)245 {246 var dateOfBirth = value;247 var arr_dateText = dateOfBirth.split("/");248 month = arr_dateText[0];249 day = arr_dateText[1];250 year = arr_dateText[2];251 var dob = new Date(year, month - 1, day, 0, 0, 0);252 var campDate = new Date(2015, 5, 1, 0, 0, 0);253 var maxDate = new Date(campDate.getFullYear() - 12, campDate.getMonth(), campDate.getDate()+1, 0, 0, 0);254 var minDate = new Date(campDate.getFullYear() - 18, campDate.getMonth(), campDate.getDate()-1, 0, 0, 0);255 if ((dob > minDate)&&(dob < maxDate)) {256 return true;257 }258 return false;259 }260 function isEmail(fieldValue) {261 var re = /^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i;262 return re.test(fieldValue);263 }264 function isAddress(fieldValue) {265 var re = /^[a-zA-Z0-9] ?([a-zA-Z0-9-\/]|[a-zA-Z0-9-\/] )*[a-zA-Z0-9-\/]$/;266 return re.test(fieldValue);267 }268 function isState(state) { 269 var stateList = new Array("AK","AL","AR","AZ","CA","CO","CT","DC",270 "DC2","DE","FL","GA","GU","HI","IA","ID","IL","IN","KS","KY","LA",271 "MA","MD","ME","MH","MI","MN","MO","MS","MT","NC","ND","NE","NH",272 "NJ","NM","NV","NY","OH","OK","OR","PA","PR","RI","SC","SD","TN",273 "TX","UT","VA","VT","WA","WI","WV","WY","AS", "DC", "FM", "GU", 274 "MH", "MP", "PR", "PW", "VI");275 for(var i=0; i < stateList.length; i++) 276 if(stateList[i] == $.trim(state.toUpperCase()))277 return true;278 return false;279 }280 function isCity (city) {281 var re = /^[a-zA-z] ?([a-zA-z]|[a-zA-z] )*[a-zA-z]$/;282 return re.test(city);283 }284 function isZip (zip) {285 var re = /^\d{5}$/;286 return re.test(zip);287 }288 function isAreaPrefix(fieldValue) {289 var re = /^\d{3}$/;290 return re.test(fieldValue);291 }292 function isPhone(value) {293 var re = /^\d{4}$/;294 return re.test(value);295 }296 function isSelected(value) {297 if (value.length == 0 || value == "") {298 return false;299 }300 return true;301 }302 $("#relationship").focus();303 $('#program').on('change', function() {304 var input=$(this);305 if(isSelected(input)) {306 input.removeClass("invalid").addClass("valid");307 errorStatusHandle.text("");308 $("#fname").focus();309 }310 }); 311 $('.name').on('input', function() {312 var input=$(this);313 var name=$.trim(input.val());314 if(!name) {315 input.removeClass("valid invalid border_invalid");316 }317 else {318 if(!isEmpty(name)){319 input.removeClass("invalid").addClass("valid");320 errorStatusHandle.text("");321 }322 else{323 input.removeClass("valid").addClass("invalid");324 }325 }326 });327 $('.dob').on('input', function() {328 var input=$(this);329 var dob=$.trim(input.val());330 if(!dob) {331 input.removeClass("invalid valid border_invalid");332 }333 else {334 if(isDate(dob)) {335 if(isAge(dob)) {336 input.removeClass("invalid").addClass("valid");337 errorStatusHandle.text("");338 $("#email").focus();339 }340 }341 else {342 input.removeClass("valid").addClass("invalid");343 } 344 } 345 });346 $('.dob').focusout(function() {347 var input=$(this);348 if(input.hasClass("invalid")) {349 errorStatusHandle.text("*It should be a valid date and child should be between 12-18 years of age to register");350 input.removeClass("invalid").addClass("border_invalid");351 } 352 });353 $(':radio').change(function () {354 $(':radio[name=' + this.name + ']').removeClass('invalid border_invalid');355 $(this).addClass('valid border_valid');356 errorStatusHandle.text("");357 });358 $('#relationship').on('change', function() {359 var input=$(this);360 if(isSelected(input)) {361 input.removeClass("invalid").addClass("valid");362 errorStatusHandle.text("");363 $("#pfname").focus();364 }365 }); 366 <!--Email must be an email -->367 $('#email,#pemail').on('input', function() {368 var input=$(this);369 var email=$.trim(input.val());370 if(!email) {371 input.removeClass("invalid valid border_invalid");372 }373 else {374 if(isEmail(email)) {375 input.removeClass("invalid").addClass("valid");376 errorStatusHandle.text("");377 }378 else {379 input.removeClass("valid").addClass("invalid");380 }381 }382 });383 $('#email,#pemail').focusout(function() {384 var input=$(this);385 if(input.hasClass("invalid")) {386 errorStatusHandle.text("*Enter a valid email Id");387 input.removeClass("invalid").addClass("border_invalid");388 } 389 });390 <!--Address -->391 $('.address').on('input', function() {392 var input=$(this);393 var address=$.trim(input.val());394 if(!address) {395 input.removeClass("valid invalid border_invalid");396 }397 else {398 if(!isEmpty(address)){399 input.removeClass("invalid").addClass("valid");400 errorStatusHandle.text("");401 }402 else{403 input.removeClass("valid").addClass("invalid");404 }405 }406 });407 $('.address').focusout(function() {408 var input=$(this);409 if(input.hasClass("invalid")) {410 input.removeClass("invalid").addClass("border_invalid");411 } 412 });413 // ----State----414 $('#state').on('input', function() {415 var input=$(this);416 var state=$.trim(input.val());417 if(!state) {418 input.removeClass("valid invalid border_invalid");419 }420 else {421 if(!isState(state)){422 input.removeClass("valid").addClass("invalid");423 }424 else{425 input.removeClass("invalid").addClass("valid");426 errorStatusHandle.text("");427 }428 }429 });430 $('#state').focusout(function() {431 var input=$(this);432 if(input.hasClass("invalid")) {433 errorStatusHandle.text("*The state appears to be invalid, "+434 "Please use the two letter state abbreviation");435 input.removeClass("invalid").addClass("border_invalid");436 } 437 });438 $('#city').on('input', function() {439 var input=$(this);440 var city=$.trim(input.val());441 if(!city) {442 input.removeClass("valid invalid border_valid border_invalid");443 }444 else {445 if(isCity(city)){446 input.removeClass("invalid").addClass("valid");447 errorStatusHandle.text("");448 }449 else{450 input.removeClass("valid").addClass("invalid");451 }452 }453 });454 $('#city').focusout(function() {455 var input=$(this);456 if(input.hasClass("invalid")) {457 errorStatusHandle.text("*City should contain only alphabets");458 input.removeClass("invalid").addClass("border_invalid");459 } 460 });461 $('#zip').on('input', function() {462 var input=$(this);463 var zip=$.trim(input.val());464 if(!zip) {465 input.removeClass("valid invalid border_valid border_invalid");466 }467 else {468 if(isZip(zip)){469 input.removeClass("invalid").addClass("valid");470 errorStatusHandle.text("");471 $("#home_phone_area").focus();472 }473 else{474 input.removeClass("valid").addClass("invalid");475 }476 }477 });478 $('#zip').focusout(function() {479 var input=$(this);480 if(input.hasClass("invalid")) {481 errorStatusHandle.text("*Zip should contain only numbers, and should have only 5 digits");482 input.removeClass("invalid").addClass("border_invalid");483 } 484 });485 $('#home_phone_area').on('input', function() {486 var input=$(this);487 var area=$.trim(input.val());488 if(!area) {489 input.removeClass("valid invalid border_valid border_invalid");490 }491 else {492 if(isAreaPrefix(area)){493 input.removeClass("invalid").addClass("valid");494 errorStatusHandle.text("");495 $("#home_phone_prefix").focus();496 }497 else{498 input.removeClass("valid").addClass("invalid");499 }500 }501 });502 $('#home_phone_area').focusout(function() {503 var input=$(this);504 if(input.hasClass("invalid")) {505 errorStatusHandle.text("*Please enter a valid phone number");506 input.removeClass("invalid").addClass("border_invalid");507 } 508 });509 $('#home_phone_prefix').on('input', function() {510 var input=$(this);511 var value=$.trim(input.val());512 if(!value) {513 input.removeClass("valid invalid border_valid border_invalid");514 }515 else {516 if(isAreaPrefix(value)){517 input.removeClass("invalid").addClass("valid");518 errorStatusHandle.text("");519 $("#home_phone").focus();520 }521 else{522 input.removeClass("valid").addClass("invalid");523 }524 }525 });526 $('#home_phone_prefix').focusout(function() {527 var input=$(this);528 if(input.hasClass("invalid")) {529 errorStatusHandle.text("*Please enter a valid phone number");530 input.removeClass("invalid").addClass("border_invalid");531 } 532 });533 $('#home_phone').on('input', function() {534 var input=$(this);535 var value=$.trim(input.val());536 if(!value) {537 input.removeClass("valid invalid border_valid border_invalid");538 }539 else {540 if(isPhone(value)){541 input.removeClass("invalid").addClass("valid");542 errorStatusHandle.text("");543 $("#cell_phone_area").focus();544 }545 else{546 input.removeClass("valid").addClass("invalid");547 }548 }549 });550 $('#home_phone').focusout(function() {551 var input=$(this);552 if(input.hasClass("invalid")) {553 errorStatusHandle.text("*Please enter a valid phone number");554 input.removeClass("invalid").addClass("border_invalid");555 } 556 });557 $('#cell_phone_area').on('input', function() {558 var input=$(this);559 var value=$.trim(input.val());560 if(!value) {561 input.removeClass("valid invalid border_valid border_invalid");562 }563 else {564 if(isAreaPrefix(value)){565 input.removeClass("invalid").addClass("valid");566 errorStatusHandle.text("");567 $("#cell_phone_prefix").focus();568 }569 else{570 input.removeClass("valid").addClass("invalid");571 }572 }573 });574 $('#cell_phone_area').focusout(function() {575 var input=$(this);576 if(input.hasClass("invalid")) {577 errorStatusHandle.text("*Please enter a valid phone number");578 input.removeClass("invalid").addClass("border_invalid");579 } 580 });581 $('#cell_phone_prefix').on('input', function() {582 var input=$(this);583 var value=$.trim(input.val());584 if(!value) {585 input.removeClass("valid invalid border_valid border_invalid");586 }587 else {588 if(isAreaPrefix(value)){589 input.removeClass("invalid").addClass("valid");590 errorStatusHandle.text("");591 $("#cell_phone").focus();592 }593 else{594 input.removeClass("valid").addClass("invalid");595 }596 }597 });598 $('#cell_phone_prefix').focusout(function() {599 var input=$(this);600 if(input.hasClass("invalid")) {601 errorStatusHandle.text("*Please enter a valid phone number");602 input.removeClass("invalid").addClass("border_invalid");603 } 604 });605 $('#cell_phone').on('input', function() {606 var input=$(this);607 var value=$.trim(input.val());608 if(!value) {609 input.removeClass("valid invalid border_valid border_invalid");610 }611 else {612 if(isPhone(value)) {613 input.removeClass("invalid").addClass("valid");614 errorStatusHandle.text("");615 $("#program").focus();616 }617 else{618 input.removeClass("valid").addClass("invalid");619 }620 }621 });622 $('#cell_phone').focusout(function() {623 var input=$(this);624 if(input.hasClass("invalid")) {625 errorStatusHandle.text("*Please enter a valid phone number");626 input.removeClass("invalid").addClass("border_invalid");627 } 628 });629 $('#emer_cell_phone_area').on('input', function() {630 var input=$(this);631 var value=$.trim(input.val());632 if(!value) {633 input.removeClass("valid invalid border_valid border_invalid");634 }635 else {636 if(isAreaPrefix(value)){637 input.removeClass("invalid").addClass("valid");638 errorStatusHandle.text("");639 $("#emer_cell_phone_prefix").focus();640 }641 else{642 input.removeClass("valid").addClass("invalid");643 }644 }645 });646 $('#emer_cell_phone_area').focusout(function() {647 var input=$(this);648 if(input.hasClass("invalid")) {649 errorStatusHandle.text("*Please enter a valid phone number");650 input.removeClass("invalid").addClass("border_invalid");651 } 652 });653 $('#emer_cell_phone_prefix').on('input', function() {654 var input=$(this);655 var value=$.trim(input.val());656 if(!value) {657 input.removeClass("valid invalid border_valid border_invalid");658 }659 else {660 if(isAreaPrefix(value)){661 input.removeClass("invalid").addClass("valid");662 errorStatusHandle.text("");663 $("#emer_cell_phone").focus();664 }665 else{666 input.removeClass("valid").addClass("invalid");667 }668 }669 });670 $('#emer_cell_phone_prefix').focusout(function() {671 var input=$(this);672 if(input.hasClass("invalid")) {673 errorStatusHandle.text("*Please enter a valid phone number");674 input.removeClass("invalid").addClass("border_invalid");675 } 676 });677 $('#emer_cell_phone').on('input', function() {678 var input=$(this);679 var value=$.trim(input.val());680 if(!value) {681 input.removeClass("valid invalid border_valid border_invalid");682 }683 else {684 if(isPhone(value)) {685 input.removeClass("invalid").addClass("valid");686 errorStatusHandle.text("");687 $("#submit").focus();688 }689 else{690 input.removeClass("valid").addClass("invalid");691 }692 }693 });694 $('#emer_cell_phone').focusout(function() {695 var input=$(this);696 if(input.hasClass("invalid")) {697 errorStatusHandle.text("*Please enter a valid phone number");698 input.removeClass("invalid").addClass("border_invalid");699 } 700 });701 function isValidData() {702 if(!isSelected(elementHandle[9].val())) {703 elementHandle[9].addClass("border_invalid");704 errorStatusHandle.text("*Please select the relationship");705 elementHandle[9].focus();706 return false;707 }708 if(isEmpty($.trim(elementHandle[10].val()))) {709 elementHandle[10].addClass("border_invalid");710 errorStatusHandle.text("*Please enter parent/guardian's First Name");711 elementHandle[10].focus(); 712 return false;713 }714 if(isEmpty($.trim(elementHandle[11].val()))) {715 elementHandle[11].addClass("border_invalid");716 errorStatusHandle.text("*Please enter parent/guardian's Last Name");717 elementHandle[11].focus(); 718 return false;719 }720 if(isEmpty($.trim(elementHandle[13].val()))) {721 elementHandle[13].addClass("border_invalid");722 errorStatusHandle.text("*Please enter parent/guardian's email id");723 elementHandle[13].focus(); 724 return false;725 }726 if(!isEmail($.trim(elementHandle[13].val()))) {727 elementHandle[13].addClass("border_invalid");728 errorStatusHandle.text("*Please enter a valid email id");729 elementHandle[13].focus(); 730 return false;731 }732 if(isEmpty($.trim(elementHandle[14].val()))) {733 elementHandle[14].addClass("border_invalid");734 errorStatusHandle.text("*Please enter the address");735 elementHandle[14].focus(); 736 return false;737 }738 if(isEmpty($.trim(elementHandle[16].val()))) { 739 elementHandle[16].addClass("border_invalid");740 errorStatusHandle.text("*Please enter the city");741 elementHandle[16].focus(); 742 return false;743 }744 if(!isCity($.trim(elementHandle[16].val()))) {745 elementHandle[16].addClass("border_invalid");746 errorStatusHandle.text("*Please enter a valid city name");747 elementHandle[16].focus(); 748 return false;749 }750 if(isEmpty($.trim(elementHandle[17].val()))) { 751 elementHandle[17].addClass("border_invalid");752 errorStatusHandle.text("*Please enter the State");753 elementHandle[17].focus(); 754 return false;755 }756 if(!isState($.trim(elementHandle[17].val()))) {757 elementHandle[17].addClass("border_invalid");758 errorStatusHandle.text("*The state appears to be invalid, "+759 "Please use the two letter state abbreviation");760 elementHandle[17].focus(); 761 return false;762 }763 if(isEmpty($.trim(elementHandle[18].val()))) { 764 elementHandle[18].addClass("border_invalid");765 errorStatusHandle.text("*Please enter the Zip code");766 elementHandle[18].focus(); 767 return false;768 }769 if(!$.isNumeric($.trim(elementHandle[18].val()))) {770 elementHandle[18].addClass("border_invalid");771 errorStatusHandle.text("*The zip code appears to be invalid, "+772 "numbers only please. ");773 elementHandle[18].focus(); 774 return false;775 }776 if($.trim(elementHandle[18].val()).length != 5) {777 elementHandle[18].addClass("border_invalid");778 errorStatusHandle.text("*The zip code must have exactly five digits")779 elementHandle[18].focus(); 780 return false;781 }782 if(!isEmpty($.trim(elementHandle[19].val()))) {783 if(!isAreaPrefix($.trim(elementHandle[19].val()))) {784 elementHandle[19].addClass("border_invalid");785 errorStatusHandle.text("*Please enter a valid area code");786 elementHandle[19].focus(); 787 return false;788 }789 }790 if(!isEmpty($.trim(elementHandle[20].val()))) { 791 if(!isAreaPrefix($.trim(elementHandle[20].val()))) {792 elementHandle[20].addClass("border_invalid");793 errorStatusHandle.text("*Please enter a valid phone number prefix");794 elementHandle[20].focus(); 795 return false;796 }797 }798 if(!isEmpty($.trim(elementHandle[21].val()))) { 799 if(!isPhone($.trim(elementHandle[21].val()))) {800 elementHandle[21].addClass("border_invalid");801 errorStatusHandle.text("*Please enter a valid phone number");802 elementHandle[21].focus(); 803 return false;804 }805 }806 if(isEmpty($.trim(elementHandle[22].val()))) { 807 elementHandle[22].addClass("border_invalid");808 errorStatusHandle.text("*Please enter the area code");809 elementHandle[22].focus(); 810 return false;811 }812 if(!isAreaPrefix($.trim(elementHandle[22].val()))) {813 elementHandle[22].addClass("border_invalid");814 errorStatusHandle.text("*Please enter a valid area code");815 elementHandle[22].focus(); 816 return false;817 }818 if(isEmpty($.trim(elementHandle[23].val()))) { 819 elementHandle[23].addClass("border_invalid");820 errorStatusHandle.text("*Please enter the phone number prefix");821 elementHandle[23].focus(); 822 return false;823 }824 if(!isAreaPrefix($.trim(elementHandle[23].val()))) {825 elementHandle[23].addClass("border_invalid");826 errorStatusHandle.text("*Please enter a valid phone number prefix");827 elementHandle[23].focus(); 828 return false;829 }830 if(isEmpty($.trim(elementHandle[24].val()))) { 831 elementHandle[24].addClass("border_invalid");832 errorStatusHandle.text("*Please enter the phone number");833 elementHandle[24].focus(); 834 return false;835 }836 if(!isPhone($.trim(elementHandle[24].val()))) {837 elementHandle[24].addClass("border_invalid");838 errorStatusHandle.text("*Please enter a valid phone number");839 elementHandle[24].focus(); 840 return false;841 }842 if(!isSelected(elementHandle[0].val())) {843 elementHandle[0].addClass("border_invalid");844 errorStatusHandle.text("*Please select a program");845 elementHandle[0].focus();846 return false;847 }848 if(isEmpty($.trim(elementHandle[1].val()))) {849 elementHandle[1].addClass("border_invalid");850 errorStatusHandle.text("*Please enter child's first name");851 elementHandle[1].focus(); 852 return false;853 }854 if(isEmpty($.trim(elementHandle[2].val()))) {855 elementHandle[2].addClass("border_invalid");856 errorStatusHandle.text("*Please enter child's last name");857 elementHandle[2].focus(); 858 return false;859 }860 if(isEmpty($.trim(elementHandle[4].val()))) {861 elementHandle[4].addClass("border_invalid");862 errorStatusHandle.text("*Please enter child's preferred name");863 elementHandle[4].focus(); 864 return false;865 }866 if(isEmpty($.trim(elementHandle[5].val()))) {867 elementHandle[5].addClass("border_invalid");868 errorStatusHandle.text("*Please enter Date of Birth");869 elementHandle[5].focus(); 870 return false;871 }872 if(!isDate($.trim(elementHandle[5].val()))) {873 elementHandle[5].addClass("border_invalid");874 errorStatusHandle.text("*Please enter a valid date");875 elementHandle[5].focus(); 876 return false;877 }878 if(!isAge($.trim(elementHandle[5].val()))) {879 elementHandle[5].addClass("border_invalid");880 errorStatusHandle.text("*Child should be between 12-18 years of age to register ");881 elementHandle[5].focus(); 882 return false;883 }884 if(!isEmpty($.trim(elementHandle[6].val()))) {885 if(!isEmail($.trim(elementHandle[6].val()))) {886 elementHandle[6].addClass("border_invalid");887 errorStatusHandle.text("*Please enter a valid email id");888 elementHandle[6].focus(); 889 return false;890 }891 }892 if($('input[name=gender]:checked').length<=0)893 {894 elementHandle[7].addClass("border_invalid");895 errorStatusHandle.text("*Please select the gender");896 elementHandle[7].focus(); 897 return false;898 }899 ////////////900 if(isEmpty($.trim($('[name="photo"]').val()))) { 901 $('[name="photo"]').addClass("border_invalid");902 errorStatusHandle.text("*Please enter the Photo");903 $('[name="photo"]').focus(); 904 return false;905 }906 907 ///////////908 if(isEmpty($.trim(elementHandle[27].val()))) { 909 elementHandle[27].addClass("border_invalid");910 errorStatusHandle.text("*Please enter the Emergency Contact Person's Name");911 elementHandle[27].focus(); 912 return false;913 }914 if(isEmpty($.trim(elementHandle[28].val()))) { 915 elementHandle[28].addClass("border_invalid");916 errorStatusHandle.text("*Please enter the Emergency Contact Person's phone number");917 elementHandle[28].focus(); 918 return false;919 }920 if(!isAreaPrefix($.trim(elementHandle[28].val()))) {921 elementHandle[28].addClass("border_invalid");922 errorStatusHandle.text("*Please enter a valid area code");923 elementHandle[28].focus(); 924 return false;925 }926 if(isEmpty($.trim(elementHandle[29].val()))) { 927 elementHandle[29].addClass("border_invalid");928 errorStatusHandle.text("*Please enter the Emergency Contact Person's phone number");929 elementHandle[29].focus(); 930 return false;931 }932 if(!isAreaPrefix($.trim(elementHandle[29].val()))) {933 elementHandle[29].addClass("border_invalid");934 errorStatusHandle.text("*Please enter a valid phone number prefix");935 elementHandle[29].focus(); 936 return false;937 }938 if(isEmpty($.trim(elementHandle[30].val()))) { 939 elementHandle[30].addClass("border_invalid");940 errorStatusHandle.text("*Please enter the Emergency Contact Person's phone number");941 elementHandle[30].focus(); 942 return false;943 }944 if(!isPhone($.trim(elementHandle[30].val()))) {945 elementHandle[30].addClass("border_invalid");946 errorStatusHandle.text("*Please enter a valid phone number");947 elementHandle[30].focus(); 948 return false;949 }950 return true;951 } 952 $(':submit').on('click', function(e) {953 for(var i=0; i <= 30; i++)954 elementHandle[i].removeClass("border_invalid invalid valid border_valid");955 errorStatusHandle.text("");956 if(isValidData()) {957 var params = "email=" + $("[name='pemail']").val() +958 "&first_name=" + $("[name='fname']").val(); 959 params = encodeURI(params); 960 // alert(params); 961 var req = new HttpRequest('ajax_check_dups.php?'+params,962 handleAnswer);963 req.send();964 e.preventDefault();965 }966 else967 return isValidData();968 });969 $(':reset').on('click', function() {970 for(var i=0; i <= 30; i++)971 elementHandle[i].removeClass("border_invalid invalid valid border_valid");972 errorStatusHandle.text("");973 elementHandle[0].focus(); 974 });...
elementhandle.spec.js
Source:elementhandle.spec.js
1/**2 * Copyright 2018 Google Inc. All rights reserved.3 *4 * Licensed under the Apache License, Version 2.0 (the "License");5 * you may not use this file except in compliance with the License.6 * You may obtain a copy of the License at7 *8 * http://www.apache.org/licenses/LICENSE-2.09 *10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 */16const utils = require('./utils');17module.exports.addTests = function({testRunner, expect}) {18 const {describe, xdescribe, fdescribe} = testRunner;19 const {it, fit, xit} = testRunner;20 const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;21 describe('ElementHandle.boundingBox', function() {22 it('should work', async({page, server}) => {23 await page.setViewport({width: 500, height: 500});24 await page.goto(server.PREFIX + '/grid.html');25 const elementHandle = await page.$('.box:nth-of-type(13)');26 const box = await elementHandle.boundingBox();27 expect(box).toEqual({ x: 100, y: 50, width: 50, height: 50 });28 });29 it('should handle nested frames', async({page, server}) => {30 await page.setViewport({width: 500, height: 500});31 await page.goto(server.PREFIX + '/frames/nested-frames.html');32 const nestedFrame = page.frames()[1].childFrames()[1];33 const elementHandle = await nestedFrame.$('div');34 const box = await elementHandle.boundingBox();35 expect(box).toEqual({ x: 28, y: 260, width: 264, height: 18 });36 });37 it('should return null for invisible elements', async({page, server}) => {38 await page.setContent('<div style="display:none">hi</div>');39 const element = await page.$('div');40 expect(await element.boundingBox()).toBe(null);41 });42 it('should force a layout', async({page, server}) => {43 await page.setViewport({ width: 500, height: 500 });44 await page.setContent('<div style="width: 100px; height: 100px">hello</div>');45 const elementHandle = await page.$('div');46 await page.evaluate(element => element.style.height = '200px', elementHandle);47 const box = await elementHandle.boundingBox();48 expect(box).toEqual({ x: 8, y: 8, width: 100, height: 200 });49 });50 });51 describe('ElementHandle.boxModel', function() {52 it('should work', async({page, server}) => {53 await page.goto(server.PREFIX + '/resetcss.html');54 // Step 1: Add Frame and position it absolutely.55 await utils.attachFrame(page, 'frame1', server.PREFIX + '/resetcss.html');56 await page.evaluate(() => {57 const frame = document.querySelector('#frame1');58 frame.style = `59 position: absolute;60 left: 1px;61 top: 2px;62 `;63 });64 // Step 2: Add div and position it absolutely inside frame.65 const frame = page.frames()[1];66 const divHandle = (await frame.evaluateHandle(() => {67 const div = document.createElement('div');68 document.body.appendChild(div);69 div.style = `70 box-sizing: border-box;71 position: absolute;72 border-left: 1px solid black;73 padding-left: 2px;74 margin-left: 3px;75 left: 4px;76 top: 5px;77 width: 6px;78 height: 7px;79 `;80 return div;81 })).asElement();82 // Step 3: query div's boxModel and assert box values.83 const box = await divHandle.boxModel();84 expect(box.width).toBe(6);85 expect(box.height).toBe(7);86 expect(box.margin[0]).toEqual({87 x: 1 + 4, // frame.left + div.left88 y: 2 + 5,89 });90 expect(box.border[0]).toEqual({91 x: 1 + 4 + 3, // frame.left + div.left + div.margin-left92 y: 2 + 5,93 });94 expect(box.padding[0]).toEqual({95 x: 1 + 4 + 3 + 1, // frame.left + div.left + div.marginLeft + div.borderLeft96 y: 2 + 5,97 });98 expect(box.content[0]).toEqual({99 x: 1 + 4 + 3 + 1 + 2, // frame.left + div.left + div.marginLeft + div.borderLeft + dif.paddingLeft100 y: 2 + 5,101 });102 });103 it('should return null for invisible elements', async({page, server}) => {104 await page.setContent('<div style="display:none">hi</div>');105 const element = await page.$('div');106 expect(await element.boxModel()).toBe(null);107 });108 });109 describe('ElementHandle.contentFrame', function() {110 it('should work', async({page,server}) => {111 await page.goto(server.EMPTY_PAGE);112 await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);113 const elementHandle = await page.$('#frame1');114 const frame = await elementHandle.contentFrame();115 expect(frame).toBe(page.frames()[1]);116 });117 });118 describe('ElementHandle.click', function() {119 it('should work', async({page, server}) => {120 await page.goto(server.PREFIX + '/input/button.html');121 const button = await page.$('button');122 await button.click();123 expect(await page.evaluate(() => result)).toBe('Clicked');124 });125 it('should work for Shadow DOM v1', async({page, server}) => {126 await page.goto(server.PREFIX + '/shadow.html');127 const buttonHandle = await page.evaluateHandle(() => button);128 await buttonHandle.click();129 expect(await page.evaluate(() => clicked)).toBe(true);130 });131 it('should work for TextNodes', async({page, server}) => {132 await page.goto(server.PREFIX + '/input/button.html');133 const buttonTextNode = await page.evaluateHandle(() => document.querySelector('button').firstChild);134 let error = null;135 await buttonTextNode.click().catch(err => error = err);136 expect(error.message).toBe('Node is not of type HTMLElement');137 });138 it('should throw for detached nodes', async({page, server}) => {139 await page.goto(server.PREFIX + '/input/button.html');140 const button = await page.$('button');141 await page.evaluate(button => button.remove(), button);142 let error = null;143 await button.click().catch(err => error = err);144 expect(error.message).toBe('Node is detached from document');145 });146 it('should throw for hidden nodes', async({page, server}) => {147 await page.goto(server.PREFIX + '/input/button.html');148 const button = await page.$('button');149 await page.evaluate(button => button.style.display = 'none', button);150 const error = await button.click().catch(err => err);151 expect(error.message).toBe('Node is either not visible or not an HTMLElement');152 });153 it('should throw for recursively hidden nodes', async({page, server}) => {154 await page.goto(server.PREFIX + '/input/button.html');155 const button = await page.$('button');156 await page.evaluate(button => button.parentElement.style.display = 'none', button);157 const error = await button.click().catch(err => err);158 expect(error.message).toBe('Node is either not visible or not an HTMLElement');159 });160 it('should throw for <br> elements', async({page, server}) => {161 await page.setContent('hello<br>goodbye');162 const br = await page.$('br');163 const error = await br.click().catch(err => err);164 expect(error.message).toBe('Node is either not visible or not an HTMLElement');165 });166 });167 describe('ElementHandle.hover', function() {168 it('should work', async({page, server}) => {169 await page.goto(server.PREFIX + '/input/scrollable.html');170 const button = await page.$('#button-6');171 await button.hover();172 expect(await page.evaluate(() => document.querySelector('button:hover').id)).toBe('button-6');173 });174 });175 describe('ElementHandle.screenshot', function() {176 it('should work', async({page, server}) => {177 await page.setViewport({width: 500, height: 500});178 await page.goto(server.PREFIX + '/grid.html');179 await page.evaluate(() => window.scrollBy(50, 100));180 const elementHandle = await page.$('.box:nth-of-type(3)');181 const screenshot = await elementHandle.screenshot();182 expect(screenshot).toBeGolden('screenshot-element-bounding-box.png');183 });184 it('should take into account padding and border', async({page, server}) => {185 await page.setViewport({width: 500, height: 500});186 await page.setContent(`187 something above188 <style>div {189 border: 2px solid blue;190 background: green;191 width: 50px;192 height: 50px;193 }194 </style>195 <div></div>196 `);197 const elementHandle = await page.$('div');198 const screenshot = await elementHandle.screenshot();199 expect(screenshot).toBeGolden('screenshot-element-padding-border.png');200 });201 it('should capture full element when larger than viewport', async({page, server}) => {202 await page.setViewport({width: 500, height: 500});203 await page.setContent(`204 something above205 <style>206 div.to-screenshot {207 border: 1px solid blue;208 width: 600px;209 height: 600px;210 margin-left: 50px;211 }212 </style>213 <div class="to-screenshot"></div>214 `);215 const elementHandle = await page.$('div.to-screenshot');216 const screenshot = await elementHandle.screenshot();217 expect(screenshot).toBeGolden('screenshot-element-larger-than-viewport.png');218 expect(await page.evaluate(() => ({ w: window.innerWidth, h: window.innerHeight }))).toEqual({ w: 500, h: 500 });219 });220 it('should scroll element into view', async({page, server}) => {221 await page.setViewport({width: 500, height: 500});222 await page.setContent(`223 something above224 <style>div.above {225 border: 2px solid blue;226 background: red;227 height: 1500px;228 }229 div.to-screenshot {230 border: 2px solid blue;231 background: green;232 width: 50px;233 height: 50px;234 }235 </style>236 <div class="above"></div>237 <div class="to-screenshot"></div>238 `);239 const elementHandle = await page.$('div.to-screenshot');240 const screenshot = await elementHandle.screenshot();241 expect(screenshot).toBeGolden('screenshot-element-scrolled-into-view.png');242 });243 it('should work with a rotated element', async({page, server}) => {244 await page.setViewport({width: 500, height: 500});245 await page.setContent(`<div style="position:absolute;246 top: 100px;247 left: 100px;248 width: 100px;249 height: 100px;250 background: green;251 transform: rotateZ(200deg);"> </div>`);252 const elementHandle = await page.$('div');253 const screenshot = await elementHandle.screenshot();254 expect(screenshot).toBeGolden('screenshot-element-rotate.png');255 });256 it('should fail to screenshot a detached element', async({page, server}) => {257 await page.setContent('<h1>remove this</h1>');258 const elementHandle = await page.$('h1');259 await page.evaluate(element => element.remove(), elementHandle);260 const screenshotError = await elementHandle.screenshot().catch(error => error);261 expect(screenshotError.message).toBe('Node is either not visible or not an HTMLElement');262 });263 });264 describe('ElementHandle.$', function() {265 it('should query existing element', async({page, server}) => {266 await page.goto(server.PREFIX + '/playground.html');267 await page.setContent('<html><body><div class="second"><div class="inner">A</div></div></body></html>');268 const html = await page.$('html');269 const second = await html.$('.second');270 const inner = await second.$('.inner');271 const content = await page.evaluate(e => e.textContent, inner);272 expect(content).toBe('A');273 });274 it('should return null for non-existing element', async({page, server}) => {275 await page.setContent('<html><body><div class="second"><div class="inner">B</div></div></body></html>');276 const html = await page.$('html');277 const second = await html.$('.third');278 expect(second).toBe(null);279 });280 });281 describe('ElementHandle.$$', function() {282 it('should query existing elements', async({page, server}) => {283 await page.setContent('<html><body><div>A</div><br/><div>B</div></body></html>');284 const html = await page.$('html');285 const elements = await html.$$('div');286 expect(elements.length).toBe(2);287 const promises = elements.map(element => page.evaluate(e => e.textContent, element));288 expect(await Promise.all(promises)).toEqual(['A', 'B']);289 });290 it('should return empty array for non-existing elements', async({page, server}) => {291 await page.setContent('<html><body><span>A</span><br/><span>B</span></body></html>');292 const html = await page.$('html');293 const elements = await html.$$('div');294 expect(elements.length).toBe(0);295 });296 });297 describe('ElementHandle.$x', function() {298 it('should query existing element', async({page, server}) => {299 await page.goto(server.PREFIX + '/playground.html');300 await page.setContent('<html><body><div class="second"><div class="inner">A</div></div></body></html>');301 const html = await page.$('html');302 const second = await html.$x(`./body/div[contains(@class, 'second')]`);303 const inner = await second[0].$x(`./div[contains(@class, 'inner')]`);304 const content = await page.evaluate(e => e.textContent, inner[0]);305 expect(content).toBe('A');306 });307 it('should return null for non-existing element', async({page, server}) => {308 await page.setContent('<html><body><div class="second"><div class="inner">B</div></div></body></html>');309 const html = await page.$('html');310 const second = await html.$x(`/div[contains(@class, 'third')]`);311 expect(second).toEqual([]);312 });313 });...
p1.js
Source:p1.js
1$('document').ready(function(){2 $("#pickdate").datepicker({changeMonth:true, changeYear:true, showOtherMonths:true, showButtonPanel:true,3 closeText:"Close"});4 $("a").tooltip({show:{effect: "bounce", delay:1000}}); 5 $("#panels").accordion({icons:{header:"ui-icon-folder-collapsed",activeHeader:"ui-icon-folder-open"}},6 { event:"mouseover"});7 $("#verticalMenu").menu();8 $("#box").dialog({title:"Welcome to Demo", resizable:false, hide:1500, closeOnEscape:false,9 modal:true});10 $("#tabcontainer").tabs({event:"mouseover"});11 $("#auto").autocomplete({source:["USA", "India", "Mexico", "Canada"]})12 13 14 15 16 //form validation17 18 19 20 21 function isEmpty(fieldValue) {22 return $.trim(fieldValue).length == 0; 23 } 24 25 function isValidState(state) { 26 var stateList = new Array("AK","AL","AR","AZ","CA","CO","CT","DC",27 "DE","FL","GA","GU","HI","IA","ID","IL","IN","KS","KY","LA","MA",28 "MD","ME","MH","MI","MN","MO","MS","MT","NC","ND","NE","NH","NJ",29 "NM","NV","NY","OH","OK","OR","PA","PR","RI","SC","SD","TN","TX",30 "UT","VA","VT","WA","WI","WV","WY");31 for(var i=0; i < stateList.length; i++) 32 if(stateList[i] == $.trim(state))33 return true;34 return false;35 } 36 37 // copied from stackoverflow.com, not checked or validated for correctness. 38 function isValidEmail(emailAddress) {39 var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);40 return pattern.test(emailAddress);41 } 42 43 function isValidDate() {44 var day = $("#date").val();45 var month = $("#month").val();46 var year = $("#year").val();47 48 var calc_date = new Date(year, month-1, day);49 var calc_day = calc_date.getDate();50 var calc_month = calc_date.getMonth()+1;51 var calc_year = calc_date.getFullYear();52 53 if(day == calc_day && month == calc_month && year == calc_year)54 return true;55 else56 return false;57}58 var errorStatusHandle = $('#message_line');59 var elementHandle = new Array(13);60 elementHandle[0] = $('[name="fname"]');61 elementHandle[1] = $('[name="lname"]');62 elementHandle[2] = $('[name="address1"]');63 elementHandle[3] = $('[name="city"]');64 elementHandle[4] = $('[name="state"]');65 elementHandle[5] = $('[name="zip"]');66 elementHandle[6] = $('[name="area_phone"]');67 elementHandle[7] = $('[name="prefix_phone"]');68 elementHandle[8] = $('[name="phone"]');69 elementHandle[9] = $('[name="email"]');70 elementHandle[10] = $('[name="month"]');71 elementHandle[11] = $('[name="date"]');72 elementHandle[12] = $('[name="year"]');73 74 function isValidData() {75 if(isEmpty(elementHandle[0].val())) {76 elementHandle[0].addClass("error");77 errorStatusHandle.text("Please enter your first name");78 elementHandle[0].focus();79 return false;80 }81 if(isEmpty(elementHandle[1].val())) {82 elementHandle[1].addClass("error");83 errorStatusHandle.text("Please enter your last name");84 elementHandle[1].focus(); 85 return false;86 }87 if(isEmpty(elementHandle[2].val())) {88 elementHandle[2].addClass("error");89 errorStatusHandle.text("Please enter your address");90 elementHandle[2].focus(); 91 return false;92 }93 if(isEmpty(elementHandle[3].val())) {94 elementHandle[3].addClass("error");95 errorStatusHandle.text("Please enter your city");96 elementHandle[3].focus(); 97 return false;98 }99 if(isEmpty(elementHandle[4].val())) {100 elementHandle[4].addClass("error");101 errorStatusHandle.text("Please enter your state");102 elementHandle[4].focus(); 103 return false;104 }105 if(!isValidState(elementHandle[4].val())) {106 elementHandle[4].addClass("error");107 errorStatusHandle.text("The state appears to be invalid, "+108 "please use the two letter state abbreviation");109 elementHandle[4].focus(); 110 return false;111 }112 if(isEmpty(elementHandle[5].val())) {113 elementHandle[5].addClass("error");114 errorStatusHandle.text("Please enter your zip code");115 elementHandle[5].focus(); 116 return false;117 }118 if(!$.isNumeric(elementHandle[5].val())) {119 elementHandle[5].addClass("error");120 errorStatusHandle.text("The zip code appears to be invalid, "+121 "numbers only please. ");122 elementHandle[5].focus(); 123 return false;124 }125 if(elementHandle[5].val().length != 5) {126 elementHandle[5].addClass("error");127 errorStatusHandle.text("The zip code must have exactly five digits")128 elementHandle[5].focus(); 129 return false;130 }131 if(isEmpty(elementHandle[6].val())) {132 elementHandle[6].addClass("error");133 errorStatusHandle.text("Please enter your area code");134 elementHandle[6].focus(); 135 return false;136 } 137 if(!$.isNumeric(elementHandle[6].val())) {138 elementHandle[6].addClass("error");139 errorStatusHandle.text("The area code appears to be invalid, "+140 "numbers only please. ");141 elementHandle[6].focus(); 142 return false;143 }144 if(elementHandle[6].val().length != 3) {145 elementHandle[6].addClass("error");146 errorStatusHandle.text("The area code must have exactly three digits")147 elementHandle[6].focus(); 148 return false;149 } 150 if(isEmpty(elementHandle[7].val())) {151 elementHandle[7].addClass("error");152 errorStatusHandle.text("Please enter your phone number prefix");153 elementHandle[7].focus(); 154 return false;155 } 156 if(!$.isNumeric(elementHandle[7].val())) {157 elementHandle[7].addClass("error");158 errorStatusHandle.text("The phone number prefix appears to be invalid, "+159 "numbers only please. ");160 elementHandle[7].focus(); 161 return false;162 }163 if(elementHandle[7].val().length != 3) {164 elementHandle[7].addClass("error");165 errorStatusHandle.text("The phone number prefix must have exactly three digits")166 elementHandle[7].focus(); 167 return false;168 }169 if(isEmpty(elementHandle[8].val())) {170 elementHandle[8].addClass("error");171 errorStatusHandle.text("Please enter your phone number");172 elementHandle[8].focus(); 173 return false;174 } 175 if(!$.isNumeric(elementHandle[8].val())) {176 elementHandle[8].addClass("error");177 errorStatusHandle.text("The phone number appears to be invalid, "+178 "numbers only please. ");179 elementHandle[8].focus(); 180 return false;181 }182 if(elementHandle[8].val().length != 4) {183 elementHandle[8].addClass("error");184 errorStatusHandle.text("The phone number must have exactly four digits")185 elementHandle[8].focus(); 186 return false;187 } 188 if(isEmpty(elementHandle[9].val())) {189 elementHandle[9].addClass("error");190 errorStatusHandle.text("Please enter your email address");191 elementHandle[9].focus(); 192 return false;193 } 194 if(!isValidEmail(elementHandle[9].val())) {195 elementHandle[9].addClass("error");196 errorStatusHandle.text("The email address appears to be invalid,");197 elementHandle[9].focus(); 198 return false;199 } 200 if(isEmpty(elementHandle[10].val())) {201 elementHandle[10].addClass("error");202 errorStatusHandle.text("Please Enter Month");203 elementHandle[10].focus();204 return false;205 }206 if(!$.isNumeric(elementHandle[10].val())) {207 elementHandle[10].addClass("error");208 errorStatusHandle.text("Please Enter number for month");209 elementHandle[10].focus();210 return false;211 }212 if(isEmpty(elementHandle[11].val())) {213 elementHandle[11].addClass("error");214 errorStatusHandle.text("Please Enter Day");215 elementHandle[11].focus();216 return false;217 }218 if(!$.isNumeric(elementHandle[11].val())) {219 elementHandle[11].addClass("error");220 errorStatusHandle.text("Please Enter number for Day");221 elementHandle[11].focus();222 return false;223 }224 if(isEmpty(elementHandle[12].val())) {225 elementHandle[12].addClass("error");226 errorStatusHandle.text("Please Enter Year");227 elementHandle[12].focus();228 return false;229 }230 if(!$.isNumeric(elementHandle[12].val())) {231 elementHandle[12].addClass("error");232 errorStatusHandle.text("Please Enter number for year");233 elementHandle[12].focus();234 return false;235 }236 var isValidDOB = true;237 if(!isValidDate()){238 $('[name="month"]').addClass("error");239 $('[name="date"]').addClass("error");240 $('[name="year"]').addClass("error");241 errorStatusHandle.text("Please Enter a valid date");242 isValidDOB = false;243 return false;244 245 }246 if(isValidDOB){247 var dob = new Date();248 dob.setMonth($('[name="month"]').val());249 dob.setDate($('[name="date"]').val());250 dob.setFullYear($('[name="year"]').val());251 252 var ref = new Date("Jan 1, 2017");253 var diff_year = ref.getFullYear() - dob.getFullYear();254 var diff_month = ref.getMonth() - dob.getMonth();255 var diff_day = ref.getDate() - dob.getDate();256 257 if(diff_year > 80 || (diff_year == 80 && diff_month > 0) || (diff_year == 80 && diff_month == 0 && diff_day > 0)) {258 $('[name="month"]').addClass("error");259 $('[name="date"]').addClass("error");260 $('[name="year"]').addClass("error");261 errorStatusHandle.text("age more than 80 cannot register");262 return false;263 }264 if(diff_year < 10 || (diff_year == 10 && diff_month < 0) || (diff_year==10 && diff_month == 0 && diff_day < 0)) {265 $('[name="month"]').addClass("error");266 $('[name="date"]').addClass("error");267 $('[name="year"]').addClass("error");268 errorStatusHandle.text("Kid must be atleast 10 years old to Register");269 return false;270 }271 } 272 273 return true;274 } 275 elementHandle[0].focus();276 277 278/////// HANDLERS279// on blur, if the user has entered valid data, the error message280// should no longer show.281 elementHandle[0].on('blur', function() {282 if(isEmpty(elementHandle[0].val()))283 return;284 $(this).removeClass("error");285 errorStatusHandle.text("");286 });287 288 elementHandle[9].on('blur', function() {289 if(isEmpty(elementHandle[12].val()))290 return;291 if(isValidEmail(elementHandle[12].val())) {292 $(this).removeClass("error");293 errorStatusHandle.text("");294 }295 }); 296///////////////////////////////////////////////////////////////// 297 elementHandle[4].on('keyup', function() {298 elementHandle[4].val(elementHandle[4].val().toUpperCase());299 });300 301 elementHandle[6].on('keyup', function() {302 if(elementHandle[6].val().length == 3)303 elementHandle[7].focus();304 });305 306 elementHandle[7].on('keyup', function() {307 if(elementHandle[7].val().length == 3)308 elementHandle[8].focus();309 }); 310 311 $(':submit').on('click', function(event) {312 event.preventDefault();313 for(var i=0; i < 13; i++)314 elementHandle[i].removeClass("error");315 errorStatusHandle.text("");316 317 if(!isValidData()){318 319 console.log("Invalid data");320 }321 else{322 323 $("form").submit();324 console.log("valid data");325 } 326 327 });328 329 $(':reset').on('click', function() {330 for(var i=0; i < 13; i++)331 elementHandle[i].removeClass("error");332 errorStatusHandle.text("");333 }); 334 335 ...
Element.js
Source:Element.js
1import Helpers from "./helpers";2const path = require("path");3const config = require(process.cwd() + "/test-juggler.config");4const defaultTimeout = config.defaultTimeout;5const shortTimeout = config.shortTimeout;6export default class Element {7 constructor(selector) {8 this.selector = selector;9 }10 newChildElement(childSelector) {11 var isXPathSlector = (selector) => selector.startsWith("//");12 if (isXPathSlector(this.selector) != isXPathSlector(childSelector)) {13 throw "Cannot combine different selectors types!";14 }15 return new Element(`${this.selector} ${childSelector}`);16 }17 async wait(timeout = defaultTimeout) {18 console.log(`Waiting for ${this.selector} ...`);19 const elementHandle = await page.waitForSelector(this.selector, { timeout: timeout });20 if (config.captureScreenshots) {21 await Helpers.takeScreenshot();22 }23 return elementHandle;24 }25 async waitUntilVisible(timeout = defaultTimeout) {26 console.log(`Waiting for ${this.selector} to be visible...`);27 const elementHandle = await page.waitForSelector(this.selector, { state: "visible", timeout: timeout });28 if (config.captureScreenshots) {29 await Helpers.takeScreenshot();30 }31 return elementHandle;32 }33 async waitUntilInvisible(timeout = defaultTimeout) {34 console.log(`Waiting for ${this.selector} to be invisible...`);35 await page.waitForSelector(this.selector, { state: "hidden", timeout: timeout });36 if (config.captureScreenshots) {37 await Helpers.takeScreenshot();38 }39 }40 async getCoordinates(xOffset = null, yOffset = null) {41 const elementHandle = await this.wait();42 const rect = await elementHandle.boundingBox();43 const xCoordinate = xOffset !== null ? xOffset : rect.width / 2;44 const yCoordinate = yOffset !== null ? yOffset : rect.height / 2;45 console.log(`Element width: ${rect.width}, height: ${rect.height}`);46 console.log(`Action on element rectangle at position x: ${xCoordinate}, y: ${yCoordinate}`);47 return { x: xCoordinate, y: yCoordinate };48 }49 async click(xOffset = null, yOffset = null) {50 console.log(`Clicking ${this.selector} ...`);51 if (xOffset != null || yOffset != null) {52 const coordinates = await this.getCoordinates(xOffset, yOffset);53 await page.click(this.selector, { position: { x: coordinates.x, y: coordinates.y } });54 }55 else await page.click(this.selector);56 }57 async doubleClick(xOffset = null, yOffset = null) {58 console.log(`Double clicking ${this.selector} ...`);59 if (xOffset != null || yOffset != null) {60 const coordinates = await this.getCoordinates(xOffset, yOffset);61 await page.dblclick(this.selector, { position: { x: coordinates.x, y: coordinates.y } });62 }63 else await page.dblclick(this.selector);64 }65 async rightClick(xOffset = null, yOffset = null) {66 console.log(`Right clicking ${this.selector} ...`);67 if (xOffset != null || yOffset != null) {68 const coordinates = await this.getCoordinates(xOffset, yOffset);69 await page.click(this.selector, { position: { x: coordinates.x, y: coordinates.y }, button: "right" } );70 }71 else await page.click(this.selector, { button: "right" });72 }73 async hover(xOffset = null, yOffset = null) {74 console.log(`Hovering mouse on to ${this.selector} ...`);75 if (xOffset != null || yOffset != null) {76 const coordinates = await this.getCoordinates(xOffset, yOffset);77 await page.hover(this.selector, { position: { x: coordinates.x, y: coordinates.y } });78 }79 else await page.hover(this.selector);80 }81 async exists() {82 let exist;83 try {84 await this.wait(shortTimeout);85 exist = true;86 console.log(`Element ${this.selector} exists`);87 }88 catch (error) {89 exist = false;90 console.log(`Element ${this.selector} does not exist`);91 }92 return exist;93 }94 async isVisible() {95 let visible;96 try {97 await this.waitUntilVisible(shortTimeout);98 visible = true;99 console.log(`Element ${this.selector} is visible`);100 }101 catch (error) {102 visible = false;103 console.log(`Element ${this.selector} is not visible`);104 }105 return visible;106 }107 async dragAndDrop(destination) {108 const sourceElement = await page.waitForSelector(this.selector);109 const destinationElement = await page.waitForSelector(destination.selector);110 const sourceBox = await sourceElement.boundingBox();111 const destinationBox = await destinationElement.boundingBox();112 console.log(`Drag and dropping ${this.selector} to ${destination.selector} ...`);113 await page.mouse.move(sourceBox.x + sourceBox.width / 2, sourceBox.y + sourceBox.height / 2);114 await page.mouse.down();115 await page.mouse.move(destinationBox.x + destinationBox.width / 2, destinationBox.y + destinationBox.height / 2);116 await page.mouse.up();117 }118 async text() {119 console.log(`Getting inner text of ${this.selector} ...`);120 const elementHandle = await this.wait();121 const text = await elementHandle.evaluate(element => element.innerText);122 return text;123 }124 async value() {125 console.log(`Getting value of ${this.selector} ...`);126 const elementHandle = await this.wait();127 const value = await elementHandle.evaluate(element => element.value);128 return value;129 }130 async enterText(text) {131 console.log(`Entering the text value for ${this.selector} ...`);132 const elementHandle = await this.wait();133 await elementHandle.type(text);134 }135 async clearText() {136 console.log(`Clearing the text value for ${this.selector} ...`);137 await this.click();138 await page.keyboard.down("Control");139 await page.keyboard.press("A");140 await page.keyboard.up("Control");141 await page.keyboard.press("Backspace");142 }143 async takeScreenshot() {144 console.log(`Taking the screenshot for ${this.selector} ...`);145 const elementHandle = await this.wait();146 return await elementHandle.screenshot();147 }148 async getAttributeValue(attributeName) {149 const elementHandle = await this.wait();150 console.log(`Getting '${attributeName}' attribute value of element ${this.selector} ...`);151 const atributeValue = await elementHandle.evaluate((element, attributeName) => element.getAttribute(`${attributeName}`), attributeName);152 return atributeValue;153 }154 async getStyleAttributeValue(name) {155 const elementHandle = await this.wait();156 console.log(`Getting value of style attribute '${name}' of ${this.selector} ...`);157 const attributeValue = await elementHandle.evaluate((element, name) => element.style[name], name);158 return attributeValue;159 }160 async cover() {161 const elementHandle = await this.wait();162 await elementHandle.evaluate((element) => {163 //Get bounding area of element we want to cover164 const rect = element.getBoundingClientRect();165 //Create a canvas element166 var canvas = document.createElement("canvas");167 //Set canvas drawing area width/height168 canvas.width = window.innerWidth;169 canvas.height = window.innerHeight;170 //Position canvas171 canvas.style.position = "absolute";172 canvas.style.left = 0;173 canvas.style.top = 0;174 canvas.style.zIndex = 100000;175 //Make sure you can click 'through' the canvas176 canvas.style.pointerEvents = "none";177 //Append canvas to body element178 document.body.appendChild(canvas);179 var context = canvas.getContext("2d");180 //Draw rectangle181 context.rect(rect.x, rect.y, rect.width, rect.height);182 context.fillStyle = "yellow";183 context.fill();184 });185 }186 async uploadFile(filePath, isAbsolutePath) {187 if (!isAbsolutePath) filePath = process.cwd() + filePath;188 console.log(`Uploading a file with path ${filePath}`);189 const elementHandle = await this.wait();190 await elementHandle.setInputFiles(filePath);191 }192 async downloadFile(filePath) {193 if (!path.isAbsolute(filePath)) filePath = process.cwd().replace(/\\/g, "/") + filePath;194 const [download] = await Promise.all([195 page.waitForEvent("download"),196 this.click(),197 ]);198 await download.saveAs(filePath);199 }...
channels.js
Source:channels.js
1"use strict";2Object.defineProperty(exports, "__esModule", {3 value: true4});5exports.pausesBeforeInputActions = exports.commandsWithTracingSnapshots = void 0;6/**7 * Copyright (c) Microsoft Corporation.8 *9 * Licensed under the Apache License, Version 2.0 (the "License");10 * you may not use this file except in compliance with the License.11 * You may obtain a copy of the License at12 *13 * http://www.apache.org/licenses/LICENSE-2.014 *15 * Unless required by applicable law or agreed to in writing, software16 * distributed under the License is distributed on an "AS IS" BASIS,17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.18 * See the License for the specific language governing permissions and19 * limitations under the License.20 */21// This file is generated by generate_channels.js, do not edit manually.22// ----------- FetchRequest -----------23// ----------- Root -----------24// ----------- Playwright -----------25// ----------- Selectors -----------26// ----------- BrowserType -----------27// ----------- Browser -----------28// ----------- EventTarget -----------29// ----------- BrowserContext -----------30// ----------- Page -----------31// ----------- Frame -----------32// ----------- Worker -----------33// ----------- JSHandle -----------34// ----------- ElementHandle -----------35// ----------- Request -----------36// ----------- Route -----------37// ----------- Response -----------38// ----------- WebSocket -----------39// ----------- ConsoleMessage -----------40// ----------- BindingCall -----------41// ----------- Dialog -----------42// ----------- Artifact -----------43// ----------- Stream -----------44// ----------- CDPSession -----------45// ----------- Electron -----------46// ----------- ElectronApplication -----------47// ----------- Android -----------48// ----------- AndroidSocket -----------49// ----------- AndroidDevice -----------50// ----------- JsonPipe -----------51const commandsWithTracingSnapshots = new Set(['EventTarget.waitForEventInfo', 'BrowserContext.waitForEventInfo', 'Page.waitForEventInfo', 'WebSocket.waitForEventInfo', 'ElectronApplication.waitForEventInfo', 'AndroidDevice.waitForEventInfo', 'Page.goBack', 'Page.goForward', 'Page.reload', 'Page.setViewportSize', 'Page.keyboardDown', 'Page.keyboardUp', 'Page.keyboardInsertText', 'Page.keyboardType', 'Page.keyboardPress', 'Page.mouseMove', 'Page.mouseDown', 'Page.mouseUp', 'Page.mouseClick', 'Page.mouseWheel', 'Page.touchscreenTap', 'Frame.evalOnSelector', 'Frame.evalOnSelectorAll', 'Frame.addScriptTag', 'Frame.addStyleTag', 'Frame.check', 'Frame.click', 'Frame.dragAndDrop', 'Frame.dblclick', 'Frame.dispatchEvent', 'Frame.evaluateExpression', 'Frame.evaluateExpressionHandle', 'Frame.fill', 'Frame.focus', 'Frame.getAttribute', 'Frame.goto', 'Frame.hover', 'Frame.innerHTML', 'Frame.innerText', 'Frame.inputValue', 'Frame.isChecked', 'Frame.isDisabled', 'Frame.isEnabled', 'Frame.isHidden', 'Frame.isVisible', 'Frame.isEditable', 'Frame.press', 'Frame.selectOption', 'Frame.setContent', 'Frame.setInputFiles', 'Frame.tap', 'Frame.textContent', 'Frame.type', 'Frame.uncheck', 'Frame.waitForTimeout', 'Frame.waitForFunction', 'Frame.waitForSelector', 'Frame.expect', 'JSHandle.evaluateExpression', 'ElementHandle.evaluateExpression', 'JSHandle.evaluateExpressionHandle', 'ElementHandle.evaluateExpressionHandle', 'ElementHandle.evalOnSelector', 'ElementHandle.evalOnSelectorAll', 'ElementHandle.check', 'ElementHandle.click', 'ElementHandle.dblclick', 'ElementHandle.dispatchEvent', 'ElementHandle.fill', 'ElementHandle.hover', 'ElementHandle.innerHTML', 'ElementHandle.innerText', 'ElementHandle.inputValue', 'ElementHandle.isChecked', 'ElementHandle.isDisabled', 'ElementHandle.isEditable', 'ElementHandle.isEnabled', 'ElementHandle.isHidden', 'ElementHandle.isVisible', 'ElementHandle.press', 'ElementHandle.scrollIntoViewIfNeeded', 'ElementHandle.selectOption', 'ElementHandle.selectText', 'ElementHandle.setInputFiles', 'ElementHandle.tap', 'ElementHandle.textContent', 'ElementHandle.type', 'ElementHandle.uncheck', 'ElementHandle.waitForElementState', 'ElementHandle.waitForSelector']);52exports.commandsWithTracingSnapshots = commandsWithTracingSnapshots;53const pausesBeforeInputActions = new Set(['Frame.check', 'Frame.click', 'Frame.dragAndDrop', 'Frame.dblclick', 'Frame.fill', 'Frame.hover', 'Frame.press', 'Frame.selectOption', 'Frame.setInputFiles', 'Frame.tap', 'Frame.type', 'Frame.uncheck', 'ElementHandle.check', 'ElementHandle.click', 'ElementHandle.dblclick', 'ElementHandle.fill', 'ElementHandle.hover', 'ElementHandle.press', 'ElementHandle.selectOption', 'ElementHandle.setInputFiles', 'ElementHandle.tap', 'ElementHandle.type', 'ElementHandle.uncheck']);...
FixedDragHandle.js
Source:FixedDragHandle.js
1/*****************************************************************************2 * Open MCT, Copyright (c) 2014-2018, United States Government3 * as represented by the Administrator of the National Aeronautics and Space4 * Administration. All rights reserved.5 *6 * Open MCT is licensed under the Apache License, Version 2.0 (the7 * "License"); you may not use this file except in compliance with the License.8 * You may obtain a copy of the License at9 * http://www.apache.org/licenses/LICENSE-2.0.10 *11 * Unless required by applicable law or agreed to in writing, software12 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT13 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the14 * License for the specific language governing permissions and limitations15 * under the License.16 *17 * Open MCT includes source code licensed under additional open source18 * licenses. See the Open Source Licenses file (LICENSES.md) included with19 * this source code distribution or the Licensing information page available20 * at runtime from the About dialog for additional information.21 *****************************************************************************/22define(23 [],24 function () {25 // Drag handle dimensions26 var DRAG_HANDLE_SIZE = [6, 6];27 /**28 * Template-displayable drag handle for an element in fixed29 * position mode.30 *31 * @param elementHandle the element handle32 * @param configPath the configuration path of an element33 * @param {Object} fixedControl the fixed controller34 * @memberof platform/features/layout35 * @constructor36 */37 function FixedDragHandle(elementHandle, configPath, fixedControl) {38 this.elementHandle = elementHandle;39 this.configPath = configPath;40 this.fixedControl = fixedControl;41 }42 /**43 * Get a CSS style to position this drag handle.44 *45 * @returns CSS style object (for `ng-style`)46 * @memberof platform/features/layout.FixedDragHandle#47 */48 FixedDragHandle.prototype.style = function () {49 var gridSize = this.elementHandle.getGridSize();50 // Adjust from grid to pixel coordinates51 var x = this.elementHandle.x() * gridSize[0],52 y = this.elementHandle.y() * gridSize[1];53 // Convert to a CSS style centered on that point54 return {55 left: (x - DRAG_HANDLE_SIZE[0] / 2) + 'px',56 top: (y - DRAG_HANDLE_SIZE[1] / 2) + 'px',57 width: DRAG_HANDLE_SIZE[0] + 'px',58 height: DRAG_HANDLE_SIZE[1] + 'px'59 };60 };61 /**62 * Start a drag gesture. This should be called when a drag63 * begins to track initial state.64 */65 FixedDragHandle.prototype.startDrag = function () {66 // Cache initial x/y positions67 this.dragging = {68 x: this.elementHandle.x(),69 y: this.elementHandle.y()70 };71 };72 /**73 * Continue a drag gesture; update x/y positions.74 *75 * @param {number[]} delta x/y pixel difference since drag started76 */77 FixedDragHandle.prototype.continueDrag = function (delta) {78 var gridSize = this.elementHandle.getGridSize();79 if (this.dragging) {80 // Update x/y positions (snapping to grid)81 var newX = this.dragging.x + Math.round(delta[0] / gridSize[0]);82 var newY = this.dragging.y + Math.round(delta[1] / gridSize[1]);83 this.elementHandle.x(Math.max(0, newX));84 this.elementHandle.y(Math.max(0, newY));85 this.fixedControl.updateSelectionStyle();86 }87 };88 /**89 * End a drag gesture. This should be called when a drag90 * concludes to trigger commit of changes.91 */92 FixedDragHandle.prototype.endDrag = function () {93 this.dragging = undefined;94 this.fixedControl.mutate(this.configPath, this.elementHandle.element);95 };96 return FixedDragHandle;97 }...
stepDefinitions.js
Source:stepDefinitions.js
1const scope = require("../support/scope");2// puppeteer@1.9.03let { ElementHandle } = require( "puppeteer/lib/ExecutionContext" );4// puppeteer@1.12 5if ( ElementHandle === undefined ) {6 ElementHandle = require( "puppeteer/lib/JSHandle" ).ElementHandle;7}8const typeUserId = async (ID_X_PATH, ID_X_VALUE) => {9 await scope.context.currentPage.type(ID_X_PATH, ID_X_VALUE,{delay: 50});10};11const typePassword = async (PASSWORD_X_PATH, PASSWORD_X_VALUE) => {12 await scope.context.currentPage.type(PASSWORD_X_PATH, PASSWORD_X_VALUE,{delay: 50});13};14const clickSubmit = async (SUBMIT_X_PATH) => {15 await scope.context.currentPage.click(SUBMIT_X_PATH);16};17const login = async (ID_X_PATH, ID_X_VALUE, PASSWORD_X_PATH, PASSWORD_X_VALUE, SUBMIT_X_PATH) => {18 await typeUserId(ID_X_PATH, ID_X_VALUE);19 await typePassword(PASSWORD_X_PATH, PASSWORD_X_VALUE);20 await clickSubmit(SUBMIT_X_PATH); 21};22const getElement = async (elementClassOrId) => {23 const element = await scope.context.currentPage.$(elementClassOrId);24 return element; 25}26const getCurrentPageUrl = () => {27 return scope.context.currentPage._target._targetInfo.url;28}29const waitForElementToLoad = async (selector) => {30 await scope.context.currentPage.waitForSelector(selector)31}32const getElementListByClass = async () => {33 const elementList = await scope.context.currentPage.evaluate((myclass) => {34 let data = [];35 let elements = document.getElementsByClassName(myclass);36 for (var element of elements)37 data.push(element.textContent);38 return data;39 });40 return elementList;41}42/**43 * Set value on a select element44 * @param {string} value45 * @returns {Promise<Undefined>}46 */47ElementHandle.prototype.select = async function( value ) {48 await this._page.evaluateHandle( ( el, value ) => {49 const event = new Event( "change", { bubbles: true });50 event.simulated = true;51 el.querySelector( `option[value="${ value }"]` ).selected = true;52 el.dispatchEvent( event );53 }, this, value );54};55/**56 * Check if element is visible in the DOM57 * @returns {Promise<Boolean>}58 **/59ElementHandle.prototype.isVisible = async function(){60 return (await this.boundingBox() !== null);61};62/**63 * Get element attribute64 * @param {string} attr65 * @returns {Promise<String>}66 */67ElementHandle.prototype.getAttr = async function( attr ){68 const handle = await this._page.evaluateHandle( ( el, attr ) => el.getAttribute( attr ), this, attr );69 return await handle.jsonValue();70};71/**72 * Get element property73 * @param {string} prop74 * @returns {Promise<String>}75 */76ElementHandle.prototype.getProp = async function( prop ){77 const handle = await this._page.evaluateHandle( ( el, prop ) => el[ prop ], this, prop );78 return await handle.jsonValue();79};80ElementHandle.prototype.isDisabled = async (selector) => {81 const isDisabled = await scope.context.currentPage.$eval(selector, (button) => {82 return button.disabled 83 })84 return isDisabled;85}86module.exports = {87 typeUserId,88 typePassword,89 clickSubmit,90 login,91 getElement,92 getCurrentPageUrl,93 waitForElementToLoad,94 getElementListByClass...
base-function.js
Source:base-function.js
1const puppeteer = require('puppeteer');2const fs = require('fs');3 4let browser;5let page;6let url;7 8export const launchPuppeteer = async () => {9 browser = await puppeteer.launch({10 headless: false,11 args: [12 '--suppress-message-center-popups',13 '--window-size=1350,768',14 ],15 });16 [page] = await browser.pages();17 await page.setViewport({ width: 1366, height: 768 });18 return page;19};20 21export const closePuppeteer = async () => {22 await browser.close();23};24 25export const overridePermissions = async (link) => {26 const context = browser.defaultBrowserContext();27 await context.overridePermissions(link, ['geolocation', 'notifications']);28};29export const sleep = async (miliSeconds) => {30 await page.waitForTimeout(miliSeconds);31 };32 33 export const getProperty = async (xpathQuery, property) => {34 await page.waitForXPath(xpathQuery);35 36 const elementHandle = await page.$x(xpathQuery);37 const propertyHandle = await elementHandle[0].getProperty(property);38 const propertyValue = await propertyHandle.jsonValue();39 40 return propertyValue;41 };42 43 export const typeValueElementXpath = async (selector, text) => {44 const elementHandle = await page.$x(selector);45 await elementHandle[0].type(text);46 };47 48 export const clickElementXpath = async (selector) => {49 await page.waitForXPath(selector);50 const elementHandle = await page.$x(selector);51 await elementHandle[0].click();52 };53 54 export const clickListDropdown = async (selector, value) => {55 await page.select(selector, value);56 };57 58 export const checkVisibleXpathElement = async (xpathQuery) => {59 const elementHandle = await page.$x(xpathQuery);60 return elementHandle;61 };62 63 export const expectElementEqualTextContent = async (selector, expectedText) => {64 const text = await getProperty(selector, 'textContent');65 expect(text).toEqual(expectedText);66 };67 68 export const expectElementContainTextContent = async (selector, expectedText) => {69 const text = await getProperty(selector, 'textContent');70 expect(text).toContain(expectedText);71 };72 export const expectURL = async (expectedUrl) => {73 const Url = await page.url();74 expect(Url).toEqual(expectedUrl);75 };76 export const getURL = async () => {77 await page.url();...
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 const elementHandle = await page.$('text=Get started');7 await elementHandle.click();8 await browser.close();9})();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 const elementHandle = await page.$('#main');7 const boundingBox = await elementHandle.boundingBox();8 console.log(boundingBox);9 await browser.close();10})();11{12}13const { chromium } = require('playwright');14(async () => {15 const browser = await chromium.launch();16 const context = await browser.newContext();17 const page = await context.newPage();18 const elementHandle = await page.$('#main');19 const boundingBox = await elementHandle.boundingBox();20 const x = boundingBox.x;21 const y = boundingBox.y;22 console.log(x,y);23 await browser.close();24})();25const { chromium } = require('playwright');26(async () => {27 const browser = await chromium.launch();28 const context = await browser.newContext();29 const page = await context.newPage();30 const elementHandle = await page.$('#main');
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 const elementHandle = await page.$('.navbar__inner');7 console.log(elementHandle);8 await browser.close();9})();
Using AI Code Generation
1const {chromium} = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 const elementHandle = await page.$('input[name="q"]');7 await elementHandle.focus();8 await page.screenshot({ path: `screenshot.png` });9 await browser.close();10})();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 const elementHandle = await page.$('text=Get started');7 await elementHandle.click();8 await browser.close();9})();10const { chromium } = require('playwright');11(async () => {12 const browser = await chromium.launch();13 const context = await browser.newContext();14 const page = await context.newPage();15 const elementHandle = await page.$('text=Get started');16 await elementHandle.click();17 await browser.close();18})();19const { chromium } = require('playwright');20(async () => {21 const browser = await chromium.launch();22 const context = await browser.newContext();23 const page = await context.newPage();24 const elementHandle = await page.$('text=Get started');25 await elementHandle.click();26 await browser.close();27})();28const { chromium } = require('playwright');29(async () => {30 const browser = await chromium.launch();31 const context = await browser.newContext();32 const page = await context.newPage();33 const elementHandle = await page.$('text=Get started');34 await elementHandle.click();35 await browser.close();36})();37const { chromium } = require('playwright');38(async () => {39 const browser = await chromium.launch();40 const context = await browser.newContext();41 const page = await context.newPage();42 const elementHandle = await page.$('text=Get started');43 await elementHandle.click();44 await browser.close();45})();46const { chromium } = require('playwright');47(async () => {48 const browser = await chromium.launch();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch({4 });5 const context = await browser.newContext();6 const page = await context.newPage();7 await page.fill('input[title="Search"]', 'Playwright');8 await page.click('input[value="Google Search"]');9 await page.waitForNavigation();10 const searchResults = await page.$('div#search');11 const searchResultsCount = await searchResults.$$eval('div.g', (elements) => elements.length);12 console.log(`Search results count: ${searchResultsCount}`);13 await browser.close();14})();15const { chromium } = require('playwright');16(async () => {17 const browser = await chromium.launch({18 });19 const context = await browser.newContext();20 const page = await context.newPage();21 await page.fill('input[title="Search"]', 'Playwright');22 await page.click('input[value="Google Search"]');23 await page.waitForNavigation();24 const searchResults = await page.$('div#search');25 const searchResultsCount = await searchResults.$$eval('div.g', (elements) => elements.length);26 console.log(`Search results count: ${searchResultsCount}`);27 await browser.close();28})();29const { chromium } = require('playwright');30(async () => {31 const browser = await chromium.launch({32 });33 const context = await browser.newContext();34 const page = await context.newPage();35 await page.fill('input[title="Search"]', 'Playwright');36 await page.click('input[value="Google Search"]');37 await page.waitForNavigation();38 const searchResults = await page.$('div#search');39 const searchResultsCount = await searchResults.$$eval('div.g', (elements) => elements.length);40 console.log(`Search results count: ${searchResultsCount}`);41 await browser.close();42})();43const {
Using AI Code Generation
1const {chromium} = require("playwright");2(async () => {3 const browser = await chromium.launch({headless: false});4 const context = await browser.newContext();5 const page = await context.newPage();6 const elementHandle = await page.$("text=Get Started");7 const boundingBox = await elementHandle.boundingBox();8 console.log(boundingBox);9 await browser.close();10})();11{ x: 20, y: 20, width: 150, height: 40 }12const {chromium} = require("playwright");13(async () => {14 const browser = await chromium.launch({headless: false});15 const context = await browser.newContext();16 const page = await context.newPage();17 const elementHandle = await page.$("text=Get Started");18 const boundingBox = await elementHandle.boundingBox();19 console.log(boundingBox);20 await page.mouse.click(boundingBox.x, boundingBox.y);21 await browser.close();22})();23{ x: 20, y: 20, width: 150, height: 40 }
Using AI Code Generation
1const {chromium} = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const page = await browser.newPage();5 const elementHandle = await page.$('text=Get started');6 await elementHandle.click();7 await browser.close();8})();9const {chromium} = require('playwright');10(async () => {11 const browser = await chromium.launch();12 const page = await browser.newPage();13 const elementHandle = await page.$('text=Get started');14 await elementHandle.click();15 await browser.close();16})();17const {chromium} = require('playwright');18(async () => {19 const browser = await chromium.launch();20 const page = await browser.newPage();21 const elementHandle = await page.$('text=Get started');22 await elementHandle.click();23 await browser.close();24})();25const {chromium} = require('playwright');26(async () => {27 const browser = await chromium.launch();28 const page = await browser.newPage();29 const elementHandle = await page.$('text=Get started');30 await elementHandle.click();31 await browser.close();32})();33const {chromium} = require('playwright');34(async () => {35 const browser = await chromium.launch();36 const page = await browser.newPage();37 const elementHandle = await page.$('text=Get started');38 await elementHandle.click();39 await browser.close();40})();41const {chromium} = require('playwright');42(async () => {43 const browser = await chromium.launch();44 const page = await browser.newPage();45 const elementHandle = await page.$('text=Get started');
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch({4 });5 const context = await browser.newContext();6 const page = await context.newPage();7 const searchInput = await page.$('input[name="q"]');8 await searchInput.fill('');9 await searchInput.fill('playwright');10 await page.click('input[value="Google Search"]');11 await page.waitForSelector('h3.LC20lb');12 const firstResult = await page.$('h3.LC20lb');13 const firstResultText = await firstResult.innerText();14 console.log(firstResultText);15 await browser.close();16})();
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!