I want to create a script that when I write a string to check if this string is a number or no if it isn't a number it should give me the input dialogue again, the is the code I tried:
<script>
var nombre;
nombre = parseInt(prompt("Donnez un nombre entre 0 et 999: "));
var nombreIsInt = false;
while(!nombreIsInt)
{
if(isNaN(nombre))
prompt("Svp Saisie un nombre entre 0 et 999: ");
else
nombreIsInt = true;
}
</script>
The problem is that when I write a number it gives me the input dialogue again.
Try a do-while loop:
do {
var nombre = parseInt(prompt("Donnez un nombre entre 0 et 999: "));
var nombreIsInt = !isNaN(nombre);
} while (!nombreIsInt);
You need to assign the prompt to nombre. Here:
<script>
var nombre;
nombre = parseInt(prompt("Donnez un nombre entre 0 et 999: "));
var nombreIsInt = false;
while(!nombreIsInt)
{
if(isNaN(nombre))
nombre = prompt("Svp Saisie un nombre entre 0 et 999: "); // the problem is here
else
nombreIsInt = true;
}
</script>
Related
I'm making a project that receives the user input, saves it in an array, and then checks if the words are vowels or consonants, everything's fine here, however, i can't get the consonant count correctly.
I discovered two things,
First, if i try to count the consonants while checking each character with the vowels, it gives me the double or triple characters.
Second, i don't know how to count only one time each consonant.
Here's my code:
<!DOCTYPE html>
<html lang="ca">
<head>
<meta charset="utf-8" />
<title>DAW0612-Pràctica 08</title>
<link href="imatges/favicon.ico" type="image/ico" rel="Shortcut Icon"/>
<link href="codi/estil.css" rel="stylesheet" type="text/css" />
</head>
<body>
<header>A l'inrevés</header>
<br />
<div id="missatge"></div>
<h3 id="paraula"></h3>
<h4 id="caracters"></h4>
<p id="consonants"></p>
<p id="vocals"></p>
<p id="espais"></p>
<p id="especials"></p>
<script>
/************ COMENÇEU AQUÍ EL VOSTRE CODI ***************************************************************/
//variables
var frase =[10];
var fraseinreves=[10];
var dump;
var vocales=["a","e","i","o","u"];
var espais = 0;
var j=0;
var vocals = 0;
var consonants = 0;
//programa
frase = window.prompt("Dame una frase cualquiera");
lfrase = frase.length;
for (let i = frase.length -1; i >=0; i--){
//guardamos la frase al reves dentro de la nueva array
fraseinreves[j]=frase[i];
// resultado += frase[i];
if (frase[i] == " "){
espais++;
}
//incrementamos el contador de la array nueva
j++;
}
for (let i = 0; i < frase.length; i ++){
//guardamos los caracteres uno por uno del array a la constante char
const char = frase[i];
//window.alert(char);
window.alert(char);
//creamos un loop para recorrer la array que contiene las vocales
for (let j = 0; j < vocales.length; j++){
//SI EL CONTENIDO DE CHAR, ES IGUAL A ALGUNA VOCAL (ESTAS SE RECORREN EN EL SEGUNDO LOOP), entonces:
if(char == vocales[j]){
window.alert(char);
vocals++;
}
}
//contador para las consonantes.
}
/************ NO TOQUEU EL SEGÜENT CODI ***************************************************************/
document.getElementById("missatge").innerHTML = fraseinreves;
document.getElementById("paraula").innerHTML = "Paraula o frase original: <span>" + frase + "</span>";
document.getElementById("caracters").innerHTML = "Nombre de caràcters: " + lfrase;
document.getElementById("consonants").innerHTML = "Consonants: " + consonants;
document.getElementById("vocals").innerHTML = "Vocals: " + vocals;
document.getElementById("espais").innerHTML = "Espais en blanc: " + espais;
document.getElementById("especials").innerHTML = "Lletres ñ o ç: " + especial;
</script>
<noscript>
El seu navegador no accepta Javascript, si us plau actualitzis a una versió mes moderna.
</noscript>
<br />
<footer>
2016 Departament d'Informàtica - INS LA PINEDA - BADALONA<span>DAW M06-Desenvolupament Web en Entorn Client</span>
</footer>
</body>
</html>
Basically i don't want to use any function like includes() because i want to improve my thinking, and i want to know what i did bad.
Thanks.
this will check if the char is not a vowel. if the char is not a vowel, but is still a letter (checked with regex), then it will add to the consonants counter. not sure how to do with without regex or at least an array of all consonants, because otherwise you might start counting spaces and periods and the like.
//creamos un loop para recorrer la array que contiene las vocales
for (let j = 0; j < vocales.length; j++){
//SI EL CONTENIDO DE CHAR, ES IGUAL A ALGUNA VOCAL (ESTAS SE RECORREN EN EL SEGUNDO LOOP), entonces:
let vocalesFound = false;
if(char == vocales[j]){
window.alert(char);
vocals++;
vocalesFound = true;
}
}
//contador para las consonantes.
if ( !vocalesFound && char.match( /[A-Za-z]/ ) ) consonants++;
}
I need to click two times on my button to validate my form,
I have a event listener like this :
btnCartSend.addEventListener('click', function(){
checkInput();
window.location="confirm.html "
})
Then it call
function checkInput(){
if (fristName.length == 0){
alert("test 1");
}else if(lastName.length == 0){
alert("test 2");
}else if(address.length == 0){
alert("test 3");
}else if(zip.length != 5){
alert("test 4");
}else if(city.length == 0){
alert("test 5");
}else if(email.length == 0){
alert("test 6");
}else {
console.log('send to api');
sendToApi();
}
}
I put the whole project on my github and here you have the cart file with both functions and others: https://github.com/lliolla/P5-onorico/blob/master/frontend/js/cart.js
I have cloned your project and find some omissions that you are using shoppingCart.length everywhere while shoppingCart is having null initially, so wherever you are using the length or any other property, please first check if that variable is null or not.
After fixing all this, I have run the code and it is validating the form with a single click.
Check your code or replace the cart.js with the below code I have corrected at some places.
//déclaration des variables
let shoppingCart = JSON.parse(localStorage.getItem('shoppingCart')); // recuperer le panier convertit en javascript
console.log('shoppingCart',shoppingCart)
let orderInfos = JSON.parse(localStorage.getItem('orderInfos')); // recuperer le retour API convertit en javascript
console.log('orderInfos',orderInfos)
let form =document.getElementById("form") // formulaire
let btnCartSend =document.getElementById("btnCartSend") // bouton envoi
let tableCartRows = document.getElementById("tableCartRows")// corps du tableau
let tableFoot = document.getElementById("tableFoot")//pied du tableau
let table=document.getElementById("table") // tableau entier
let tableTitle=document.getElementById("tableTitle") // h2
let orderModal = document.getElementById('orderModal')// modal de confirmation de commande
//variables info clients a vérifier
let fristName = document.getElementById("inputFristName").value;
let lastName= document.getElementById("inputLastName").value;
let address = document.getElementById("inputAddress").value;
let zip = document.getElementById("inputZip").value;
let city = document.getElementById("inputCity").value;
let email = document.getElementById("InputMail").value;
function showCart(){
//au chargement de la page génerer dynamiquement le panier si shoppingcart est plein sinon on affiche panier vide avec bouton de retour a teddiesHome.html
if (shoppingCart && shoppingCart.length <= 0) {
// on masque le cart le formulaire et son bouton et on affiche un retour à la page des produits
tableTitle.style.display = "none";
tableCart.style.display = "none";
form.style.display = "none";
btnCartSend.style.display = "none";
let h2 = document.createElement("h2");
table.appendChild(h2);
h2.textContent ="Votre panier est vide ";
let p = document.createElement("p");
table.appendChild(p);
p.textContent ="Faites un petit tour dans nos boutiques et laissez-vous tenter";
var a = document.createElement("a");
p.appendChild(a);
a.setAttribute('class','btn btn-secondary btn-lg btn-block');
a.setAttribute('href','teddiesHome.html');
a.setAttribute('role','button');
a.textContent = "Continuer mes achats";
}else{
totalCartPrice ();// total price du panier
//verifier si il y a des doublons
if(shoppingCart) {
createTableCart(); //sinon afficher le panie
}
}
}
showCart()
function delateItemCart(index){
//supprimer un teddy en fonction de son index dans teddyArray
console.log ("suprimer le teddy dans shopping cart",index, shoppingCart[index])
shoppingCart.splice(index,1)
console.log ("suprimer le teddy dans shopping cart", shoppingCart)
//vide le localstorage
localStorage.clear();
//mettre à jour le local storage avec nouveau panier
localStorage.setItem('shoppingCart',JSON.stringify(shoppingCart) ) ;
totalCartPrice ();
// recharger la page
document.location.reload();
//}
}
// on fait une boucle pour acceder à tous les boutons supprimer
let bntDelated = document.querySelectorAll('.bntDelated') //boutons supprimer
for (i=0 ;i<bntDelated.length ; i++ ){
console.log("bntDelated", bntDelated[i])
bntDelated[i].addEventListener("click", function(){ // au clic sur sup on suprimer le teddy coorepondant dans le shopping cart
let index = Array.from(bntDelated).indexOf(event.target) ;
console.log("click pour suprimer envoi l'index, ",index)
delateItemCart(index);
})
}
// au clic sur le btn envoyer la commande
btnCartSend.addEventListener('click', function(){
checkInput();// on verifie le format des input
sendToApi(); // on envoi les donnees a l'api et on recuperer le num de commande
//si tout est ok on affiche le modal avec un num de commande et le prix total
window.location="confirm.html "
})
function totalCartPrice (){
if(shoppingCart) {
let totalCart = 0;
for ( let i=0; i<shoppingCart.length ; i++ ){
let cartQte = shoppingCart[i].qte;
let cartprice = shoppingCart[i].price;
totalCart += cartQte * cartprice
localStorage.setItem('totalCart',JSON.stringify(totalCart) );
}
}
}
function createTableCart(){// on affiche dynamiquement le panier sous forme de tableau
// on boucle le shopping cart pour afficher une ligne par teddy
for ( let i=0; i<shoppingCart.length ; i++ ){
let tr1 = document.createElement("tr");
tableCartRows.appendChild(tr1);
let th7 = document.createElement("th");
tr1.appendChild(th7);
th7.setAttribute('scoop','row');
th7.textContent="counter ligne";
let td = document.createElement("td");
tr1.appendChild(td);
let teddyname =shoppingCart[i].name ;
td.textContent= teddyname;
td.setAttribute("id","Name")
let td1 = document.createElement("td");
tr1.appendChild(td1);
let teddyColor = shoppingCart[i].colors;
td1.textContent=teddyColor;
td.setAttribute("id","Color")
let price = shoppingCart[i].price + "€";
let td2 = document.createElement("td");
tr1.appendChild(td2);
td2.textContent=price;
let td3 = document.createElement("td");
tr1.appendChild(td3);
td3.setAttribute("class","counter");
let div = document.createElement("div");
td3.appendChild(div);
div.setAttribute("class","number");
div.setAttribute("id","number");
div.textContent=shoppingCart[i].qte;
// let div1 = document.createElement("div")
// td3.appendChild(div1)
// div1.setAttribute("class","counter-clic")
// let i1 = document.createElement("i")
// div1.appendChild(i1)
// i1.setAttribute("class","fas fa-plus plus")
// let i2 = document.createElement("i")
// div1.appendChild(i2)
// i2.setAttribute("class","fas fa-minus minus")
// let td4 = document.createElement("td")
// tr1.appendChild(td4)
// td4.textContent= subTotal
let td5 = document.createElement("td");
tr1.appendChild(td5);
td5.setAttribute("class","text-center");
let i3 = document.createElement("i");
td5.appendChild(i3);
i3.setAttribute("class","fas fa-times-circle bntDelated");
}
let tr2 = document.createElement("tr");
tableFoot.appendChild(tr2);
let td6 = document.createElement("td");
tr2.appendChild(td6);
td6.setAttribute("colspan","2");
let td7 = document.createElement("td");
tr2.appendChild(td7);
td7.textContent = "Total"
let totalCart = localStorage.getItem('totalCart')
let td8 = document.createElement("td");
tr2.appendChild(td8);
td8.setAttribute("colspan","3");
td8.setAttribute('class','text-right');
td8.textContent = totalCart + "€";
}
function checkInput(){
if (fristName.length == 0){
alert("test 1");
}else if(lastName.length == 0){
alert("test 2");
}else if(address.length == 0){
alert("test 3");
}else if(zip.length != 5){
alert("test 4");
}else if(city.length == 0){
alert("test 5");
}else if(email.length == 0){
alert("test 6");
}else {
console.log('send to api');
sendToApi();
}
}
function sendToApi(){
// crerer un objet qui va recuperer la value de chaque input du formulaire
//creation de la class client
class customer{
constructor(fristName,lastName,address,city,email){
this.lastName = lastName;
this.fristName = fristName;
this.address = address;
this.city = city;
this.email = email;
}
}
// objet contenant les infos du formulaire
let newCustumer = new customer (lastName,fristName, address,city,email)
// creer un tableau pour envoyer uniquement les ID des teddy
//recupérer le shoppingCart
let apiCart =JSON.parse(localStorage.getItem("shoppingCart")) ;
console.log("apiCart",apiCart)
let apiCartArray = []; // tableau des id des teddy
//parcourir le tableau et recuperer les id des teddy
if(apiCart) {
for (let i=0; i<apiCart.length; i++){
apiCartArray.push(apiCart[i].id)
console.log("send api id",apiCartArray)
}
}
// POST API
fetch("http://localhost:3000/api/teddies/order", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
contact: {
firstName: newCustumer.fristName,
lastName: newCustumer.lastName,
address: newCustumer.address,
city: newCustumer.city,
email: newCustumer.email,
},
products: apiCartArray,
}),
})
.then((response) => {
if (response.ok) {
return response.json();
}
})
.then((data) => {
localStorage.setItem("orderInfos", JSON.stringify(data));
})
.catch((error) => console.log("erreur de type : ", error));
}
I'm trying to parse .srt but I get an internal error and I can't figure out what is it.
Here is my code:
var subtitles;
jQuery.get('SB_LKRG-eng.srt', function(data) {
//alert(data);
function strip(s) {
return s.replace(/^\s+|\s+$/g,"");
}
srt = data.replace(/\r\n|\r|\n/g, '\n');
//alert(srt);
srt = strip(srt);
//alert(srt);
var srt_ = srt.split('\n\n');
alert(srt_);
var cont = 0;
for(s in srt_) {
st = srt_[s].split('\n');
alert(st);
if(st.length >=2) {
n = st[0];
i = strip(st[1].split(' --> ')[0]);
o = strip(st[1].split(' --> ')[1]);
t = st[2];
if(st.length > 2) {
for(j=3; j<st.length;j++)
t += '\n'+st[j];
}
subtitles[cont].number = n;
subtitles[cont].start = i;
subtitles[cont].end = o;
subtitles[cont].text = t;
//alert(subtitles[cont].start);
}
cont++;
}
});
I can extract the first 4 subtitles and then the code stops and breaks exception: TypeError, I can't understand why...
Here a sample of the subtitles file:
1
00:00:01,000 --> 00:00:04,000
Descargados de www.AllSubs.org
2
00:00:49,581 --> 00:00:52,049
Bueno, tienes que escapar, tengo que ir a jugar
3
00:00:52,084 --> 00:00:55,178
Tengo que encontrar un día que está lleno de nada más que sol
4
00:00:55,220 --> 00:00:57,552
Crucero por la calle, moviéndose al compás
5
00:00:57,589 --> 00:01:00,683
Todos los que conoces está teniendo nada más que diversión
6
00:01:00,726 --> 00:01:03,251
Deja todo detrás de ti
7
00:01:03,295 --> 00:01:06,128
Siente esas palmeras soplan
8
00:01:06,165 --> 00:01:09,157
La gente en el norte no puede encontrar
9
00:01:09,201 --> 00:01:11,829
Están fuera de palear la nieve
10
00:01:11,870 --> 00:01:14,998
El tiempo para moverse, pero no seas lento
11
00:01:15,040 --> 00:01:17,941
En sus marcas, prepárate para ir
Part of the code is from: http://v2v.cc/~j/jquery.srt/jquery.srt.js
Can anyone help me?
Thank you
var PF_SRT = function() {
//SRT format
var pattern = /(\d+)\n([\d:,]+)\s+-{2}\>\s+([\d:,]+)\n([\s\S]*?(?=\n{2}|$))/gm;
var _regExp;
var init = function() {
_regExp = new RegExp(pattern);
};
var parse = function(f) {
if (typeof(f) != "string")
throw "Sorry, Parser accept string only.";
var result = [];
if (f == null)
return _subtitles;
f = f.replace(/\r\n|\r|\n/g, '\n')
while ((matches = pattern.exec(f)) != null) {
result.push(toLineObj(matches));
}
return result;
}
var toLineObj = function(group) {
return {
line: group[1],
startTime: group[2],
endTime: group[3],
text: group[4]
};
}
init();
return {
parse: parse
}
}();
jQuery.get('demo.srt')
.done(function(text) {
try {
//Array with {line, startTime, endTime, text}
var result = PF_SRT.parse(text);
} catch (e) {
//handle parsing error
}
});
Demo
https://jsfiddle.net/5v7wz4bq/
Here is one problem:
o = strip(st[1].split(' --> ')[1]);
At this line, when there isn't any ' --> ' to split, the returned length of the array is 1, which errors when you ask for array item 2.
And here is another:
subtitles[cont].number = n;
....
Neither is the subtitles declared, nor its properties .number, ... etc.
Update
Here is a sample that works (switched the jQuery "read srt file" part for the data)
var data = document.getElementById("data").innerHTML;
data = data.replace(/>/g,">");
function strip(s) {
return s.replace(/^\s+|\s+$/g,"");
}
srt = data.replace(/\r\n|\r|\n/g, '\n');
srt = strip(srt);
var srt_ = srt.split('\n\n');
var cont = 0;
var subtitles = [];
for(s in srt_) {
st = srt_[s].split('\n');
if(st.length >=2) {
var st2 = st[1].split(' --> ');
var t = st[2];
if(st.length > 2) {
for(j=3; j < st.length;j++)
t += '\n'+st[j];
}
subtitles[cont] = { number : st[0],
start : st2[0],
end : st2[1],
text : t
}
console.log(subtitles[cont].number + ": " + subtitles[cont].text);
document.body.innerHTML += subtitles[cont].number + ": " + subtitles[cont].text + "<br>";
cont++;
}
}
<div id="data" style="display:none">1
00:00:01,000 --> 00:00:04,000
Descargados de www.AllSubs.org
2
00:00:49,581 --> 00:00:52,049
Bueno, tienes que escapar, tengo que ir a jugar
3
00:00:52,084 --> 00:00:55,178
Tengo que encontrar un día que está lleno de nada más que sol
4
00:00:55,220 --> 00:00:57,552
Crucero por la calle, moviéndose al compás
5
00:00:57,589 --> 00:01:00,683
Todos los que conoces está teniendo nada más que diversión
6
00:01:00,726 --> 00:01:03,251
Deja todo detrás de ti
7
00:01:03,295 --> 00:01:06,128
Siente esas palmeras soplan
8
00:01:06,165 --> 00:01:09,157
La gente en el norte no puede encontrar
9
00:01:09,201 --> 00:01:11,829
Están fuera de palear la nieve
10
00:01:11,870 --> 00:01:14,998
El tiempo para moverse, pero no seas lento
11
00:01:15,040 --> 00:01:17,941
En sus marcas, prepárate para ir
</div>
It is better to use the following regex to cover them if the number of lines of text in each section increases
/(\d+)\n([\d:,]+)\s+-{2}\>\s+([\d:,]+)\n([\s\S]*?(?=\n{2}|$))/g
View the output on the console
let subtitle = document.getElementById('subtitle').value;
console.log(_subtitle(subtitle));
function _subtitle(text) {
let Subtitle = text;
let Pattern = /(\d+)\n([\d:,]+)\s+-{2}\>\s+([\d:,]+)\n([\s\S]*?(?=\n{2}|$))/g;
let _regExp = new RegExp(Pattern);
let result = [];
if (typeof (text) != "string") throw "Sorry, Parser accept string only.";
if (Subtitle === null) return Subtitle;
let Parse = Subtitle.replace(/\r\n|\r|\n/g, '\n');
let Matches;
while ((Matches = Pattern.exec(Parse)) != null) {
result.push({
Line: Matches[1],
Start: Matches[2],
End: Matches[3],
Text: Matches[4],
})
}
return result;
}
<textarea id="subtitle">1
00:00:00,000 --> 00:00:00,600
Hi my friends
2
00:00:00,610 --> 00:00:01,050
In the first line, everything works properly
But there is a problem in the second line that I could not solve :(
3
00:00:01,080 --> 00:00:03,080
But then everything is in order and good
4
00:00:03,280 --> 00:00:05,280
You do me a great favor by helping me. Thankful</textarea>
I have a function which return some elements from my MongoDB database but I have a problem with my variables. It says that one of my variable isn't defined the first time but then if I refresh, the error disappear. So I think it's an error of global variable defined in an inner scope which can't be accessed the first time or something like that.
So here's my code :
exports.findQuestion = function findQuestion()
{
var tabRand = new Array(); // on déclare un nouveau tableau où on va stocker les jets de rand
var query = boardModel.find(null); // on cherche toutes les entrées dans la collection
query.exec(function (err, tabQuestion) {
if (err) { throw err;}
var rep = tabQuestion[0];
var rand = Math.floor((Math.random()*rep.question.length+1)); // random sur le tableau
var i = false;
tabRand[0] = 0;
while (i == false)
{
for(var random in tabRand) // on vérifie le résultat du rand avec les rand précédents
{
if(random != rand) // si le rand est différent on le garde
{
i = true;
if(tabRand.length-1 == rep.question.length) // si la taille de tabRand est égale à la longueur du tableau de questions de la collection alors on le reinitialise
{
tabRand = new Array();
}
}
}
tabRand.push[rand]; // on ajoute le rand précédent à tabRand
rand = Math.floor((Math.random()*rep.question.length+1)); // et on en fait un nouveau
}
quest = rep.question[rand-1].quest; // on récupère le resultat attendu
repJuste = rep.question[rand-1].rep_j;
repFausse1 = rep.question[rand-1].rep_f1;
repFausse2 = rep.question[rand-1].rep_f2;
gainQ = rep.question[rand-1].gain;
nomTr = rep.question[rand-1].name_t;
});
return [quest, repJuste, repFausse1, repFausse2, gainQ, nomTr];
}
So the first time, it says that quest is not defined but then everything works well ...
PS : Sorry for the half-French, half-English code ^^
I see one problem here, you can't return something in a asynchronous function, you should use a callback.
If you want to understand it :
You do your asynchronous query (and you do something in your callback with the result tabQuestion)
and your return something but you're not sure your async function is done.
try async.js to help you manage your asynchronous problems
EDIT:
async.parallel([
function(callback){
boardModel.find().exec(function (err, tabQuestion) {
if (err) { throw err;}
var rep = tabQuestion[0];
var rand = Math.floor((Math.random()*rep.question.length+1)); // random sur le tableau
var i = false;
tabRand[0] = 0;
while (i == false)
{
for(var random in tabRand) // on vérifie le résultat du rand avec les rand précédents
{
if(random != rand) // si le rand est différent on le garde
{
i = true;
if(tabRand.length-1 == rep.question.length) // si la taille de tabRand est égale à la longueur du tableau de questions de la collection alors on le reinitialise
{
tabRand = new Array();
}
}
}
tabRand.push[rand]; // on ajoute le rand précédent à tabRand
rand = Math.floor((Math.random()*rep.question.length+1)); // et on en fait un nouveau
}
quest = rep.question[rand-1].quest; // on récupère le resultat attendu
repJuste = rep.question[rand-1].rep_j;
repFausse1 = rep.question[rand-1].rep_f1;
repFausse2 = rep.question[rand-1].rep_f2;
gainQ = rep.question[rand-1].gain;
nomTr = rep.question[rand-1].name_t;
});
callback(null, quest, repJuste, repFausse1, repFausse2, gainQ, nomTr);
}],
function(err){
if(err){
console.log(err);
}else{
console.timeEnd('chargement bd');
socket.emit('event', {'quest': quest, 'repJuste' : repJuste }); //add all your params
}
});
I'm facing this embarrassing situation. First, I'm on IE 10 right now, but this problem has been detected on IE9 as well. I have this input field and I need 2 events to work on it:
- onKeyUp, to check if the field's value is numeric; and
- onChange, to run some JS when the right number is inputted
If assigned separately, they work just fine. However, whenever I set these 2 events on the input field, the onChange event won't trigger, no matter what. All the other JS on this page has been stripped to prevent interference.
Below is the JS code for the onKeyUp:
<script>
function CampoNumerico(campo){
var valor = campo.value;
var novoValor = '';
var pontoPosicao = '';
if (isNaN(valor)){ // se nao for numero, devemos retornar o campo ao ultimo valor valido
alert(valor + " nao eh um numero valido");
novoValor = campo.defaultValue;
}
else{ //sendo um numero, buscamos a posicao de sua eventual virgula
valor = valor.split('');
for (var i = 0; i < valor.length; i++){
if (valor[i] == '.' && pontoPosicao == ''){
pontoPosicao = i;
}
}
// se nao houver ponto, o novo valor do campo sera igual ao valor de entrada da funcao
if ( pontoPosicao == ''){
for (var i = 0; i < valor.length; i++){
novoValor += valor[i];
}
}
else{ // se houver o ponto, registramos o novo valor igual ao valor de entrada, ate o limite de casas decimais
var tamanho = ((pontoPosicao + 3) < valor.length)? pontoPosicao + 3 : valor.length;
for (var i = 0; i < tamanho; i++){
novoValor += valor[i];
}
}
if (pontoPosicao != '' && pontoPosicao < (valor.length - 3)){ // se houver um ponto e mais de 2 casas decimais, alertamos o usario e desconsideramos as casas adicionais
alert("Aviso: " + campo.value + " tem mais de 2 casas decimais; serão consideradas apenas as primeiras casas - " + novoValor);
}
}
// terminamos por atualizar o valor do campo
campo.value = novoValor;
} // fim da CampoNumerico
</script>
Below is the field I'm trying to assign this script to:
<input type='text' name='campo' value='0' onchange='alert("1")' onkeyup='CampoNumerico(this)'>
At this point I just want to alert "1" when the onchange is triggered, but I'm unable to do even this simple action...
Interestingly, this coding works on other browsers just fine - Chrome & Firefox. Can anyone help me with this embarrassing situation? Thanks in advance for any thoughts.
EDIT - input field now visible separately