I have been recently working on a website, which will mainly be used as a medium where various tourist agencies could post their travel offers.
The index page contains a functional filters area, where the user could perform an offer search based on multiple conditions.
<div id="offer-filters">
<h2>Filter search</h2>
<div id="filter-bars">
<ul id="filter-list">
<li>
<label for="searchagency">Agency</label>
<input list="agencies" id="searchagency" name="searchagency"
onclick="dataListFromOriginAgency('agencies', 'searchagency')">
</li>
<datalist id="agencies"></datalist>
<li>
<label for="searchdepart">Departure</label>
<input list="departures" id="searchdepart" name="searchdepart"
onclick="dataListFromOriginOffersDeparture('departures', 'searchdepart')">
</li>
<datalist id="departures"></datalist>
<li>
<label for="searchdestination">Destination</label>
<input list="destinations" id="searchdestination" name="searchdestination"
onclick="dataListFromOriginOffersDestination('destinations', 'searchdestination')">
</li>
<datalist id="destinations"></datalist>
<li>
<label for="searchpricerangefrom">Price below</label>
<input type="number" id="searchpricerangefrom" name="searchpricerangefrom" min="1"
max="1000000">
<label for="searchpricerangeto">over</label>
<input type="number" id="searchpricerangeto" name="searchpricerangeto" min="1"
max="1000000">
</li>
<li>
<label for="searchtransport">Transport</label>
<input list="transport" id="searchtransport" name="searchtransport"
onclick="dataListFromOriginOffersTransportation('transport', 'searchtransport')">
</li>
<datalist id="transport"></datalist>
<li>
<label for="searchstartdate">Start date</label>
<input type="date" name="searchstartdate" id="searchstartdate"></li>
<li>
<label for="searchenddate">Return date</label>
<input type="date" name="searchenddate" id="searchenddate">
</li>
</ul>
</div>
<button class="search-filter">Search</button>
</div>
The key idea is that the button present at the bottom would return functions based on how many inputs contain values, that saying how many inputs are not empty. I.e. an user performs a search of offers based on a certain agency, passing the agency name into the first input, and a destination which would be entered into the third one.
When i define a function that will return different results based on input conditions, some functions would never be called as the previous condition already evaulated.
function triggerFuncByScenario() {
if (!(document.querySelector("#searchagency").value === "")) {
getOffersByName();
}
else if (!(document.querySelector("#searchagency").value === "" && document.querySelector("#searchdestination").value === "")) {
getOffersByDestinationName();
}
Taken as an example, the first function normally occurs on button click, while the second one doesn't work because the first part of the condition is already evaluated, leading to the constant call of the first one.
Is there any solution so that every filter combination could be assigned to different functions?
The functions also use an AJAX request for obtaining the data.
function prepareOffers(type, route, objectJSON) {
var offer = document.getElementsByClassName("offer");
while (offer[0]) {
offer[0].parentNode.removeChild(offer[0]);
}
while (!(document.getElementById("offers-nav").innerHTML == "")) {
var nav = document.getElementById("offers-nav");
nav.innerHTML = "";
}
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function () {
if (httpRequest.readyState == 4) {
var response = httpRequest.responseText;
var respArray = response.split(",");
var arrayParsed = JSON.parse(respArray);
for (let i = 0; i < arrayParsed.length; i++) {
var offer = document.createElement("div");
offer.className = "offer";
document.getElementById("offers-list").appendChild(offer);
var offerFlex = document.createElement("div");
offerFlex.className = "offer-flex";
document.getElementsByClassName("offer")[i].appendChild(offerFlex);
var image = document.createElement("img");
image.setAttribute("alt", "Image description of an given agency offer destination");
image.setAttribute("src", ("img/" + arrayParsed[i].destination + ".jpg"));
image.setAttribute("class", "destination-image");
var image2 = document.createElement("img");
image2.setAttribute("alt", "Logo of an agency that provided the offer");
image2.setAttribute("src", ("img/" + arrayParsed[i].tourism_agency + ".png"));
image2.setAttribute("class", "agency-logo");
var markAsFavourite = document.createElement("a");
markAsFavourite.setAttribute("class", "favourite");
markAsFavourite.setAttribute("href", "#a");
markAsFavourite.setAttribute("onclick", "addToFavourites()");
markAsFavourite.innerHTML = "<i class='fas fa-star'></i> Add to favourites";
var list = document.createElement("ul");
document.getElementsByClassName("offer-flex")[i].appendChild(markAsFavourite);
document.getElementsByClassName("offer-flex")[i].insertBefore(list, markAsFavourite);
document.getElementsByClassName("offer-flex")[i].insertBefore(image2, list);
document.getElementsByClassName("offer-flex")[i].insertBefore(image, image2);
var element1 = list.appendChild(document.createElement("li"));
element1.setAttribute("class", "destination");
var element2 = list.appendChild(document.createElement("li"));
element2.setAttribute("class", "start");
var element3 = list.appendChild(document.createElement("li"));
element3.setAttribute("class", "end");
var element4 = list.appendChild(document.createElement("li"));
element4.setAttribute("class", "price");
var element5 = list.appendChild(document.createElement("li"));
element5.setAttribute("class", "transportation");
var element6 = list.appendChild(document.createElement("li"));
element6.setAttribute("class", "more-info");
document.getElementsByClassName("destination")[i].innerHTML = "Destination: " + arrayParsed[i].destination;
document.getElementsByClassName("start")[i].innerHTML = "Start date: " + arrayParsed[i].start;
document.getElementsByClassName("end")[i].innerHTML = "Return date: " + arrayParsed[i].end;
document.getElementsByClassName("price")[i].innerHTML = "Price: " + arrayParsed[i].price + " €";
document.getElementsByClassName("transportation")[i].innerHTML = "Transport: " + arrayParsed[i].transportation;
document.getElementsByClassName("more-info")[i].innerHTML = "For more info please click <a href='#offers-page' onClick='displayMoreInfo()'>here</a>";
document.getElementById("offers-count").innerHTML = "Showing " + document.querySelectorAll(".offer").length + " from " + arrayParsed.length + " offer(s):";
}
if (arrayParsed.length == 0) {
var noOffers = document.createElement("h2");
noOffers.setAttribute("id", "no-offers");
document.querySelectorAll(".show-offers")[0].insertBefore(noOffers, document.querySelector("#offers-list"));
document.querySelector("#no-offers").innerHTML = "No offers found!";
} else {
var noOffers = document.createElement("h2");
noOffers.setAttribute("id", "no-offers");
document.querySelectorAll(".show-offers")[0].insertBefore(noOffers, document.querySelector("#offers-list"));
document.querySelector("#no-offers").remove();
}
}
}
httpRequest.open(type, route, true);
if (!(objectJSON == "" || objectJSON == null)) {
httpRequest.setRequestHeader("Content-type", "application/json");
httpRequest.send(objectJSON);
} else {
httpRequest.send();
}
Thank you in advance.
So I've been looking it over and just a thought, have you tried to nest your if-else statements?
function triggetFuncByScenario(){
if(!(document.querySelector("#searchagency").value === "")){
if(!(document.querySelector("#searchdestination").value === "")){
getOffersByDestinationName();
}else{
getOffersByName();
}
}
}
To me, it looks like that little oversight is what is causing your problem.
By nesting this you are getting a certain check of all the given conditions.
Hope it is helpful and good luck with your project.
While simply changing the order in which you evaluate your conditions could get the result you want, a more verbose solution can make very clear what is happening at each step.
Here, the evaluateSearchFields function reports a single value representing which combination of fields the user filled in. With this information, you can be confident about which action to take.
I wouldn't bother with this level of detail in most cases, but sometimes clarity is what we need so we can proceed from a solid foundation.
function triggerFuncByScenario() {
const
searchAgency = document.getElementById("searchagency"),
searchDestination = document.getElementById("searchdestination"),
agencyEmpty = (searchAgency.value === ""),
destinationEmpty = (searchDestination.value === "");
if( evaluateSearchFields() == "agencyOnly" ){ getOffersByName(); }
else if( evaluateSearchFields() == "both" ){ getOffersByDestinationName(); }
}
function evaluateSearchFields(){
if(!agencyEmpty && !destinationEmpty){ return "both"; }
if(!agencyEmpty && destinationEmpty){ return "agencyOnly"; }
if( agencyEmpty && !destinationEmpty){ return "destinationOnly"; }
if( agencyEmpty && destinationEmpty){ return "neither"; }
else { return "this is impossible"; }
}
For this part removing else will evaluate both conditions and execute.
Also try to use getElementById if you need to get only one element by ID
function triggerFuncByScenario() {
var searchAgency = document.getElementById("searchagency");
if (!(searchAgency.value === "")) {
getOffersByName();
}
if (!(searchAgency.value === "" &&
document.querySelector("#searchdestination").value === "")) {
getOffersByDestinationName();
}
}
Related
I am a high school student and I am trying to make a password cracker to show my school how vulnerable their Student Dashboard is. A student Dashboard is a website that contains student accounts, links, and private information like addresses, passwords, and relatives.
Everyone's password has the following syntax: Pmonth/day/year
EXAMPLE: P05/03/2005
There is a problem though, when the code clicks the sign in button, the URL changes, and the page reloads, which stops the code when I run it in the console.
Is there a way that I could keep the code running from console even if page reloads.
I have thought of using web cookies to store the last used password, and then when the page reloads, just input it into the password textbox, but I am not sure, since I haven't used cookies before.
Any help is greatly appreciated.
What I am aiming to do is that I input an Id, and then it tries to crack the password by going through all dates a year has after 2003.
I will appreciate all answers, but I would like my answer in raw javascript(no libraries).
The sign in page consists of an username textbox, a password textbox and a sign in button.
Here's what the sign in page looks like: Sign in page
Here is the source code of the page:
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=10.000"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<meta http-equiv="cache-control" content="no-cache,no-store"/>
<meta http-equiv="pragma" content="no-cache"/>
<meta http-equiv="expires" content="-1"/>
<meta name='mswebdialog-title' content='Connecting to Broward County Public Schools'/>
<title>Sign In</title>
<script type='text/javascript'>
//<![CDATA[
function LoginErrors(){this.userNameFormatError = 'Enter your user ID in the format \u0026quot;domain\\user\u0026quot; or \u0026quot;user#domain\u0026quot;.'; this.passwordEmpty = 'Enter your password.'; this.passwordTooLong = 'Password must be shorter than 128 characters.';}; var maxPasswordLength = 128;
//]]>
</script>
<script type='text/javascript'>
//<![CDATA[
// Copyright (c) Microsoft Corporation. All rights reserved.
function InputUtil(errTextElementID, errDisplayElementID) {
if (!errTextElementID) errTextElementID = 'errorText';
if (!errDisplayElementID) errDisplayElementID = 'error';
this.hasFocus = false;
this.errLabel = document.getElementById(errTextElementID);
this.errDisplay = document.getElementById(errDisplayElementID);
};
InputUtil.prototype.canDisplayError = function () {
return this.errLabel && this.errDisplay;
}
InputUtil.prototype.checkError = function () {
if (!this.canDisplayError){
throw new Error ('Error element not present');
}
if (this.errLabel && this.errLabel.innerHTML) {
this.errDisplay.style.display = '';
var cause = this.errLabel.getAttribute('for');
if (cause) {
var causeNode = document.getElementById(cause);
if (causeNode && causeNode.value) {
causeNode.focus();
this.hasFocus = true;
}
}
}
else {
this.errDisplay.style.display = 'none';
}
};
InputUtil.prototype.setInitialFocus = function (input) {
if (this.hasFocus) return;
var node = document.getElementById(input);
if (node) {
if ((/^\s*$/).test(node.value)) {
node.focus();
this.hasFocus = true;
}
}
};
InputUtil.prototype.setError = function (input, errorMsg) {
if (!this.canDisplayError) {
throw new Error('Error element not present');
}
input.focus();
if (errorMsg) {
this.errLabel.innerHTML = errorMsg;
}
this.errLabel.setAttribute('for', input.id);
this.errDisplay.style.display = '';
};
InputUtil.makePlaceholder = function (input) {
var ua = navigator.userAgent;
if (ua != null &&
(ua.match(/MSIE 9.0/) != null ||
ua.match(/MSIE 8.0/) != null ||
ua.match(/MSIE 7.0/) != null)) {
var node = document.getElementById(input);
if (node) {
var placeholder = node.getAttribute("placeholder");
if (placeholder != null && placeholder != '') {
var label = document.createElement('input');
label.type = "text";
label.value = placeholder;
label.readOnly = true;
label.style.position = 'absolute';
label.style.borderColor = 'transparent';
label.className = node.className + ' hint';
label.tabIndex = -1;
label.onfocus = function () { this.nextSibling.focus(); };
node.style.position = 'relative';
node.parentNode.style.position = 'relative';
node.parentNode.insertBefore(label, node);
node.onkeyup = function () { InputUtil.showHint(this); };
node.onblur = function () { InputUtil.showHint(this); };
node.style.background = 'transparent';
node.setAttribute("placeholder", "");
InputUtil.showHint(node);
}
}
}
};
InputUtil.focus = function (inputField) {
var node = document.getElementById(inputField);
if (node) node.focus();
};
InputUtil.hasClass = function(node, clsName) {
return node.className.match(new RegExp('(\\s|^)' + clsName + '(\\s|$)'));
};
InputUtil.addClass = function(node, clsName) {
if (!this.hasClass(node, clsName)) node.className += " " + clsName;
};
InputUtil.removeClass = function(node, clsName) {
if (this.hasClass(node, clsName)) {
var reg = new RegExp('(\\s|^)' + clsName + '(\\s|$)');
node.className = node.className.replace(reg, ' ');
}
};
InputUtil.showHint = function (node, gotFocus) {
if (node.value && node.value != '') {
node.previousSibling.style.display = 'none';
}
else {
node.previousSibling.style.display = '';
}
};
//]]>
</script>
<link rel="stylesheet" type="text/css" href="/adfs/portal/css/style.css?id=D74D4D6943F32AE6F7F11D14D601DBB0E1A58919176EE512150366B6279AAF99" /><style>.illustrationClass {background-image:url(/adfs/portal/illustration/illustration.jpg?id=EB0C84D8C0F5E1E10127F3AD4A4C45BCDAA7AC32FFE204DACEBEAF85C61DA2F9);}</style>
</head>
<body dir="ltr" class="body">
<div id="noScript" style="position:static; width:100%; height:100%; z-index:100">
<h1>JavaScript required</h1>
<p>JavaScript is required. This web browser does not support JavaScript or JavaScript in this web browser is not enabled.</p>
<p>To find out if your web browser supports JavaScript or to enable JavaScript, see web browser help.</p>
</div>
<script type="text/javascript" language="JavaScript">
document.getElementById("noScript").style.display = "none";
</script>
<div id="fullPage">
<div id="brandingWrapper" class="float">
<div id="branding"></div>
</div>
<div id="contentWrapper" class="float">
<div id="content">
<div id="header">
<img class="logoImage" src="/adfs/portal/logo/logo.png?id=4F68FA71CF303418A19ABB7297038B46FA3E25ED3754C2175A7B840EC6F97BE8" alt="Broward County Public Schools"/>
</div>
<div id="workArea">
<div id="authArea" class="groupMargin">
<div id="loginArea">
<div id="loginMessage" class="groupMargin">Sign in with your organizational account</div>
<form method="post" id="loginForm" autocomplete="off" novalidate="novalidate" onKeyPress="if (event && event.keyCode == 13) Login.submitLoginRequest();" action="/adfs/ls/?wctx=WsFedOwinState%3doJ9avOrRYr1UaVPxwGOAIzjfQ78zxpRhLHRmhne8M1AEjI9Y5SUSP0viJgR2iCtpjpu-gGqW73MjMkyVrK9b_N9m5JlVSyznBQxTGDsRm5WDilyumMYDi4x5qL9-To1jCTs2bXP7iiZJuHS0aLiN-jXhIHy26i4J9qpsUHbiivCUYCZQNb0m68RqVJwDU-Cqf0DW1ieuP1_sAcqk3l0nwBlRoG-cO039YHVhBOyZSbnHfZtGqJRSX7p6yt5wwRQ6Y5vz9dPJ8V7FTz6-GIZPnk4ee4A&wa=wsignin1.0&wtrealm=http%3a%2f%2fgb.browardschools.com%2fpinnacle%2fgradebook%2f" >
<div id="error" class="fieldMargin error smallText">
<label id="errorText" for=""></label>
</div>
<div id="formsAuthenticationArea">
<div id="userNameArea">
<input id="userNameInput" name="UserName" type="email" value="" tabindex="1" class="text fullWidth"
spellcheck="false" placeholder="someone#example.com" autocomplete="off"/>
</div>
<div id="passwordArea">
<input id="passwordInput" name="Password" type="password" tabindex="2" class="text fullWidth"
placeholder="Password" autocomplete="off"/>
</div>
<div id="kmsiArea" style="display:none">
<input type="checkbox" name="Kmsi" id="kmsiInput" value="true" tabindex="3" />
<label for="kmsiInput">Keep me signed in</label>
</div>
<div id="submissionArea" class="submitMargin">
<span id="submitButton" class="submit" tabindex="4"
onKeyPress="if (event && event.keyCode == 32) Login.submitLoginRequest();"
onclick="return Login.submitLoginRequest();">Sign in</span>
</div>
</div>
<input id="optionForms" type="hidden" name="AuthMethod" value="FormsAuthentication"/>
</form>
<div id="authOptions">
<form id="options" method="post" action="https://fs.browardschools.com:443/adfs/ls/?wctx=WsFedOwinState%3doJ9avOrRYr1UaVPxwGOAIzjfQ78zxpRhLHRmhne8M1AEjI9Y5SUSP0viJgR2iCtpjpu-gGqW73MjMkyVrK9b_N9m5JlVSyznBQxTGDsRm5WDilyumMYDi4x5qL9-To1jCTs2bXP7iiZJuHS0aLiN-jXhIHy26i4J9qpsUHbiivCUYCZQNb0m68RqVJwDU-Cqf0DW1ieuP1_sAcqk3l0nwBlRoG-cO039YHVhBOyZSbnHfZtGqJRSX7p6yt5wwRQ6Y5vz9dPJ8V7FTz6-GIZPnk4ee4A&wa=wsignin1.0&wtrealm=http%3a%2f%2fgb.browardschools.com%2fpinnacle%2fgradebook%2f">
<script type="text/javascript">
function SelectOption(option) {
var i = document.getElementById('optionSelection');
i.value = option;
document.forms['options'].submit();
return false;
}
</script>
<input id="optionSelection" type="hidden" name="AuthMethod" />
<div class='groupMargin'></div>
</form>
</div>
<div id="introduction" class="groupMargin">
<p align=center><b>REPORT CHILD ABUSE</b></p><p align=center><b>CALL 1-800-96ABUSE OR 1-800-962-2873</b></p></BR><p align=center><b>Students</b></p><p>If you are a student, your login name is your
student number (06########). If you have forgotten your password, please contact your teacher. </p></BR><p
align=center><b>Staff</b></p><p>If you are staff, your login name should be your staff ID (P0#######). If you have forgotten your password,
please contact your tech.</p></BR><p align=center><b>Parents Accessing Pinnacle</b></p><p>If you are a parent of a student in grades 6-12
and are accessing Pinnacle, please use your child’s Active Directory userid and password to login. If you are the parent of a child in
grades 3-5, please use the <b>BCPS Mobile App</b> to view the current average grade your child has earned in each class.</p>
</div>
<script type="text/javascript">
//<![CDATA[
function Login() {
}
Login.userNameInput = 'userNameInput';
Login.passwordInput = 'passwordInput';
Login.initialize = function () {
var u = new InputUtil();
u.checkError();
u.setInitialFocus(Login.userNameInput);
u.setInitialFocus(Login.passwordInput);
}();
Login.submitLoginRequest = function () {
var u = new InputUtil();
var e = new LoginErrors();
var userName = document.getElementById(Login.userNameInput);
var password = document.getElementById(Login.passwordInput);
if (!userName.value || !userName.value.match('[#\\\\]')) {
u.setError(userName, e.userNameFormatError);
return false;
}
if (!password.value) {
u.setError(password, e.passwordEmpty);
return false;
}
if (password.value.length > maxPasswordLength) {
u.setError(password, e.passwordTooLong);
return false;
}
document.forms['loginForm'].submit();
return false;
};
InputUtil.makePlaceholder(Login.userNameInput);
InputUtil.makePlaceholder(Login.passwordInput);
//]]>
</script>
</div>
</div>
</div>
<div id="footerPlaceholder"></div>
</div>
<div id="footer">
<div id="footerLinks" class="floatReverse">
<div><span id="copyright">© 2013 Microsoft</span></div>
</div>
</div>
</div>
</div>
<script type='text/javascript'>
//<![CDATA[
// Copyright (c) Microsoft Corporation. All rights reserved.
// This file contains several workarounds on inconsistent browser behaviors that administrators may customize.
"use strict";
// iPhone email friendly keyboard does not include "\" key, use regular keyboard instead.
// Note change input type does not work on all versions of all browsers.
if (navigator.userAgent.match(/iPhone/i) != null) {
var emails = document.querySelectorAll("input[type='email']");
if (emails) {
for (var i = 0; i < emails.length; i++) {
emails[i].type = 'text';
}
}
}
// In the CSS file we set the ms-viewport to be consistent with the device dimensions,
// which is necessary for correct functionality of immersive IE.
// However, for Windows 8 phone we need to reset the ms-viewport's dimension to its original
// values (auto), otherwise the viewport dimensions will be wrong for Windows 8 phone.
// Windows 8 phone has agent string 'IEMobile 10.0'
if (navigator.userAgent.match(/IEMobile\/10\.0/)) {
var msViewportStyle = document.createElement("style");
msViewportStyle.appendChild(
document.createTextNode(
"#-ms-viewport{width:auto!important}"
)
);
msViewportStyle.appendChild(
document.createTextNode(
"#-ms-viewport{height:auto!important}"
)
);
document.getElementsByTagName("head")[0].appendChild(msViewportStyle);
}
// If the innerWidth is defined, use it as the viewport width.
if (window.innerWidth && window.outerWidth && window.innerWidth !== window.outerWidth) {
var viewport = document.querySelector("meta[name=viewport]");
viewport.setAttribute('content', 'width=' + window.innerWidth + 'px; initial-scale=1.0; maximum-scale=1.0');
}
// Gets the current style of a specific property for a specific element.
function getStyle(element, styleProp) {
var propStyle = null;
if (element && element.currentStyle) {
propStyle = element.currentStyle[styleProp];
}
else if (element && window.getComputedStyle) {
propStyle = document.defaultView.getComputedStyle(element, null).getPropertyValue(styleProp);
}
return propStyle;
}
// The script below is used for downloading the illustration image
// only when the branding is displaying. This script work together
// with the code in PageBase.cs that sets the html inline style
// containing the class 'illustrationClass' with the background image.
var computeLoadIllustration = function () {
var branding = document.getElementById("branding");
var brandingDisplay = getStyle(branding, "display");
var brandingWrapperDisplay = getStyle(document.getElementById("brandingWrapper"), "display");
if (brandingDisplay && brandingDisplay !== "none" &&
brandingWrapperDisplay && brandingWrapperDisplay !== "none") {
var newClass = "illustrationClass";
if (branding.classList && branding.classList.add) {
branding.classList.add(newClass);
} else if (branding.className !== undefined) {
branding.className += " " + newClass;
}
if (window.removeEventListener) {
window.removeEventListener('load', computeLoadIllustration, false);
window.removeEventListener('resize', computeLoadIllustration, false);
}
else if (window.detachEvent) {
window.detachEvent('onload', computeLoadIllustration);
window.detachEvent('onresize', computeLoadIllustration);
}
}
};
if (window.addEventListener) {
window.addEventListener('resize', computeLoadIllustration, false);
window.addEventListener('load', computeLoadIllustration, false);
}
else if (window.attachEvent) {
window.attachEvent('onresize', computeLoadIllustration);
window.attachEvent('onload', computeLoadIllustration);
}
if (typeof Login != 'undefined'){
Login.submitLoginRequest = function () {
var u = new InputUtil();
var e = new LoginErrors();
var userName = document.getElementById(Login.userNameInput);
var password = document.getElementById(Login.passwordInput);
if (userName.value && !userName.value.match('[#\\\\]'))
{
var userNameValue = 'browardschools\\' + userName.value;
document.forms['loginForm'].UserName.value = userNameValue;
}
if (!userName.value) {
u.setError(userName, e.userNameFormatError);
return false;
}
if (!password.value)
{
u.setError(password, e.passwordEmpty);
return false;
}
document.forms['loginForm'].submit();
return false;
};
}
// Check whether the loginMessage element is present on this page.
var loginMessage = document.getElementById('loginMessage');
if (loginMessage)
{
// loginMessage element is present, modify its properties.
loginMessage.innerHTML = 'Sign in with your Browardschools Personnel Number or Student Number';
}
//]]>
</script>
</body>
</html>
Here is my following code:
//Gets id textbox
var username = document.getElementById("userNameInput");
//Gets password textbox
var password = document.getElementById("passwordInput");
//Gets button
var clickbutton = document.getElementById("submitButton");
var num1 = 1; // Month, start
var num2 = 0; // Day start
var num3 = 2003; // Year start
var id = username.value;
var passwrd = password.value;
var _DOB = "P" + "0" + num1 + "/" + num2 + "/" + num3; //Sets up the syntax for password Pmonth/day/year
function writeInput()
{
password.value = _DOB; // writes the _DOB value into the password textbox
clickbutton.click(); //clicks the sign in button
//SOTRES THE ID
id = username.value;
//ADDS THE NEXT DAY
num2 += 1; // If password is incorrect.
//RESETS DAY WHEN REACHES 31(max number a month has)
if(num2 > 31)
{
num2 = 1; // resets day to 1
num1 += 1; // adds 1 to the month count.
}
// ADDS NEXT YEAR
if(num2 == 31 && num1 == 12) // when reaches the last day of a year, it resets month and day, but adds one to the year count.
{
num3 += 1;
}
//RESET MONTH
if(num1 > 12)
{
num1 = 1;
}
if(num2 < 10)//Adds 0 to month and day if it is less than 10. Example: P5/5/2021 is not a correct systax, it turns to P05/05/2021. It adds the zeroes.
{
_DOB = "P" + "0" + num1 + "/" + "0" + num2 + "/" + num3;
}
else
{
_DOB = "P" + "0" + num1 + "/" + num2 + "/" + num3;
}
//Some output
clickbutton.onclick = console.log("SIGN IN BUTTON CLICKED");
console.log("Password used: " + _DOB);
}
}, 100);
}
setInterval(function()
{
writeInput();
}, 500);
Your challenge is to persist your JavaScript code inside a website hosted by someone else. All code within your browsers console is obsolete after page reload.
Another challenge you are facing is a legal one. It's highly recommended to get a permission to access an online service for the purpose you described. Any kind of security assessment has to be coordinated and aligned with the organization responsible for the questioned online service.
Since you will not want to change the content of the web server for legal reasons, you would need a tool manipulate the content served by the webserver within your client (read "browser").
There are browser automation tool like Puppeteer or Selenium Webdriver you can use to request any url repeatedly and to automate certain actions within the context of a browser like clicking elements, filling forms, executing JavaScript and so on.
Additionally there a fuzzers that can perform what is called credential stuffing. You can read more here about Burp Suite.
I am trying to create a multiplication table in JavaScript. The user is prompted to provide the Table number (1 to 10) after which all the question marks ('?') are replaced with that number. The user then needs to enter the answers in all the provided text fields. Finally, the user will have the option to check the answer (i.e. whether it is right or wrong).
When I run my code. After entering the user data to prompt it shows Incorrect infront of each textfield and the user entered value just before the Check answers button. How can I remove them to be shown initially.
Output:
My code:
function result() {
var value = document.getElementById("a1").value;
var checkMessageSpan1 = document.getElementById("checkMessage1");
var checkMessageSpan2 = document.getElementById("checkMessage2");
var r = x * 1;
if (value == x) {
checkMessageSpan1.innerHTML = "<span style=\"color:green\">"+"Correct!";
}else{
checkMessageSpan1.innerHTML = "<span style=\"color:red\">"+"Incorrect!";
}
var value = document.getElementById("a2").value;
var r = x * 2;
if (value == r) {
checkMessageSpan2.innerHTML = "<span style=\"color:green\">"+"Correct!";
}else{
checkMessageSpan2.innerHTML = "<span style=\"color:red\">"+"Incorrect!";
}
</script>
<button onClick="alert_field()"> Generate Question</button><br><br>
<p id="s1">
? x 1 = <input type="text" id="a1"><span id="checkMessage1"></span><br>
? x 2 = <input type="text" id="a2"><span id="checkMessage2"></span><br>
</p><br><br>
<p id="a"></p>
Check answers
For replacing all special characters, you may leverage regular expressions in js
var res=str.replace(/[^a-zA-Z0-9]/g,x); instead of
var res = str.replace("?",x);
More on Regular expressions in JS https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
Try to add this code:
var value = document.getElementById("a1").value;
if (checkMessageSpan1.style.display === "none") {
checkMessageSpan1.style.display = "inline-block";
} else {
checkMessageSpan1.style.display = "none";
}
var value = document.getElementById("a2").value;
if (checkMessageSpan2.style.display === "none") {
checkMessageSpan2.style.display = "inline-block";
} else {
checkMessageSpan2.style.display = "none";
}
So I'm creating a search website where the user enters a part of a name or a full name and then presses a button. And based on the string entered, it displays a hint of names of actors that contain the string or sub-string. The names are stored in a mysql database.
I was able to accomplish all of that by using ajax to interact with php and php to interact with mysql database. However, if the user enters nothing, it's supposed to display nothing.
So I though of just deleting all names when the field text is empty (in other words, I just delete all p elements of a div).
That's where the problem is. Even though I used element.removeChild(), It doesn't delete anything. Instead, even when the string is empty and the user presses the button, it keeps the same info from the previous search. I already searched on similar questions about removeChild(), but none of the answers or hints I found have worked for me.
Here is the javascript and html code below.
var array = [];
var str = "";
var clicked_id = "";
var body = document.getElementsByTagName('BODY')[0];
var actors = document.getElementById('actors');
var roles = document.getElementById('roles');
actors.addEventListener("click", function(){
getData(this.id);
}, false);
roles.addEventListener("click", function(){
getData(this.id);
}, false);
function getData(myid) {
str = document.getElementById('mytext').value;
clicked_id = myid;
var id = "roles";
console.log(clicked_id);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
array = JSON.parse(xmlhttp.responseText);
var element = document.createElement('div');
element.id = "mydiv";
if (str == "" && element.hasChildNodes() != null) {
while (element.hasChildNodes()) {
element.removeChild(element.lastChild);
}
} else {
for (var i = 0; i < array.length; i++) {
var p = document.createElement('p');
p.append(array[i]);
element.append(p);
}
body.append(element);
}
}
};
xmlhttp.open("GET", "controller.php?q="+str , true);
xmlhttp.send();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<h2>Search for either all roles or all actors in the database imdb_small</h2>
<hr> Search string <br>
<input type="text" id="mytext"> <br>
<input type="button" value="Actors" id="actors">
<input type="button" value="Roles" id="roles" > <br> <br>
<hr> <br><br>
</body>
<?php
$servername="localhost";
$username="root";
$password="";
$dbname="demon";
//CREATE CONNECTION
$conn=new mysqli($servername,$username,$password,$dbname);
//CHECK CONNECTION
if ($conn->connect_error)
{
die("connection failed:".$conn->connect_error);
}
$sql="delete from category where SUBCATEGORY_ID='".$_GET["id"]."'";
$result=$conn->query($sql);
if ($result===TRUE)
{
echo"RECORD DELETED SUCCESSFULLY";
}
else
{
echo "ERROR:".$sql."<br>".$conn->error;
}
$conn->close();
?>
var array = [];
var str = "";
var clicked_id = "";
var body = document.getElementsByTagName('BODY')[0];
var actors = document.getElementById('actors');
var roles = document.getElementById('roles');
actors.addEventListener("click", function(){
getData(this.id);
}, false);
roles.addEventListener("click", function(){
getData(this.id);
}, false);
function getData(myid) {
str = document.getElementById('mytext').value;
clicked_id = myid;
var id = "roles";
console.log(clicked_id);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
array = JSON.parse(xmlhttp.responseText);
// Check for an existing mydiv first here, before creating a new one
// If it exists then get it and check its child nodes
var element = document.getElementById('#mydiv');
element = element ? element : document.createElement('div');
element.id = "mydiv";
if (str == "" && element.hasChildNodes() != null) {
while (element.hasChildNodes()) {
element.removeChild(element.lastChild);
}
} else {
for (var i = 0; i < array.length; i++) {
var p = document.createElement('p');
p.append(array[i]);
element.append(p);
}
body.append(element);
}
}
};
xmlhttp.open("GET", "controller.php?q="+str , true);
xmlhttp.send();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<h2>Search for either all roles or all actors in the database imdb_small</h2>
<hr> Search string <br>
<input type="text" id="mytext"> <br>
<input type="button" value="Actors" id="actors">
<input type="button" value="Roles" id="roles" > <br> <br>
<hr> <br><br>
</body>
I am making a text based game for school and I am stuck with trying to set a variable as an text input. What I would like to happen is the player type start into the input and it do what is inside of the if statement. However from there I would like the player to enter a username and then it set the variable of "name" to what they input but with out it saving the name as "start".
//js
var name = "";
var beginBeenTo = false;
if (beginBeenTo == false) {
if (input == "START") {
beginBeenTo = true;
page = page + 1;
healthPoints = 25;
soundEveningBreeze.play();
$("#welcome_message").show().insertBefore("#placeholder").delay(3000).fadeOut(3000);
$("<br><p class='text'>You there, what is your name?</p>").hide().insertBefore("#placeholder").delay(7000).fadeIn(3000);
if (input != "" || namingBeenTo == false) {
name = input;
}
}
}
document.getElementById("print_name").innerHTML = name;
Quite simply, watch for some event (keyup in my case), check if the input value is START, if so ask for a username.
var started = false;
var username = '';
$('input').on('keyup', function(){
var tmpValue = $(this).val();
if(started){
username = tmpValue
}
if(tmpValue === 'START') {
started = true;
$(this).val('')
$(this).attr('placeholder','Username')
}
$('#username').text(username)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<span id="username"></span>
<br>
<input type="text" placeholder="Type START to play">
it could be done with use of function like this :
var name = "";
$("form").submit(function() {
var input = $("#command_input").val().toUpperCase();
if (input == "START") {
name = $("#input_form").val();
}
}
document.getElementById("print_name").innerHTML = name;
you were missing one of #(hashtag)
And this code would work
Thanks & Cheers
This function replicates the user experience of a Select/MultiSelect dropdown element - displaying the values of checkboxes checked in a container (adds/removes them when they're checked/unchecked), and if more than 3 items have been checked it displays the # selected instead of the values selected.
It's a combination of 2 functions and they're not playing well together when items are unchecked (i.e. it's removing the values but not the commas, doesn't work correctly when more than 3 items have been selected, etc.)
I think it would be much better if I used an array to store the values, adding/removing values from the array when items are checked/unchecked, and I know how do to in PHP but not in Javascript. This code should create the array, but I can't figure out how to integrate it into my code.
$('input:checkbox[name="color[]"]:checked').each(function () {
selectedColors.push($(this).val());
});
Existing Code:
JS
$(".dropdown_container ul li").click(function () {
var text = $(this.children[0]).find("input").val();
var text_edited = text.replace(/_/g, " ");
var currentHtml = $(".dropdown_box span").html();
var positionLocation = currentHtml.indexOf(text_edited);
var numberChecked = $('input[name="color[]"]:checked').length;
if (positionLocation < 1) {
if (numberChecked <= 3) {
$(".dropdown_box span").html(currentHtml.replace('Colors', ''));
$(".dropdown_box span").append(', ' + text_edited);
} else {
$(".dropdown_box span").html(currentHtml.replace(currentHtml, numberChecked + " Selected"));
}
} else {
(currentHtmlRevised = currentHtml.replace(text_edited, ""));
$(".dropdown_box span").html(currentHtmlRevised.replace(currentHtml));
}
});
HTML
<div class="dropdown_box"><span>Colors</span></div>
<div class="dropdown_container">
<ul id="select_colors">
<li>
<label><a href="#"><div style="background-color: #ff8c00" class="color" onclick="toggle_colorbox_alt(this);"><div class=CheckMark>✓</div>
<input type="checkbox" name="color[]" value="Black" class="cbx"/>
</div>Black</a></label>
</li>
<!-- More List Items --!>
</ul>
</div>
Easiest to just replace the entire content each time. Also use the change event instead of the click event.
$(".dropdown_container input").change(function () {
var checked = $(".dropdown_container input:checked");
var span = $(".dropdown_box span");
if (checked.length > 3) {
span.html("" + checked.length + " selected");
}
else {
span.html(checked.map(function () { return $(this).val().replace("_"," "); }).get().join(", "));
}
});
Example: http://jsfiddle.net/bman654/FCVjj/
try this:
$('.cbx').change(function(){
var cbx = $('.cbx:checked');
var str = '';
if (cbx.length<=3 && cbx.length!=0){
for (var i=0;i<cbx.length;i++){
if (i>0) str += ', ';
str += cbx[i].value;
}
} else if (cbx.length==0){
str = 'Colors';
} else {
str = cbx.length;
}
$('.dropdown_box span').html(str);
});