Checking by not restricting how many elements - javascript

I want to make it like for example when the word spilt into elements, the checking part will not restrict to only four.(In code comment it as "this part"). I want to be depending on how many the elements split so that it will be correct.
if(original[0]==$("#box1").text()&&original[1]==$("#box2").text()&&original[2]==$("#box3").text()&&original[3]==$("#box4").text())
This only restricted to four, then the checking will be correct. How can I do it such as there will be three split elements or more then four elements and the checking will still be correct.
<script>
js_var = "<?php echo $output ?>";
var c = ['c1','c2','c3','c4','c5','c6','c7','c8','c9','c10'];
var div_id = ['id1','id2','id3','id4','id5','id6','id7','id8','id9','id10'];
var box_id = ['box1','box2','box3','box4','box5','box6','box7','box8','box9','box10'];
var original = js_var.split("#");
var balls90= js_var.split("#");
var x = document.getElementById("demo");
for (var i=0; i < original.length; i++) {
var el = document.createElement('div');
el.id = c[i];
el.innerHTML = original[i];
x.appendChild(el);
}
function getNumbers() {
var player1 = new Array();
balls90.sort(function() {
return Math.random() - .25;
document.getElementById("shuffle").onclick = function(){displayDate()};
});
for (var i = 0; i < balls90.length; i++) {
document.writeln('<div id='+box_id[i]+' class=box droppable=true ondrop=drop(event)
ondragover=allowDrop(event)></div>');
}
for (var i = 0; i < balls90.length; i++) {
player1.push(balls90[i]);
document.writeln('<div id='+div_id[i]+' draggable=true droppable=true
ondragstart=drag(event)>'+balls90[i]+'</div>');
}
}
getNumbers();
function dragWord(dragEvent){
dragEvent.dataTransfer.setData("text/html",
dragEvent.target.textContent+"|"+dragEvent.target.parentNode.id);
}
function dropWord(dropEvent){
var dropData = dropEvent.dataTransfer.getData("text/html");
var dropItems = dropData.split("|");
var prevElem = document.getElementById(dropItems[1]);
prevElem.getElementsByTagName("div")[0].textContent = dropEvent.target.textContent;
dropEvent.target.textContent = dropItems[0];
dropEvent.preventDefault();
}
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("Text", ev.target.id);
}
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("Text");
ev.target.appendChild(document.getElementById(data));
//this part
if(original[0]==$("#box1").text()&&original[1]==$("#box2").text()&&original[2]==$("#box3").text()&&original[3]==$("#box4").text())
{
alert('correct');
}
}
<script>

Something along these lines:
var result = true;
for (var i=0, i<original.length, ++i) {
if (original[i] !== $("#box"+(i+1)).text()) {
result = false;
break;
}
}
if(result) {
alert('correct');
}

Related

TypeError in Javascript

function url_info()
{
var url_val=document.getElementsByClassName("spc-tab");
var current_s=0;
for(var i=0;i<url_val.length;i++)
{
var url_class=url_val[i].className.split(" ");
if(url_class[1]!=null)
{
if(url_class[1]=="selected")
{
current_s=i;
break;
}
}
}
var temp_1=url_val[current_s].text; //**Error here**
return(temp_1);
}
In this function url_info i am getting the TypeError But i don't know why?? .... as My var current_s is defined within the scope and integer...
why write this much of code when one line can do:
function url_info() {
var temp_1 = "";
var url_val = document.querySelector(".spc-tab.selected");
temp_1 = url_val[0].text > 0 ? url_val[0].text : temp_1;
return (temp_1);
}
and second, you don't require to convert your class name to string then split. You just can access them through classlist. Then use contains.
function url_info() {
var url_val = document.getElementsByClassName("spc-tab");
var current_s = 0;
for (var i = 0; i < url_val.length; i++) {
var isSelected = url_val[i].classList.contains("selected");
if (isSelected) {
current_s = i;
break;
}
}
var temp_1 = url_val[current_s].text;
return (temp_1);
}

Upload small image in a dynamic form?

