How to exclude consonants in javascript? - javascript

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++;
}

Related

How to create a score board js for my game

I'm just starting to learn how to code, I've been working on a game battleship like, I have managed to do most of the things but I can't make my scoreboard work, I would like to know how to do it or what do I need to change in order for making it work.
I've tried adding var drawScore but when I add it to my game board disappears.
Also, I speak Spanish so part of my code is in that language.
var rows = 8;
var cols = 8;
var squareSize = 55;
var aciertos=0;
var errores=0;
var gameBoardContainer = document.getElementById("gameboard");
// Columnas y Filas
for (i = 0; i < cols; i++) {
for (j = 0; j < rows; j++) {
var square = document.createElement("div");
gameBoardContainer.appendChild(square);
square.id = 's' + j + i;
var topPosition = j * squareSize;
var leftPosition = i * squareSize;
square.style.top = topPosition + 'px';
square.style.left = leftPosition + 'px';
}
}
var hitCount = 0;
var missCount= 0;
/*
0 = vacio, 1 = Barco , 2 = Barco Hundiso, 3 = Tiro fallido
*/
var gameBoard = [
[0,0,0,1,1,1,1,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,1,0],
[0,0,0,0,0,0,1,0],
[1,0,0,0,0,0,0,0],
[1,0,0,0,0,0,0,0],
[1,0,0,0,0,0,0,0]
]
gameBoardContainer.addEventListener("click", fireTorpedo, false);
function fireTorpedo(e) {
if (e.target !== e.currentTarget) {
var row = e.target.id.substring(1,2);
var col = e.target.id.substring(2,3);
if (gameBoard[row][col] == 0) {
e.target.style.backgroundImage = "url('agua.png')";
// se indica que hay un tiro fallido
gameBoard[row][col] = 3;
missCount++;
if (missCount == 8) {
alert("Perdiste");
errores=errores+1;
}
// Se cambia el color del cuadro si se da click en uno con barco y se cambia el valor del cuadro
} else if (gameBoard[row][col] == 1) {
e.target.style.backgroundImage = "url('explo.png')";
// El valor cambia a 2 si el barco fue "golpeado"
gameBoard[row][col] = 2;
// Se incrementa el valor si otra parte se ha "golpeado"
hitCount++;
if (hitCount == 9) {
alert("Todas las naves enemigas fueron derrotadas! Ganaste!");
}
// Alerta si el jugador dio click en un cuadro previamente seleccionado
} else if (gameBoard[row][col] > 1) {
alert("No gastes tus torpedos! Ya disparaste aquí.");
}
// Si se gana o pierde, el juego se reinicia
if ((hitCount==9) || (missCount==8))location.href="Battleship.html";
}
aciertos==hitCount;
errores==missCount;
//Coloca las puntuaciones
if ((missCount >= 1) ) {
errores=missCount+1;
document.puntuacion.errores.value=errores;}
if ((hitCount >= 1)) {
aciertos=parseInt(document.puntuacion.aciertos.value);
aciertos=aciertos+1;
document.puntuacion.aciertos.value=aciertos;};
}
body {
margin: 60px auto;
width: 70%;
max-width: 950px;
}
h1 {
font-size: 3em;
font-family:'Helvetica', 'Arial', 'Sans-Serif';
}
p, button, input {
font-size: 1.5em;
line-height: 1.4em;
color: #333;
margin-bottom:1em;
}
#gameboard {
position:relative;
margin:0 auto 2em auto;
width:500px;
height:500px;
}
#gameboard div {
position:absolute;
-moz-box-sizing: border-box; /* Firefox 1 - 28 */
box-sizing: border-box; /* Safari 5.1+, Chrome 10+, Firefox 29+, Opera 7+, IE 8+, Android 4.0+, iOS any */
background: #add3e6; /* Old browsers */
border: 1px solid #ddd;
width:50px;
height:50px;
}
#gameboard div:hover
{
color: white;
background-image: url(mira.png) ;
}
<!DOCTYPE html>
<html>
<head>
<title>Battleship</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body background="Mar.jpg">
<img src="Battleship.jpg" valign="top" height="100%" width="100%" > <br>
<table border="" cellpadding="9" cellspacing="9" width="99%" >
<form name="inicia">
<tr align= "center" > <p style="background-color: aliceblue"><b>Instrucciones:</b> <br>
Coloque el cursor sobre alguno de los cuadros y haga click;<br>
La siguiente imagen <img src="agua.png" height="5%" width="5%"> aparecerá si en el cuadro no hay un barco <br>Si el cuadro tiene un barco aparecerá la siguiente imagen <img src="explo.png" height="5%" width="5%">. <br>
Usted debe encontrar los siguientes 3 barcos: uno de dos posiciones (dos celdas), uno de tres posiciones y uno de 4 posiciones, los barcos pueden estar en posición vertical (|) u horizontal (--)
<br>
Si usted comete 8 errores el juego terminará. </p>
</tr>
<tr align="center">
<form name="puntuacion">
<td><p class="texto" style="background: #ffffff">
Puntaje
<p class="texto" style="background: #9efaf3">Aciertos</p>
<input name="aciertos" type="text" size="3" class="campo" readonly="true" disabled="true" style="background: #9efaf3">
<p class="texto" style="background: #f47f53">Errores</p>
<input name="errores" type="text" size="3" class="campo" readonly="true" disabled="true" style="background: #f47f53">
</td>
<td> <div id="gameboard"></div>
<script type="text/javascript" src="battleship.js"></script>
</td>
</tr></form></table>
<tr>
</body>
</html>
You need to the input for the miss counter and the input for the hit counter.
After that you need to set the input value every time a miss or a hit occur.
var rows = 8;
var cols = 8;
var squareSize = 55;
var aciertos=0;
var errores=0;
var gameBoardContainer = document.getElementById("gameboard");
// Here you get the inputs, you need to set the id's in the html code.
var hitCountInputElement = document.getElementById('aciertos');
var missCountInputElement = document.getElementById('errores');
var hitCount = 0;
var missCount= 0;
/*
0 = vacio, 1 = Barco , 2 = Barco Hundiso, 3 = Tiro fallido
*/
var gameBoard = [
[0,0,0,1,1,1,1,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,1,0],
[0,0,0,0,0,0,1,0],
[1,0,0,0,0,0,0,0],
[1,0,0,0,0,0,0,0],
[1,0,0,0,0,0,0,0]
]
// Columnas y Filas
for (i = 0; i < cols; i++) {
for (j = 0; j < rows; j++) {
var square = document.createElement("div");
gameBoardContainer.appendChild(square);
square.id = 's' + j + i;
var topPosition = j * squareSize;
var leftPosition = i * squareSize;
square.style.top = topPosition + 'px';
square.style.left = leftPosition + 'px';
}
}
gameBoardContainer.addEventListener("click", fireTorpedo, false);
function fireTorpedo(e) {
if (e.target !== e.currentTarget) {
var row = e.target.id.substring(1,2);
var col = e.target.id.substring(2,3);
if (gameBoard[row][col] == 0) {
e.target.style.backgroundImage = "url('agua.png')";
// se indica que hay un tiro fallido
gameBoard[row][col] = 3;
missCount++;
// Here is where you set the input miss count value
setMissCountInputElementValue(missCount);
if (missCount == 8) {
alert("Perdiste");
errores=errores+1;
}
// Se cambia el color del cuadro si se da click en uno con barco y se cambia el valor del cuadro
} else if (gameBoard[row][col] == 1) {
e.target.style.backgroundImage = "url('explo.png')";
// El valor cambia a 2 si el barco fue "golpeado"
gameBoard[row][col] = 2;
// Se incrementa el valor si otra parte se ha "golpeado"
hitCount++;
// Here is where you set the input hit count value
setHitCountInputElementValue(hitCount);
if (hitCount == 9) {
alert("Todas las naves enemigas fueron derrotadas! Ganaste!");
}
// Alerta si el jugador dio click en un cuadro previamente seleccionado
} else if (gameBoard[row][col] > 1) {
alert("No gastes tus torpedos! Ya disparaste aquí.");
}
// Si se gana o pierde, el juego se reinicia
if ((hitCount==9) || (missCount==8)) {
location.href="Battleship.html"
};
}
aciertos==hitCount;
errores==missCount;
//Coloca las puntuaciones
if ((missCount >= 1) ) {
errores=missCount+1;
document.puntuacion.errores.value=errores;
}
if ((hitCount >= 1)) {
aciertos=parseInt(document.puntuacion.aciertos.value);
aciertos=aciertos+1;
document.puntuacion.aciertos.value=aciertos;
}
}
function setHitCountInputElementValue (hitCount) {
hitCountInputElement.value = hitCount;
}
function setMissCountInputElementValue (missCount) {
missCountInputElement.value = missCount;
}

