Comment utiliser les deux code javascript [Résolu]

Messages postés
481
Date d'inscription
lundi 24 août 2009
Dernière intervention
31 janvier 2019
- - Dernière réponse : msi79
Messages postés
481
Date d'inscription
lundi 24 août 2009
Dernière intervention
31 janvier 2019
- 31 janv. 2019 à 14:19
Bonjour,
je dois utiliser ces deux codes javascript mais les deux veulent pas cohabiter.
je commente un le deuxième fonctionne bien .vis versa

le premier:
<script type="text/javascript">
$(document).ready(function(){
const buttons = document.querySelectorAll("button");
const currCalc = document.querySelector("#calculation");
const currInput = document.getElementById("inpresult");

const checkRE = /(\d|\))$/; // RegExp matches, if last character of string is number or ')'
const re1 = /(0+)$/g; // RegExp matches all 0 at the en of a string
const re2 = /\.$/; // RegExp matches dot at the end
let calc = [];
let input = [];
let res;
let intRes = false;
let disCalc = [];
let disResult;
let str;

function onNumber(el) {
  // print number, unless user tries to input multiple zeros in the beginning & input-display is full
  if (
    ((el === "0" && (input[0] !== "0" || input.includes("."))) || el !== "0") &&
    input.length < 20
  ) {
    input[0] === "0" && !input.includes(".") && el !== "0"
      ? (input = [])
      : input;
    input.push(el);
    currInput.value = `${input.join("")}`;
  }
}

function onClear(el) {
  if (el === "c") {
    // clear all
    calc = [];
    input = [];
    intRes = false;
    res = undefined;
    displayCalculation(calc, false);
    currInput.value = "";
    // console.log(calc, input, negative, intRes, res);
  } else if (el === "ce") {
    // clear entry (input)
    input = [];
    currInput.value = "";
  } else if (el === "del" && input.length > 0) {
    // delete last input character
    input.splice(-1);
    currInput.value = `${input.join("")}`;
  }
}

function onNeg() {
  // toggle between ± only if input is not 0
  if (input.length !== 0 && eval(input.join("")) !== 0) {
    let negative;
    input[0] === "-" ? (negative = true) : (negative = false);
    // if-condition for display-reasons
    if ((!negative && input.length < 20) || negative) {
      negative ? input.shift() : input.unshift("-");
      currInput.value = `${input.join("")}`;
    }
  }
}

function onDot() {
  // print dot, unless input is already a decimal & condition for display-reasons
  if (!input.includes(".") && input.length < 20) {
    input.length > 0 ? input.push(".") : input.push("0", ".");
    currInput.value = `${input.join("")}`;
  }
}

function onOperator(operator) {
  // eliminate redundant 0 from input end(re1), and dot if necessary(re2)
  input.join("").includes(".") && re1.test(input.join(""))
    ? (input = input
        .join("")
        .replace(re1, "")
        .replace(re2, "")
        .split(""))
    : input;
  // run only, if input ends with checkRE OR
  // calc isn't empty and ends with checkRE =>  || (calc.length > 0 && checkRE.test(calc))
  if (checkRE.test(input)) {
    // input in calc, dependend if input is negative or not ; then reset input
    eval(input.join("")) < 0
      ? calc.push(`(${input.join("")})`)
      : calc.push(`${input.join("")}`);
    input = [];
    // operator in calc
    calc.push(operator);
    // display current input and calc
    displayCalculation(calc, false);
    currInput.value = `${input.join("")}`;
  }
}

function onEqual() {
  // eliminate redundant 0 from input end(re1), and dot if necessary(re2)
  input.join("").includes(".") && re1.test(input.join(""))
    ? input = input
        .join("")
        .replace(re1, "")
        .replace(re2, "")
        .split("")
    : input;
  // run only if input ends with checkRE
  if (checkRE.test(input)) {
    // input in calc, dependend if input is negative or not ; then reset input
    eval(input.join("")) < 0
      ? calc.push(`(${input.join("")})`)
      : calc.push(`${input.join("")}`);
    input = [];
    // resolve calculation, only if calc ends with checkRE
    if (checkRE.test(calc)) {
      res = eval(calc.join(""));
      // display calculation and result
      displayCalculation(calc, true);
      displayResult(res);
    }
  }
}

function followUp(withIntRes) {
  if (withIntRes) {
    input = res.toString().split("");
  }
  calc = [];
  res = undefined;
  intRes = undefined;
  currCalc.innerHTML = `${calc}`;
}

function displayResult(res) {
  if (res > 99999999999999999999 || res < -9999999999999999999) {
    disResult = "error";
    calc = [];
    input = [];
    res = [];
    intRes = false;
    displayCalculation([], false);
  } else {
    disResult = res;
    intRes = true;
  }
  currInput.value = `${disResult}`;
}

function displayCalculation(calcArr, final) {
  final ? calcArr.push("=") : calcArr;
  str = calcArr.join("");
  if (str.length > 30) {
    str = str.substr(-29);
    disCalc = `…${str}`;
  } else {
    disCalc = str;
  }
  currCalc.innerHTML = disCalc;
}

function calculator() {
  if (this.className === "number") {
    if (intRes) {
      followUp(false);
    }
    onNumber(this.id);
  } else if (this.className === "clear") {
    onClear(this.id);
  } else if (this.id === "negative") {
    if (intRes) {
      followUp(true);
    }
    onNeg();
  } else if (this.className === "dot") {
    if (intRes) {
      followUp(false);
    }
    onDot();
  } else if (this.className === "operator") {
    if (intRes) {
      followUp(true);
    }
    onOperator(this.id);
  } else if (this.className === "equal") {
    onEqual();
  }
}

buttons.forEach(button => button.addEventListener("click", calculator));
});

