Delete a button upon click - javascript

I'm trying to get my button to delete itself after being clicked, as it shouldn't be clicked twice, and I think I may get the reference error because I'm using an online compiler. I also have a hard time changing to jquery, as it seems to mess up everything else I wrote.
I've looked through a ton of stack overflow pages, none of them seem to have malfunctioning code after the switch to jquery. I would prefer to have a way to do this in base html, but if not, I hope someone can explain how to make the switch.
var clicks = 0;
var cursor1 = false;
var autoclicker = false;
//Click Button And Cursor Upgrade
document.getElementById("clickMe").onclick = function() {
clicks++;
if (cursor1 == true) clicks++;
document.getElementById('output').innerHTML = clicks;
document.getElementById("Cursors").onclick = function() {
//PAY UP, PEASANT
clicks -= 100;
//NO MONEY, NO SERVICE
if (clicks < 0) {
clicks += 100;
alert("You are too poor! Peasant...");
} else if (cursor1 == true) {
clicks += 100;
alert("You can't do that!")
} else {
cursor1 = true;
alert("You bought an extra cursor!");
}
document.getElementById('output').innerHTML = clicks;
}
}
//Autoclicker
var delay = 1000;
var autoClick1 = false;
var autoClick2 = false;
var autoClick3 = false;
var autoClick4 = false;
var autoClick5 = false;
var autoClick6 = false;
var autoClick7 = false;
var autoClick8 = false;
var autoClick9 = false;
var autoClick0 = false;
document.getElementById("AutoClicker").onclick = function() {
clicks -= 250;
if (clicks < 0) {
clicks += 250;
alert("You are too poor! Peasant...");
} else if (autoclicker == true) {
clicks += 250;
alert("You can't do that!");
} else {
autoclicker = true;
alert("You bought the autoclicker!");
document.getElementById('output').innerHTML = clicks;
setInterval(clickIncrement, delay);
$("input").remove("AutoClicker");
}
}
var autoCMax = false;
document.getElementById("moreAutoC").onclick = function() {
clicks -= 250;
if (clicks < 0) {
clicks += 250;
alert("You are too poor! Peasant...");
} else if (autoCMax == true) {
clicks += 250;
alert("It's already maxed!");
} else {
if (autoClick0 == false) {
autoClick0 = true;
alert("You bought 1 more autoclicker! Autoclickers:2");
} else if (autoClick0 == true && autoClick1 != true) {
autoClick1 = true;
alert("You bought 1 more autoclicker! Autoclickers:3");
} else if (autoClick0 == true && autoClick1 == true && autoClick2 != true) {
autoClick2 = true;
alert("You bought 1 more autoclicker! Autoclickers:4");
} else if (autoClick0 == true && autoClick1 == true && autoClick2 == true && autoClick3 != true) {
autoClick3 = true;
alert("You bought 1 more autoclicker! Autoclickers:5");
} else if (autoClick0 == true && autoClick1 == true && autoClick2 == true && autoClick3 == true && autoClick4 != true) {
autoClick4 = true;
alert("You bought 1 more autoclicker! Autoclickers:6");
} else if (autoClick0 == true && autoClick1 == true && autoClick2 == true && autoClick3 == true && autoClick4 == true && autoClick5 != true) {
autoClick5 = true;
alert("You bought 1 more autoclicker! Autoclickers:7");
} else if (autoClick0 == true && autoClick1 == true && autoClick2 == true && autoClick3 == true && autoClick4 == true && autoClick5 == true && autoClick6 != true) {
autoClick6 = true;
alert("You bought 1 more autoclicker! Autoclickers:8");
} else if (autoClick0 == true && autoClick1 == true && autoClick2 == true && autoClick3 == true && autoClick4 == true && autoClick5 == true && autoClick6 == true && autoClick7 != true) {
autoClick7 = true;
alert("You bought 1 more autoclicker! Autoclickers:9");
} else if (autoClick0 == true && autoClick1 == true && autoClick2 == true && autoClick3 == true && autoClick4 == true && autoClick5 == true && autoClick6 == true && autoClick7 == true && autoClick8 != true) {
autoClick8 = true;
alert("You bought 1 more autoclicker! Autoclickers:10");
} else if (autoClick0 == true && autoClick1 == true && autoClick2 == true && autoClick3 == true && autoClick4 == true && autoClick5 == true && autoClick6 == true && autoClick7 == true && autoClick8 == true && autoClick9 != true) {
autoClick9 = true;
alert("You bought 1 more autoclicker! Autoclickers:11");
autoCMax = true;
} else {
alert("It's already maxed!")
}
if (autoClick0 == true)
setInterval(clickIncrement, delay);
if (autoClick1 == true)
setInterval(clickIncrement, delay);
if (autoClick2 == true)
setInterval(clickIncrement, delay);
if (autoClick3 == true)
setInterval(clickIncrement, delay);
if (autoClick4 == true)
setInterval(clickIncrement, delay);
if (autoClick5 == true)
setInterval(clickIncrement, delay);
if (autoClick6 == true)
setInterval(clickIncrement, delay);
if (autoClick7 == true)
setInterval(clickIncrement, delay);
if (autoClick8 == true)
setInterval(clickIncrement, delay);
if (autoClick9 == true)
setInterval(clickIncrement, delay);
}
}
//code buffs
function clickIncrement() {
clicks++;
}
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds) {
break;
}
}
}
function display() {
document.getElementById('output').innerHTML = clicks;
}
<!doctype html>
<html>
<head>
<title>Cookie Clicker (WIP)</title>
<script>
//alert("Please click the cookie first as there is an issue with a segment of the code. Do not hack. It makes the game not fun.");
</script>
</head>
<body>
<input class="tooltip" id="clickMe" type="image" src="" onclick="doFunction();" />
<br>
<h2>Clicks:</h2>
<p id="output"></p>
<h2 align="center">Perks</h2>
<input title="Doubles Mouse Clicks
Cost:250" class="tooltip" id="Cursors" type="image" src="" width="150" onclick="doFunction();" />
<br>
<h2>Items</h2>
<input id="AutoClicker" title="Buy The Autoclicker For 250 Clicks! Clicks once every second!" type="image" src="https://www.macupdate.com/images/icons256/50547.png" width="150" onclick="doFunction();" />
<br>
<h2>Item Upgrades:</h2>
<input id="moreAutoC" type="image" src="" title="More Autoclickers! (MAX:11)" onclick="doFunction();" />
</body>
</html>
I thought it would instantly make the button disappear, and then that would be the end of it. I didn't know there would be other stuff involved. Note: all the src tags are removed due to them being VERY long.