Using either Javascript or HTML, I have a dynamic form that refreshes/updates each time the user adds data to the table. It even has a 'modify' button and an 'erase' button to delete that particular line. However, one last thing I want to add is a button that would allow the user to upload a picture that would fit in the very last slot of the column. How do I achieve it in such a way that every time the user 'adds' the data (and another row is formed) with that particular image, the next time he wants to add another row he is able to select another image?
window.onload = load;
var id = 1;
var colEmpleados = [];
var colSectores = [{id:1, nombre:"Sector 1"},
{id:2, nombre:"Sector 2"},
{id:3, nombre:"Sector 3"}];
function load()
{
var btnAgregar = document.getElementById("btnAgregar");
btnAgregar.onclick = agregar;
var btnConfirmar = document.getElementById("btnConfirmar");
btnConfirmar.onclick = confirmarModificacion;
var btnCancelar = document.getElementById("btnCancelar");
btnCancelar.onclick = cancelar;
cargarSelectSectores();
habilitarIngreso();
}
function habilitarIngreso()
{
var rowA = document.getElementById("rowAgregar");
rowA.style.display = 'block';
var rowM = document.getElementById("rowModificar");
rowM.style.display = 'none';
}
function habilitarModificar()
{
var rowM = document.getElementById("rowModificar");
rowM.style.display = 'block';
var rowA = document.getElementById("rowAgregar");
rowA.style.display = 'none';
}
function confirmarModificacion()
{
var idEmpleado = document.getElementById("idEmpleado").value;
for(var i = 0; i<colEmpleados.length;i++)
{
if(colEmpleados[i].idEmpleado == idEmpleado)
{
colEmpleados[i].nombre = document.getElementById("txtNombre").value;
colEmpleados[i].apellido = document.getElementById("txtApellido").value;
colEmpleados[i].sector = document.getElementById("sltSector").value;
colEmpleados[i].edad = document.getElementById("txtEdad").value;
colEmpleados[i].ingreso = document.getElementById("dtpIngreso").value;
}
}
mostrar();
habilitarIngreso();
limpiarForm();
}
function cancelar()
{
habilitarIngreso();
limpiarForm();
}
function borrar()
{
var idEmpleado = this.getAttribute("idEmpleado");
for(var i=0; i<colEmpleados.length; i++)
{
if(colEmpleados[i].idEmpleado == idEmpleado)
{
colEmpleados.splice(i,1);
}
}
mostrar();
}
function modificar()
{
habilitarModificar();
var idEmpleado = this.getAttribute("idEmpleado");
for(var i=0; i<colEmpleados.length; i++)
{
if(colEmpleados[i].idEmpleado == idEmpleado)
{
document.getElementById("idEmpleado").value = colEmpleados[i].idEmpleado;
document.getElementById("txtNombre").value = colEmpleados[i].nombre;
document.getElementById("txtApellido").value = colEmpleados[i].apellido;
document.getElementById("sltSector").value = colEmpleados[i].sector;
document.getElementById("txtEdad").value= colEmpleados[i].edad;
document.getElementById("dtpIngreso").value= colEmpleados[i].ingreso;
}
}
mostrar();
}
function cargarSelectSectores()
{
var selectSectores = document.getElementById("sltSector");
selectSectores.innerHTML = "<option id='0'>--- Sectores ---</option>";
for(var i = 0; i<colSectores.length; i++)
{
selectSectores.innerHTML +="<option id="+colSectores[i].id+">"+colSectores[i].nombre+"</option>";
}
mostrar();
}
function agregar()
{
var nombre = document.getElementById("txtNombre").value;
var apellido = document.getElementById("txtApellido").value;
var sector = document.getElementById("sltSector").value;
var edad = document.getElementById("txtEdad").value;
var fechaIngreso = document.getElementById("dtpIngreso").value;
var empleado = {};
empleado.idEmpleado = id;
empleado.nombre = nombre;
empleado.apellido = apellido;
empleado.sector = sector;
empleado.edad = edad;
empleado.ingreso = fechaIngreso;
colEmpleados.push(empleado);
id++;
limpiarForm();
mostrar();
}
function limpiarForm()
{
var colInputs = document.getElementsByTagName("input");
for(var i = 0; i<colInputs.length; i++)
{
if(colInputs[i].type != "button")
{
colInputs[i].value = "";
}
}
document.getElementById("sltSector").value = "0";
}
function mostrar()
{
var bodyTabla = document.getElementById("datosEmpleados");
bodyTabla.innerHTML = "";
for(var i = 0; i<colEmpleados.length; i++)
{
var emp = colEmpleados[i];
bodyTabla.innerHTML +="<tr><td>"+emp.idEmpleado+"</td><td>"+emp.nombre+"</td><td>"+emp.apellido+"</td><td>"+emp.edad+"</td><td>"+emp.sector+"</td><td>"+emp.ingreso+"</td><td><input class='btnBorrar' type='button' value='Borrar' idEmpleado="+emp.idEmpleado+" /></td><td><input class='btnModificar' type='button' value='Modificar' idEmpleado="+emp.idEmpleado+" /></td></tr>";
}
var colBotones = document.getElementsByClassName("btnBorrar");
for(var i = 0; i<colBotones.length; i++)
{
colBotones[i].onclick = borrar;
}
var colBotonesModificar = document.getElementsByClassName("btnModificar");
for(var i = 0; i<colBotonesModificar.length; i++)
{
colBotonesModificar[i].onclick = modificar;
}
}
Thanks in advance!