</script>



le deuxième

<script type="text/javascript">
// Get all the keys from document
var keys = document.querySelectorAll('#calculator span');
var operators = ['+', '-', 'x', '÷'];
var decimalAdded = false;
// Add onclick event to all the keys and perform operations
		
for(var i = 0; i < keys.length; i++) {
	keys[i].onclick = function(e) {
		// Get the input and button values
		var input = document.getElementById("inpresult");
		var inputVal = input.value;
		var btnVal = this.innerHTML
		
		// Now, just append the key values (btnValue) to the input string and finally use javascript's eval function to get the result
		// If clear key is pressed, erase everything
		if(btnVal == 'C') {
			input.value = '';
			decimalAdded = false;
		}
		
		// If eval key is pressed, calculate and display the result
		else if(btnVal == '=') {
			var equation = inputVal;
			var lastChar = equation[equation.length - 1];
			
			// Replace all instances of x and ÷ with * and / respectively. This can be done easily using regex and the 'g' tag which will replace all instances of the matched character/substring
			equation = equation.replace(/x/g, '*').replace(/÷/g, '/');
			
			// Final thing left to do is checking the last character of the equation. If it's an operator or a decimal, remove it
			if(operators.indexOf(lastChar) > -1 || lastChar == '.')
				equation = equation.replace(/.$/, '');
			
			if(equation)
				input.value = eval(equation);
				
			decimalAdded = false;
		}
		
		// Basic functionality of the calculator is complete. But there are some problems like 
		// 1. No two operators should be added consecutively.
		// 2. The equation shouldn't start from an operator except minus
		// 3. not more than 1 decimal should be there in a number
		
		// We'll fix these issues using some simple checks
		
		// indexOf works only in IE9+
		else if(operators.indexOf(btnVal) > -1) {
			// Operator is clicked
			// Get the last character from the equation
			var lastChar = inputVal[inputVal.length - 1];
			
			// Only add operator if input is not empty and there is no operator at the last
			if(inputVal != '' && operators.indexOf(lastChar) == -1) 
				input.value += btnVal;
			
			// Allow minus if the string is empty
			else if(inputVal == '' && btnVal == '-') 
				input.value += btnVal;
			
			// Replace the last operator (if exists) with the newly pressed operator
			if(operators.indexOf(lastChar) > -1 && inputVal.length > 1) {
				// Here, '.' matches any character while $ denotes the end of string, so anything (will be an operator in this case) at the end of string will get replaced by new operator
				input.value = inputVal.replace(/.$/, btnVal);
			}
			
			decimalAdded =false;
		}
		
		// Now only the decimal problem is left. We can solve it easily using a flag 'decimalAdded' which we'll set once the decimal is added and prevent more decimals to be added once it's set. It will be reset when an operator, eval or clear key is pressed.input.innerHTML
		else if(btnVal == '.') {
			if(!decimalAdded) {
				input.value += btnVal;
				decimalAdded = true;
			}
		}
		
		// if any other key is pressed, just append it
		else {
			input.value += btnVal;
		}
		
		// prevent page jumps
		e.preventDefault();
	} 
}
</script>
Afficher la suite 