If you wanna remove the button & not just hide it, without jquery, you'll use an event argument from the onclick handler;
event.target.parentNode.removeChild(event.target);

Make an id of button as example id="btn"
Put on click of the code below
And use following code
function hide(){
document.getElementById("btn").style.display = "none";
}

Your question is a little unclear and there is a lot of code, it is not obvious which button you want to delete. As such I'll give you a generic answer that hopefully you will be able to apply.
//Will just hide the button
document.getElementById("willHide").addEventListener("click", function(event){
event.target.style.display = "none";
});
//Will remove the button from the DOM entirely
document.getElementById("willDelete").addEventListener("click", function(event){
event.target.parentNode.removeChild(event.target);
});
//Will disable the button
document.getElementById("willDisable").addEventListener("click", function(event){
event.target.disabled = true;
});
<input type="button" id="willHide" value="I will be hidden" />
<input type="button" id="willDelete" value="I will be deleted" />
<input type="button" id="willDisable" value="I will be disabled" />

Related

What is the best way to deal with multiple else if statements to increase speed in Google Apps Script?

I have a function that is supposed to unhide certain columns, but only if other filters that relate to the columns are not in use. Because there are 4 other filters that it needs to check to see if they are in use (either 'true' or 'false'), there are 16 possibilities that the function needs to run through.
I've used else if statements to accomplish this and it does work, but it is incredibly slow. I was wondering if there is a more appropriate way to deal with all the possible options that is faster.
This is the code I currently have (sorry if I've shown too much, not sure how much I need to include):
function Unfilter(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var numCols = sheet.getRange(1,3).getValue(); //gets the number of columns to loop through
var xRow = sheet.getRange(1,5).getValue() + 16; //gets the target row to run the blank check on
// check filter statuses
var nameShow = sheet.getRange(1,1).getValue();
var statusShow = sheet.getRange(2,1).getValue();
var dateShow = sheet.getRange(3,1).getValue();
var evidenceShow = sheet.getRange(4,1).getValue();
//loop through all target columns and unhide all columns that are not filtered
for (var i=10; i<=numCols; i++) {
if (sheet.getRange(xRow,i).getValue() == "") {
var catType = sheet.getRange(16,i).getValue();
if (nameShow == true && statusShow == true && dateShow == true && evidenceShow == true) {
sheet.showColumns(i)
} else if (nameShow == false && statusShow == true && dateShow == true && evidenceShow == true) {
if(catType !== "Name") {
sheet.showColumns(i);
}
} else if (nameShow == false && statusShow == false && dateShow == true && evidenceShow == true){
if (catType == "Date" || catType == "Evidence") {
sheet.showColumns(i);
}
} else if (nameShow == false && statusShow == true && dateShow == false && evidenceShow == true) {
if (catType == "Status" || catType == "Evidence") {
sheet.showColumns(i);
}
} else if (nameShow == false && statusShow == true && dateShow == true & evidenceShow == false){
if (catType == "Status"|| catType == "Date") {
sheet.showColumns(i);
}
} else if (nameShow == false && statusShow == false && dateShow == false && evidenceShow == true){
if (catType == "Evidence") {
sheet.showColumns(i);
}
} else if (nameShow == false && statusShow == false && dateShow == true && evidenceShow == false){
if (catType == "Date") {
sheet.showColumns(i);
}
}
//...etc for all 9 remaining possibilities
}
}
}
Even if you can't speed up showColumns() function you can significantly accelerate your script if you will use getValue() or getValues() as few as it possible. For example here you invoke these functions more than 7 times on the same sheet with static data. It's far from best practices:
You could use getValues() just once to get all data from the sheet and analyze the array instead. It would be much faster. getValue() / getValues() are quite slow and intentionally limited functions.
For example:
var data = sheet.getRange(1,1,10,10).getValues(); // get the array
var numCols = data[0][2];
var xRow = data[0][4] + 16;
var nameShow = data[0][0];
var statusShow = data[1][0];
var dateShow = data[2][0];
var evidenceShow = data[3][0];
// etc
I think it will be about five seconds faster already.
And it will even more faster if you change getRange(xRow,i).getValue() to data[xRow-1][i-1] in the loop.

Else condition is not working in javascript

I'm a beginner to JavaScript. Can someone help me in this regard?
In the below code the logic for submit button doesn't work. _btn.addEventListener. Only the if part is getting executed, some issue with the else part condition. If the "if" condition gets satisfied then the alert is getting executed and not the conditions in else part even if the date and image is clicked.
<p align=center>
<input type="submit" value="submit" id="button">
</p>
<script type="text/javascript">
let _img = document.getElementById("img");
let _img1 = document.getElementById("img1");
let _img2 = document.getElementById("img2");
let _picker = document.getElementById("picker");
let _btn = document.getElementById("button");
let isImgClicked = false;
let isDatePicked = false;
/*let ImgClicked = '_img';
let ImgClicked1 = '_img1';
let ImgClicked2 = '_img2';
let DatePicked = '2019';
let DatePicked1 = '2020';*/
_img.addEventListener("click", function(){
isImgClicked = true;
ImgClicked=true
});
/*_img1.addEventListener("click", function(){
ImgClicked1 = true;
});
_img2.addEventListener("click", function(){
ImgClicked2 = true;
}); */
_picker.addEventListener("click", function(){
isDatePicked = true;
});
_btn.addEventListener("click", function(){
if(!isImgClicked || !isDatePicked)
{
alert("select the Year and Click the car image");
}
else
{
if((isImgClicked == "_img") && (isDatePicked == "DatePicked"))
{
window.location.replace("sample1.html");
}
else if((isImgClicked == "_img") && (isDatePicked == "DatePicked1"))
{
window.location.replace("sample2.html");
}
else
{
if((isImgClicked == "_img1") && (isDatePicked == "DatePicked"))
{
window.location.replace("sample3.html");
}
else if((isImgClicked == "_img1") && (isDatePicked == "DatePicked1"))
{
window.location.replace("sample4.html");
}
else
{
alert("!!!!");
}
}
}
});
</script>
Here you are assigning isImgClicked = true and ImgClicked = true
img.addEventListener("click", function(){
isImgClicked = true;
ImgClicked=true
});
But you are comparing this boolean with strings. Why?
if((isImgClicked == "_img1") && (isDatePicked == "DatePicked1"))
Fix it.
This is your function re-written in early-return style:
function() {
if(!isImgClicked || !isDatePicked) {
alert("select the Year and Click the car image");
return
}
if((isImgClicked == "_img") && (isDatePicked == "DatePicked")) {
window.location.replace("sample1.html");
return
}
if((isImgClicked == "_img") && (isDatePicked == "DatePicked1")) {
window.location.replace("sample2.html");
return
}
if((isImgClicked == "_img1") && (isDatePicked == "DatePicked")) {
window.location.replace("sample3.html");
return
}
if((isImgClicked == "_img1") && (isDatePicked == "DatePicked1")) {
window.location.replace("sample4.html");
return
}
alert("!!!!");
}
Which if statement are you having a problem with?

Uncaught TypeError: Cannot set property 'innerText' of null - possible syntax error

Working on a simple Tic Tac Toe game to better my JS but am stuck with this error msg. My "console.log("message");" returns what it should display " Game is ready. Player X turn." Its a single file with my script tags at the end just above my </body> tag. It's pretty basic. Any help would be appreciated.
var Display = function(displayElement) { // create 'class' to eliminate many 'innerText' usage
var display = displayElement; // and makes it easy to port to say android
function setText(message) {
console.log(message);
display.innerText = message;
}
return {setMessage: setText};
};
function isValid(button) { //if text within then not valid; if 0 then valid; any
return button.innerText.length == 0; //characters then invalid
}
function checkForWinner(squares, players, currentTurn) {
if (squares[0].innerText == players[currentTurn] &&
squares[1].innerText == players[currentTurn] &&
squares[2].innerText == players[currentTurn])
return true;
if (squares[3].innerText == players[currentTurn] &&
squares[4].innerText == players[currentTurn] &&
squares[5].innerText == players[currentTurn])
return true;
if (squares[6].innerText == players[currentTurn] &&
squares[7].innerText == players[currentTurn] &&
squares[8].innerText == players[currentTurn])
return true;
if (squares[0].innerText == players[currentTurn] &&
squares[3].innerText == players[currentTurn] &&
squares[6].innerText == players[currentTurn])
return true;
if (squares[1].innerText == players[currentTurn] &&
squares[4].innerText == players[currentTurn] &&
squares[7].innerText == players[currentTurn])
return true;
if (squares[2].innerText == players[currentTurn] &&
squares[5].innerText == players[currentTurn] &&
squares[8].innerText == players[currentTurn])
return true;
if (squares[0].innerText == players[currentTurn] &&
squares[4].innerText == players[currentTurn] &&
squares[8].innerText == players[currentTurn])
return true;
if (squares[2].innerText == players[currentTurn] &&
squares[4].innerText == players[currentTurn] &&
squares[6].innerText == players[currentTurn])
return true;
}
function setMark(button, mark) {
button.innerText = mark;
}
function main() {
var squares = document.querySelectorAll("#game button"); // returns array of all the buttons
var players = ["X", "O"]; // text displayed in the button
var currentTurn = 0; // either will be 0 or 1
var isGameOver = false; // boolean either T or F
var display = new Display(document.querySelector("gameActionDisplay")); //reference to msg
display.setMessage("Game is ready. Player " + players[currentTurn] + " turn.");
for (var i = 0, len = squares.length; i<len; i++) { //for loop to iterate through squares; set local var len
squares[i].addEventListener("click", function() {
if (isGameOver)
return;
if(!isValid(this)) {
display.setMessage("Invalid move bud!");
} else {
setMark(this, players[currentTurn]);
isGameOver = checkForWinner(squares, players, currentTurn);
//Game is over
//Game is draw
//Game is not over yet; play on
currentTurn++; // mod remainder toggles between 1 and 0
currentTurn = currentTurn % 2;
display.setMessage("Player " + players[currentTurn] + " move");
}
});
}
}
main();
<body>
<div id="game">
<div>
<button></button>
<button></button>
<button></button>
</div>
<div>
<button></button>
<button></button>
<button></button>
</div>
<div>
<button></button>
<button></button>
<button></button>
</div>
<div id="gameActionDisplay"></div>
</div>
</body>
you need you get your element by id
document.querySelector("#gameActionDisplay")
do the trick
Cheers

JS in page head section isn't excecuting

I have a script that handles a semi-complex contact form. The site is built using a website building platform called Duda and I think there may be timing issues as they load a bunch of scripts of their own. Anyway I'm getting a ReferenceError: price is not defined, error.
Price gets called onChange on inputs, for example:
<input value="Yes" name="dmform-9" type="radio" id="watch-me-hide" checked="checked" onchange="price()"/>
The script works sometimes, then other times not. Very frustrating. Does anyone know how to make sure that my functions get loaded in this situation?
Here is the whole script:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
var counter = 0;
$(document).ready(function() {
$("input[type="radio"]").click(function() {
alert("here");
var ids = ["#occupiedBy", "#nameOccupied", "#phoneOccupied", "#mobileOccupied", "#emailOccupied"];
if($(this).attr("id") == "watch-me-hide" || $(this).attr("id") == "watch-me-show") {
if ($(this).attr("id") == "watch-me-hide") {
$("#show-me").hide();
ids.forEach((id) => $(id).prop("required", false));
}
else if ($(this).attr("id") == "watch-me-show"){
$("#show-me").show();
ids.forEach((id) => $(id).prop("required", true));
}
else {
}
} else if($(this).attr("id") == "hideShowInDepth-hide" || $(this).attr("id") == "hideShowInDepth-show") {
if ($(this).attr("id") == "hideShowInDepth-hide") {
$("#moreRooms").hide();
price(null);
ids.forEach((id) => $(id).prop("required", false));
}
else if ($(this).attr("id") == "hideShowInDepth-show"){
$("#moreRooms").show();
price(null);
ids.forEach((id) => $(id).prop("required", true));
}
}
else{
}
});
};
function price() {
var priceIncrement = 70;
var minimumPrice = "189.00";
var basic = document.getElementById("hideShowInDepth-hide");
var advanced = document.getElementById("hideShowInDepth-show");
var ids = ["numberAdditionalRooms", "numberLaundries", "bedrooms", "numberLounges", "numberDining", "numberKitchens", "numberBathrooms", "numberHallways", "numberGarages"];
if ((basic.checked == true) && (advanced.checked == false)) {
/* Get number of rooms for basic inspection */
var e = document.getElementById("bedrooms");
var numberOfBedrooms = e.options[e.selectedIndex].value;
if (numberOfBedrooms == 0){
document.getElementById("totalPrice").textContent = "0.00";
}
else if ((numberOfBedrooms <= 3) && (numberOfBedrooms >= 1)){
document.getElementById("totalPrice").textContent = minimumPrice;
}
else if ((numberOfBedrooms <= 6) && (numberOfBedrooms >= 3)){
document.getElementById("totalPrice").textContent = "259.00";
}
else if (numberOfBedrooms > 6){
document.getElementById("totalPrice").textContent = "329.00";
}
else {
alert("Script error: Undefined number of bedrooms")
}
return false;
}
else if ((basic.checked == false) && (advanced.checked == true)) {
/* Get number of rooms for advanced inspection */
ids.forEach(logArrayElements);
if (counter == 0){
document.getElementById("totalPrice").textContent = "0.00";
}
else if (counter == 1){
document.getElementById("totalPrice").textContent = minimumPrice.toFixed(2);
;
}
else {
var money = ((counter * priceIncrement) + +minimumPrice) - +priceIncrement;
document.getElementById("totalPrice").textContent = money.toFixed(2);
}
counter=0;
return false;
}
else if ((basic.checked == false) && (advanced.checked == false)) {
alert("Script error: Neither checkbox is checked");
return false;
}
else if ((basic.checked == true) && (advanced.checked == true)) {
alert("Script error: Both checkboxes are checked");
return false;
}
else{
alert("Script error: Unknown error");
return false;
}
}
function logArrayElements(element, index, array) {
// alert("a[" + index + "] = " + element + " - " + value);
var e = document.getElementById(element);
var strUser = e.options[e.selectedIndex].value;
counter = +counter + +strUser;
}
</script>
watch-me-hide and watch-me-show are radio buttons that when changed they hide or show another section of the contact form to fill out, and make the inputs required or not.
hideShowInDepth-hide and hideShowInDepth-show are the same, but for another div section.
the price function updates the text in a span to reflect a new price when an input value has changed.
price() gets called onchange of dropdowns and radio buttons.
Any help appreciated.

NaN error equation

In this javascript code I try to solve a quadratic equation, I've been working on it for an hour and this should tell me the value of a, b and c where y is a(x^2). I'm a relative javascript beginner and would love some help. Why are the values of a, b and c not numbers? The variable names are in italian, in english and in something else(Not even I know what), but I commented what they are. That's one of my bad traits as a student that usually works alone, sorry if it's not easy to understand.
<script type="text/javascript">
var equa=prompt("Scrivi l'equazione senza spazi usando x come incognita e y come x^2");
var a = 0.0; b = 0.0; c = 0.0;//ax2+bx+c
var prima = true; //before or after equal?
var ope = 1;//1add 2sub 3mul 4div
var lasto = 0.0;//last number, used for div and mul
var lastos = 3; //1a2b3c
var errore=0;//is something messed up?
for(var i = 0; i < equa.length;i=i){
if(equa.charAt(i)=='='){
prima = false;
i++;
}else if(equa.charAt(i)=='+'){
ope=1;
i++;
}else if(equa.charAt(i)=='-'){
ope=2;
i++;
}else if(equa.charAt(i)=='*'){
ope=3;
i++;
}else if(equa.charAt(i)=='/'){
ope=4;
i++;
}else{
var nume = "";//Current number in string form
while(i<equa.length && equa.charAt(i)>'0' && equa.charAt(i)<'9'){
nume+=equa.charAt(i);
i++;
}
var lasnum = 0.0;//current number in float form
var lasval = 3; //1a2b3c
if(equa.charAt(i) == 'x'){
lasnum=parseFloat(nume);
lasval = 2;
}else if(equa.charAt(i) == 'y'){
lasnum=parseFloat(nume);
lasval = 1;
}else{
lasnum = parseFloat(nume);
lasval=3;
}
i++;
if( (ope == 1 || ope == 2) && !(equa.charAt(i) =='*' || equa.charAt(i) == '/')){
if(lasval == 1){
if(prima) a+=lasnum;
else a-=lasnum;
}
else if(lasval == 2){
if(prima) b+=lasnum;
else b-=lasnum;
}
else {
if(prima) c+=lasnum;
else c-=lasnum;
}
}else if( (ope==1 || ope == 2) && (equa.charAt(i) =='*' || equa.charAt(i) == '/')){
//zitto e fermo
lasto=lasnum;
lastos=lasval;
}else if( (ope==3||ope == 4)){
if(ope==3){
if(lastos==3){
lasnum*=lasto;
}
if(lastos == 2){
if(lastval==3){
lasnum*=lasto;
lastval=2;
}
if(lastval==2){
lasnum*=lasto;
lastval=1;
}
if(lastval==1){
errore=1;
}
}
if(lastos == 1){
if(lastval == 3){
lasnum*=lasto;
lastval=1;
}else{
errore=1;
}
}
}
if(ope == 4){
if(lastos == 1){
if(lastval==3){
lasnum/=lasto;
lastval=1;
}
if(lastval==2){
lasnum/=lasto;
lastval=2;
}
if(lastval==1){
lasnum/=lasto;
lastval=3;
}
}
if(lastos == 2){
if(lastval==1){
errore=1;
}
if(lastval==2){
lasnum/=lasto;
lastval=3;
}
if(lastval==3){
lasnum/=lasto;
lastval=2;
}
}
if(lastos == 3){
if(lastval==3){
lasnum/=lasto;
}else{
errore=1;
}
}
}
if(equa.charAt(i) =='*' || equa.charAt(i) == '/'){
lasto=lasnum;
lasto=lasval;
}else{
if(lasval == 1){
if(prima) a+=lasnum;
else a-=lasnum;
}
else if(lasval == 2){
if(prima) b+=lasnum;
else b-=lasnum;
}
else {
if(prima) c+=lasnum;
else c-=lasnum;
}
lasto=0;
lastos=3;
}
}
}
}
if(errore==0){
alert("a ="+a+" b="+b+" c="+c);
}else{
alert("AOOOOOOo");
}
</script>
Since the expected input should be in the format "15y+3x+5=20" for example, then this is a simple regular expression:
var equa = prompt("Scrivi l'equazione senza spazi usando x come incognita e y come x^2");
var regex = /^([0-9.]+)y\+([0-9.]+)x\+([0-9.]+)=([0-9.]+)$/;
var matches = regex.exec(equa);
if (matches) {
var a = parseFloat(matches[1]);
var b = parseFloat(matches[2]);
var c = parseFloat(matches[3]) - parseFloat(matches[4]);
var discriminant = b*b - 4*a*c;
if (discriminant < 0) {
alert('No real solutions');
}
else {
var root = Math.sqrt(discriminant);
alert('Root: ' + ((-b + root)/(2*a)) + ', ' + ((-b - root)/(2*a)));
}
}
else {
alert("AOOOOOOo");
}

Categories

Resources