Populate form from JSON.parse

I am trying to re-populate a form from some values in localStorage. I can't quite manage the last part to get the loop to populate my name and values.
function loadFromLocalStorage() {
PROCESS_SAVE = true;
var store = localStorage.getItem(STORE_KEY);
var jsn = JSON.parse(store);
console.log(jsn);
if(store.length === 0) {
return false;
}
var s = jsn.length-1;
console.log(s);
for (var i = 0; i < s.length; i++) {
var formInput = s[i];
console.log(s[i]);
$("form input[name='" + formInput.name +"']").val(formInput.value);
}
}
Could I get some pointers please.
Your issue is in this section of code.
var s = jsn.length-1;
console.log(s);
for (var i = 0; i < s.length; i++) {
You are setting s to the length of the jsn array minus 1, then using it as if it were jsn. I think you intended something like this.
function loadFromLocalStorage() {
PROCESS_SAVE = true;
var store = localStorage.getItem(STORE_KEY);
var jsn = JSON.parse(store);
console.log(jsn);
if(store.length === 0) {
return false;
}
for (var i = 0; i < jsn.length; i++) {
var formInput = jsn[i];
console.log(jsn[i]);
$("form input[name='" + formInput.name +"']").val(formInput.value);
}
}

javascript keyword finder loop

This program is suppose to find keyword & open the link only 1 time, but the loop keeps opening infinity links. please help!
var keywordName = "miller macc";
var split = keywordName.split(" ");
var tFunction = "twitterScan()";
var tweet = new Array();
var tweetName = new Array();
function twitterScan()
{
for (var i = 0; i < split.length; i++)
{
tweetName[i] = document.getElementsByClassName("fullname js-action-profile-name show-popup-with-id")[0].innerHTML;
tweet[i] = document.getElementsByClassName("js-tweet-text")[i].innerHTML;
if (tweet[0].match(split[i]) == split[i])
{document.getElementsByClassName("twitter-timeline-link")[0].click();}
else {location.reload(true);}
}
}
setTimeout(tFunction, 200);
You were not stopping the timer. So it was performing the same action for infinite interval. Try this:
var keywordName = "miller macc";
var split = keywordName.split(" ");
var tFunction = "twitterScan()";
var tweet = new Array();
var tweetName = new Array();
var t;
function twitterScan() {
for (var i = 0; i < split.length; i++) {
tweetName[i] = document.getElementsByClassName("fullname js-action-profile-name show-popup-with-id")[0].innerHTML;
tweet[i] = document.getElementsByClassName("js-tweet-text")[i].innerHTML;
var tweetMatch = tweet[0].match(split[i]);
if (tweetMatch != null && tweetMatch == split[i]) {
document.getElementsByClassName("twitter-timeline-link")[0].click();
} else {
location.reload(true);
}
clearTimeout(t);
}
}
t = setTimeout(tFunction, 200);

banner ads not visible in html page

i have a file banners.js
function addEvent(object, evName, fnName, cap) {
if (object.attachEvent)
object.attachEvent("on" + evName, fnName);
else if (object.addEventListener)
object.addEventListener(evName, fnName, cap);
}
var nextAd;
function makeBannerAds() {
var bannerBox = document.createElement("div");
bannerBox.id = "bannerBox";
document.body.appendChild(bannerBox);
for (var i=0; i<adsURL.length; i++) {
var bannerAd = document.createElement("div");
bannerAd.className = "bannerAd";
bannerAd.style.zIndex = i;
var urlLink = document.createElement("a");
urlLink.href = adsURL[i];
var bannerIndex = document.createElement("img");
bannerIndex.src = "banner" + i +".jpg";
bannerIndex.style.width="290px";
bannerIndex.style.height="55px";
bannerBox.appendChild(bannerAd);
}
bannerBox.appendChild(bannerAd);
setInterval("changeBannerAd()", 10000);
}
function changeBannerAd() {
var allAds = document.getElementById("bannerBox").childNodes;
alert('work');
for(var i=0; i<num; i++) {
if(allAds.style.zIndex == 0) {
allAds.style.top = "-50px";
nextAd = allAds;
}
}
for(var i=0; i<num; i++) {
allAds.style.zIndex--;
if(allAds.style.zIndex < 0)
allAds.style.zIndex = num-1;
}
var timeDelay = 0;
for(var i=-50; i<=0; i++) {
setTimeout("moveNextAd(" + i + ")", timeDelay);
timeDelay += 15;
}
}
function moveNextAd(top) {
nextAd.style.top = top + ".px"
}
addEvent(window, "load", makeBannerAds(), false);
the second file
ads.js
var adsURL = new Array();
//this stores each item in the array using a index place holder
adsURL[0] = "testpage0.htm";
adsURL[1] = "testpage1.htm";
adsURL[2] = "testpage2.htm";
adsURL[3] = "testpage3.htm";
adsURL[4] = "testpage4.htm";
adsURL[5] = "testpage5.htm";
adsURL[6] = "testpage6.htm";
adsURL[7] = "testpage7.htm";
adsURL[8] = "testpage8.htm";
adsURL[9] = "testpage9.htm";
adsURL[10] = "testpage10.htm";
adsURL[11] = "testpage11.htm";
//and an html file where these are included.
javascript is not showing any error and also all the statements are running but the images are not visible on the page. i couldnot figure the problem. working from last 2 days.
New answer:
Some of your code had to be revised I think. I just edited this off of what I thought it was supposed to look like.
Check the new jsFiddle
I think it might be getting you closer.
Briefly, the issue was that childNodes() returns an array of elements, so you need to reference that variable as you would an array
Secondly, you didn't have all the appends that were required.
var adsURL = new Array();
adsURL[0] = "testpage0.htm";
...
adsURL[11] = "testpage11.htm";
var nextAd;
var moveNextAd = function (top) {
nextAd.style.top = top + ".px"
}; //changed this to function as variable, answer explained below
var changeBannerAd = function () {
var num = adsURL.length
var allAds = document.getElementById("bannerBox")
allAds = allAds.childNodes;
//^^^ here is what was wrong
// Child nodes returns an array of elements
// So for allAds, you should reference it with allAds[i]
for (var i = 0; i < num; i++) {
if (allAds[i].style.zIndex == 0) {
allAds[i].style.top = "-50px";
nextAd = allAds[i++];
}
}
for (var i = 0; i < num; i++) {
allAds[i].style.zIndex--;
if (allAds[i].style.zIndex < 0) allAds[i].style.zIndex = num - 1;
}
var timeDelay = 0;
for (var i = -50; i <= 0; i++) {
setTimeout((function () {
moveNextAd(" + i + ");
}()), timeDelay);
timeDelay += 15;
}
}; //changed this to function as variable too.
function addEvent(object, evName, fnName, cap) {
if (object.attachEvent) object.attachEvent("on" + evName, fnName);
else if (object.addEventListener) object.addEventListener(evName, fnName, cap);
}
function makeBannerAds() {
var bannerBox = document.createElement("div");
bannerBox.id = "bannerBox";
document.body.appendChild(bannerBox);
for (var i = 0; i < adsURL.length; i++) {
var bannerAd = document.createElement("div");
bannerAd.className = "bannerAd";
bannerAd.style.zIndex = i;
bannerAd.style.position = "absolute";
var urlLink = document.createElement("a");
urlLink.href = adsURL[i];
var bannerIndex = document.createElement("img");
bannerIndex.src = "banner" + i + ".jpg";
bannerIndex.style.width = "290px";
bannerIndex.style.height = "55px";
urlLink.appendChild(bannerIndex); //Here is the other problem
bannerAd.appendChild(urlLink); //All these weren't appended
bannerBox.appendChild(bannerAd); // to each other
}
setInterval((function () {
changeBannerAd();
}()), 10000);
}
addEvent(window, "load", makeBannerAds(), false);
Secondly, not to be picky or anything but you should probably declare the functions you pass into setInterval or setTimeout as variables rather than explicit functions or run them through an anonymous function like I have done. These two functions use a form of eval, and as we all know eval is evil, eval is evil, and eval is evil
Old answer; ignore
Question: Is your ads.js added before or after banners.js
Try adding the script tag before banners.js
I just placed the ads.js content above the banners.js script in a jsFiddle and it worked just fine for me
Check the JS Fiddle for full code at the top.

Categories

Resources