Votre réponse

1 réponse

Messages postés
24536
Date d'inscription
mercredi 22 octobre 2003
Statut
Modérateur
Dernière intervention
16 février 2019
362
0
Merci
Il faudrait que tu nous montres comment tu "mets" ces deux codes ensemble.

Il faudrait également regarder dans la console de ton navigateur si il n'y a pas des erreurs... (lorsque tu mets les deux codes ensemble bien entendu...)
=> Colle nous une capture écran de la console histoire qu'on se fasse notre propre avis...

msi79
Messages postés
481
Date d'inscription
lundi 24 août 2009
Dernière intervention
31 janvier 2019
-
quand je met en commentaire
<script src="js/template/code.jquery.jquery-1.11.1.min.js"></script>
, les modals fonctionnent plus, les liens fonctionnent plus.

voici placerModalPourcentage.js
let  qteInput = document.getElementById('inpresult') ;
let idInput = document.getElementById('cache') ;
//const links = document.getElementById('tableau').getElementsByTagName('a') ;

function placer(arg){
 qteInput.setAttribute('value',arg.textContent) ;
 idInput.setAttribute('value',arg.id) ;
}


la console affiche
jordane45
Messages postés
24536
Date d'inscription
mercredi 22 octobre 2003
Statut
Modérateur
Dernière intervention
16 février 2019
362 -
Encore des trucs bizarres .. que tu n'as pas du voir (ni même cherché à comprendre)

Par exemple.. tu sembles charger deux fois (et deux versions différentes de jquery)
    <script src="js/template/code.jquery.jquery-1.11.1.min.js"></script>

<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.1.min.js" > </script> 


Une seule (la plus récente) suffit.

Dans le fichier placerModalPourcentage.js
Modifie le comme ceci :
//const links = document.getElementById('tableau').getElementsByTagName('a') ;
function placer(arg){
 var idInput = document.getElementById('cache') ;
 var qteInput = document.getElementById('inpresult') ;
 qteInput.setAttribute('value',arg.textContent) ;
 idInput.setAttribute('value',arg.id) ;
}


Ensuite, dans les erreurs affichées dans la console, ça parle de "placer2"
Mais je ne trouve nul-part dans le code que tu nous montres référence à cette fonction (appellées via un onclick visiblement)...
Tu peux éventuellement cliquer sur le "nom du fichier" indiqué dans la console en regard du message d'erreur... ça devrait t'afficher la ligne de code concernée.

Tu peux déjà commencer par corriger ça.