pass an array in a function to string JavaScript

I have the following problem with the following code:
When I pass the Array to "track" I always get an error, I think it may be because an object is being passed and a String, but I'm not sure and I can't check it.
for (var i = 0; i < data.twKeyword.length; i++){
var stream = client.stream('statuses/filter', {track: data.twKeyword[i]});
}
I have tried:
data.twKeyword
data.twKeyword[i]
[data.twKeyword]
data.twKeyword
data.twKeyword[i]
'data.twKeyword[i]'
data.twKeyword[0].value
data.twKeywprd[0].toString()
And none of these options has given me a positive result.
He creado una variable nueva a la que le he ido pasando los valores del Array:
var x1 = JSON.stringify(data.twKeyword[i].name);
Después como estos valores se mostraban con doble comillas (""), he utilizado el siguiente código para eliminarlas:
x1.replace(/['"]+/g, '')
El código ha quedado así, y funciona:
for (var i = 0; i < data.twKeyword.length; i++){
var x1 = JSON.stringify(data.twKeyword[i].name);
var stream = client.stream('statuses/filter', {track: x1.replace(/['"]+/g, '')});
}

Parse a SRT file with jQuery Javascript

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>

To count number of rows in a table if the rows were created after the DOM loaded

I create rows after the DOM loaded, but I want to know how to count number of rows for eliminate the last.
I have this.
<script type="text/javascript">//Procesamiento del formulario.
$(document).ready(function(){
var cuentaTr = $('#elementos >tbody >tr').length - 1; //Cuenta el número de filas que tiene la tabla originalmente, es 1.
$('#agregar').click(function(){ //Clic en el botón que agrega nueva fila.
cuentaTr++; //Es el número de fila que le corresponde a cada una que se crea.
var nume = $('#elementos >tbody >tr >td').length; //Obtener el número de celdas
var capa = document.getElementById("elementos"); //Obtener el elemento con el id elementos
var tr = ("tr"); //Crear una tag tr
capa.appendChild(tr); //Agregar la tag al elemento con id elementos.
var nuevaLetra = "A"; //La variable con la que se le asigna una letra a cada columna.
for (var i = 1; i <= nume; i++) {
$('<td><input type="text" class="prueba" id="'+nuevaLetra+cuentaTr+'" name="columna'+nuevaLetra+cuentaTr+'" required/></td>').appendTo('#elementos'); //Creación de nuevo input. THIS IS THE IMPORTANT!
var ASCII = nuevaLetra.charCodeAt(); //Obtener código ASCII
var aumento = ((ASCII+1 >= 65 && ASCII+1 <= 90) || (ASCII+1 >= 97 && ASCII+1 <= 122)) ? ASCII+1 : ASCII; //Incremenar la letra
var nuevaLetra = String.fromCharCode(aumento); //Tranformar el código a letra.
};
if (cuentaTr == 2){
$('<button type="button" id="eliminame">-</button>').insertAfter('#agregar'); //Creación del botón de eliminación de filas
};
});
$(document).on('click', '#eliminame', function(){ //Función que elimina las filas HERE IS MY DUDE.
$('#elementos tbody tr:last').remove(); //I WANT TO REMOVE THE LAST ROW. THIS CODE ELIMINATE ONLY THE ROWS CREATE WHEN DOM LOADED.
cuentaTr--;
if (cuentaTr == 1) {
$(this).remove();
};
});
});
</script>
What I can to do?
Thank you!
I'm sorry for my English. I can't speak English well.
Looks like there are some problems on how the tr is appended to the table, try
$(document).ready(function () {
var cuentaTr = $('#elementos >tbody >tr').length - 1; //Cuenta el número de filas que tiene la tabla originalmente, es 1.
$('#agregar').click(function () { //Clic en el botón que agrega nueva fila.
cuentaTr++; //Es el número de fila que le corresponde a cada una que se crea.
var nume = $('#elementos >tbody >tr:first >td').length; //Obtener el número de celdas
var capa = $("#elementos"); //Obtener el elemento con el id elementos
var tr = $('#tr').appendChild(tr); //Agregar la tag al elemento con id elementos.
var nuevaLetra = "A"; //La variable con la que se le asigna una letra a cada columna.
for (var i = 1; i <= nume; i++) {
$('<td><input type="text" class="prueba" id="' + nuevaLetra + cuentaTr + '" name="columna' + nuevaLetra + cuentaTr + '" required/></td>').appendTo(tr); //Creación de nuevo input. THIS IS THE IMPORTANT!
var ASCII = nuevaLetra.charCodeAt(); //Obtener código ASCII
var aumento = ((ASCII + 1 >= 65 && ASCII + 1 <= 90) || (ASCII + 1 >= 97 && ASCII + 1 <= 122)) ? ASCII + 1 : ASCII; //Incremenar la letra
var nuevaLetra = String.fromCharCode(aumento); //Tranformar el código a letra.
};
if (cuentaTr == 2) {
$('<button type="button" id="eliminame">-</button>').insertAfter('#agregar'); //Creación del botón de eliminación de filas
};
});
$(document).on('click', '#eliminame', function () { //Función que elimina las filas HERE IS MY DUDE.
$('#elementos tbody tr:last').remove(); //I WANT TO REMOVE THE LAST ROW. THIS CODE ELIMINATE ONLY THE ROWS CREATE WHEN DOM LOADED.
cuentaTr--;
if (cuentaTr == 1) {
$(this).remove();
};
});
});
var cuentaTr = $('#elementos >tbody >tr').length - 1; (already in your code) should give you the number of rows (minus one). Maybe make a jsfiddle so we can debug what's going on?

onChange event not working on IE9/10 when there are other events?

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

Categories

Resources