Ensuite,
Dis toi, lorsque tu essayes de regrouper plusieurs codes ensembles :
1- Ne pas utiliser les mêmes noms de fonctions
2 - Ne pas utiliser les mêmes noms de variables à portée "globales". (si tu les déclares à l'intérieur des fonctions cela ne pose pas de souci)


Et si malgré ces ajustements les soucis persistes, recolle nous les éventuels nouveaux messages d'erreurs de la console et donne nous le code de chaque fichier js (en pensant à nous spécifier le nom de chacun )
<script type="text/javascript" src="js/placerModal.js"></script>
<script type="text/javascript" src="js/ajaxModal.js"></script>
<script type="text/javascript" src="js/placerModalPourcentage.js"></script>
<script type="text/javascript" src="js/ajaxModalPourcentage.js"></script>             
<script src="js/js.js" ></script>
msi79
Messages postés
481
Date d'inscription
lundi 24 août 2009
Dernière intervention
31 janvier 2019
-
Bonjour à vous .
il a y une avancée mais quand je sais le chiffres de la calculette, ca ne s'affiche pas dans le input .

partie concernée :
    <style type="text/css">
        /* Basic reset */
* {
	margin: 0;
	padding: 0;
	box-sizing: border-box;
	
	/* Better text styling */
	font: bold 14px Arial, sans-serif;
}

/* Finally adding some IE9 fallbacks for gradients to finish things up */

/* A nice BG gradient */
html {
	height: 100%;
	background: white;
	background: radial-gradient(circle, #fff 20%, #ccc);
	background-size: cover;
}

/* Using box shadows to create 3D effects */
#calculator {
	width: 325px;
	height: auto;
	
	margin: 100px auto;
	padding: 20px 20px 9px;
	
	background: #9dd2ea;
	background: linear-gradient(#9dd2ea, #8bceec);
	border-radius: 3px;
	box-shadow: 0px 4px #009de4, 0px 10px 15px rgba(0, 0, 0, 0.2);
}

/* Top portion */
.top span.clear {
	float: left;
}

/* Inset shadow on the screen to create indent */
.top .screen {
	height: 40px;
	width: 212px;
	
	float: right;
	
	padding: 0 10px;
	
	background: rgba(0, 0, 0, 0.2);
	border-radius: 3px;
	box-shadow: inset 0px 4px rgba(0, 0, 0, 0.2);
	
	/* Typography */
	font-size: 17px;
	line-height: 40px;
	color: white;
	text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.2);
	text-align: right;
	letter-spacing: 1px;
}

/* Clear floats */
.keys, .top {overflow: hidden;}

/* Applying same to the keys */
.keys span, .top span.clear {
	float: left;
	position: relative;
	top: 0;
	
	cursor: pointer;
	
	width: 66px;
	height: 36px;
	
	background: white;
	border-radius: 3px;
	box-shadow: 0px 4px rgba(0, 0, 0, 0.2);
	
	margin: 0 7px 11px 0;
	
	color: #888;
	line-height: 36px;
	text-align: center;
	
	/* prevent selection of text inside keys */
	user-select: none;
	
	/* Smoothing out hover and active states using css3 transitions */
	transition: all 0.2s ease;
}

/* Remove right margins from operator keys */
/* style different type of keys (operators/evaluate/clear) differently */
.keys span.operator {
	background: #FFF0F5;
	margin-right: 0;
}

.keys span.eval {
	background: #f1ff92;
	box-shadow: 0px 4px #9da853;
	color: #888e5f;
}

.top span.clear {
	background: #ff9fa8;
	box-shadow: 0px 4px #ff7c87;
	color: white;
}

/* Some hover effects */
.keys span:hover {
	background: #9c89f6;
	box-shadow: 0px 4px #6b54d3;
	color: white;
}

.keys span.eval:hover {
	background: #abb850;
	box-shadow: 0px 4px #717a33;
	color: #ffffff;
}

.top span.clear:hover {
	background: #f68991;
	box-shadow: 0px 4px #d3545d;
	color: white;
}

/* Simulating "pressed" effect on active state of the keys by removing the box-shadow and moving the keys down a bit */
.keys span:active {
	box-shadow: 0px 0px #6b54d3;
	top: 4px;
}

.keys span.eval:active {
	box-shadow: 0px 0px #717a33;
	top: 4px;
}

.top span.clear:active {
	top: 4px;
	box-shadow: 0px 0px #d3545d;
}
    </style>
<div id="calculator">
	<!-- Screen and clear key -->
	<div class="top">
		<span class="clear">C</span>
		<div class="screen">
          <input type="text" name="qte" id="inpresult2" value=""  style="font-size: 36px; text-align: left; color: red; font-weight: bold;" >
          <input id="cache2" hidden type="text" name="id" value="">
             <input id="clef" hidden type="text" name="clef" value="<?php echo  $_GET['clef']; ?>">
        </div>
	</div>
 
	<div class="keys">
		<!-- operators and other keys -->
		<span>7</span>
		<span>8</span>
		<span>9</span>
		<span>4</span>
		<span>5</span>
		<span>6</span>
		<span>1</span>
		<span>2</span>
		<span>3</span>
		<span>0</span>
	</div>
    
       <hr class="mb-4">
<div class="row">
   <div class="col-md-3"></div>
      <div class="col-md-6">
        <input onclick="inserer2()" type="button" name="valider"  class="btn btn-success btn-block flatbtn" value="Appliquez un pourcentage">

  </div>
<div class="col-md-3"></div>
</div>


</div>
<script type="text/javascript">
// Get all the keys from document
var keys = document.querySelectorAll('#calculator span');
var operators = ['+', '-', 'x', '÷'];
var decimalAdded = false;
// Add onclick event to all the keys and perform operations
		
for(var i = 0; i < keys.length; i++) {
	keys[i].onclick = function(e) {
		// Get the input and button values
		var input = document.getElementById("inpresult");
		var inputVal = input.value;
		var btnVal = this.innerHTML
		
		// Now, just append the key values (btnValue) to the input string and finally use javascript's eval function to get the result
		// If clear key is pressed, erase everything
		if(btnVal == 'C') {
			input.value = '';
			decimalAdded = false;
		}
		
		// If eval key is pressed, calculate and display the result
		else if(btnVal == '=') {
			var equation = inputVal;
			var lastChar = equation[equation.length - 1];
			
			// Replace all instances of x and ÷ with * and / respectively. This can be done easily using regex and the 'g' tag which will replace all instances of the matched character/substring
			equation = equation.replace(/x/g, '*').replace(/÷/g, '/');
			
			// Final thing left to do is checking the last character of the equation. If it's an operator or a decimal, remove it
			if(operators.indexOf(lastChar) > -1 || lastChar == '.')
				equation = equation.replace(/.$/, '');
			
			if(equation)
				input.value = eval(equation);
				
			decimalAdded = false;
		}
		
		// Basic functionality of the calculator is complete. But there are some problems like 
		// 1. No two operators should be added consecutively.
		// 2. The equation shouldn't start from an operator except minus
		// 3. not more than 1 decimal should be there in a number
		
		// We'll fix these issues using some simple checks
		
		// indexOf works only in IE9+
		else if(operators.indexOf(btnVal) > -1) {
			// Operator is clicked
			// Get the last character from the equation
			var lastChar = inputVal[inputVal.length - 1];
			
			// Only add operator if input is not empty and there is no operator at the last
			if(inputVal != '' && operators.indexOf(lastChar) == -1) 
				input.value += btnVal;
			
			// Allow minus if the string is empty
			else if(inputVal == '' && btnVal == '-') 
				input.value += btnVal;
			
			// Replace the last operator (if exists) with the newly pressed operator
			if(operators.indexOf(lastChar) > -1 && inputVal.length > 1) {
				// Here, '.' matches any character while $ denotes the end of string, so anything (will be an operator in this case) at the end of string will get replaced by new operator
				input.value = inputVal.replace(/.$/, btnVal);
			}
			
			decimalAdded =false;
		}
		
		// Now only the decimal problem is left. We can solve it easily using a flag 'decimalAdded' which we'll set once the decimal is added and prevent more decimals to be added once it's set. It will be reset when an operator, eval or clear key is pressed.input.innerHTML
		else if(btnVal == '.') {
			if(!decimalAdded) {
				input.value += btnVal;
				decimalAdded = true;
			}
		}
		
		// if any other key is pressed, just append it
		else {
			input.value += btnVal;
		}
		
		// prevent page jumps
		e.preventDefault();
	} 
}
</script>
jordane45
Messages postés
24536
Date d'inscription
mercredi 22 octobre 2003
Statut
Modérateur
Dernière intervention
16 février 2019
362 -
Je t'ai indiqué de regarder dans la console (mais tu sembles avoir du mal à comprendre ce qu'on te dit... )
par ce que... ben..... oui... il y a bien un message d'erreur qui dit que la variable input est inconnue
à la ligne
var inputVal = input.value;


Normal... vu que la ligne
var input = document.getElementById("inpresult");

semble avoir mystèrieusement disparue.....
msi79
Messages postés
481
Date d'inscription
lundi 24 août 2009
Dernière intervention
31 janvier 2019
-
pardon il fallait juste ça
var input = document.getElementById("inpresult2");


merci pour tout ça passe
Commenter la réponse de jordane45

Vous n'êtes pas encore membre ?

inscrivez-vous, c'est gratuit et ça prend moins d'une minute !

Les membres obtiennent plus de réponses que les utilisateurs anonymes.

Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.

Le fait d'être membre vous permet d'avoir des options supplémentaires.