code after while loop not Working - javascript

<script type="text/javascript">
function prepare_values()
{ldelim}
var flag= true;
var i=0;
var total_questions = new Array();
var total_answer = new Array();
while(flag)
{ldelim}
var questions = document.getElementById("question_div_"+i);
if (questions == null)
{ldelim}
flag=false;
alert("Value of flag = "+flag);
{rdelim}
var answer = document.getElementById("answer_div_"+i);
total_questions[i]=questions.firstChild.innerHTML;
if(answer.firstChild.attributes['type'].value == 'text')
{ldelim}
total_answer[i]=answer.firstChild.nodeValue;
{rdelim}
if(answer.firstChild.attributes['type'].value == 'textarea')
{ldelim}
total_answer[i]=answer.firstChild.nodeValue;
{rdelim}
if(answer.firstChild.attributes['type'].value == 'radio_div')
{ldelim}
var radio_button_parent = document.getElementById(answer.firstChild.id);
var oRadio = document.getElementsByName(radio_button_parent.firstChild.name);
for(var k = 0; k < oRadio.length; k++)
{ldelim}
if(oRadio[k].checked)
{ldelim}
var radio_button_value = document.getElementById(oRadio[k].id);
alert("From inside of ever = "+radio_button_value.nextSibling.innerHTML);
total_answer[i]=radio_button_value.nextSibling.innerHTML;
{rdelim}
{rdelim}
{rdelim}
i=i+1;
{rdelim}
alert("hello");
{rdelim}
</script>
The above is my JS code which is running in a SMARTY template file on click of a button. The Code is Working Fine except that It Does not Run the Third Last Line i.e alert("Hello"); any thing after the {redelim} is neglected. What to do ?
here is the code from the firebug:
<script type="text/javascript">
function prepare_values()
{
var flag= true;
var i=0;
var total_questions = new Array();
var total_answer = new Array();
while(flag)
{
var questions = document.getElementById("question_div_"+i);
if (questions == null)
{
flag=false;
alert("Value of flag = "+flag);
}
var answer = document.getElementById("answer_div_"+i);
total_questions[i]=questions.firstChild.innerHTML;
if(answer.firstChild.attributes['type'].value == 'text')
{
total_answer[i]=answer.firstChild.nodeValue;
}
if(answer.firstChild.attributes['type'].value == 'textarea')
{
total_answer[i]=answer.firstChild.nodeValue;
}
if(answer.firstChild.attributes['type'].value == 'radio_div')
{
var radio_button_parent = document.getElementById(answer.firstChild.id);
var oRadio = document.getElementsByName(radio_button_parent.firstChild.name);
for(var k = 0; k < oRadio.length; k++)
{
if(oRadio[k].checked)
{
var radio_button_value = document.getElementById(oRadio[k].id);
alert("From inside of ever = "+radio_button_value.nextSibling.innerHTML);
total_answer[i]=radio_button_value.nextSibling.innerHTML;
}
}
}
i=i+1;
}
alert("hello");
}
</script>

I dont Know what is the issue in the code and why its not working as it is supposed to but this is how I got my code straight.
This is the new working code :
function prepare_values()
{
var flag= true;
var i=0;
var total_questions = new Array();
var total_answer = new Array();
while(flag)
{
var questions = document.getElementById("question_div_"+i);
if (questions == null)
{
break;
}
var answer = document.getElementById("answer_div_"+i);
total_questions[i]=questions.firstChild.innerHTML;
if(answer.firstChild.attributes['type'].value == 'text')
{
total_answer[i]=answer.firstChild.nodeValue;
}
if(answer.firstChild.attributes['type'].value == 'textarea')
{
total_answer[i]=answer.firstChild.nodeValue;
}
if(answer.firstChild.attributes['type'].value == 'radio_div')
{
var radio_button_parent = document.getElementById(answer.firstChild.id);
var oRadio = document.getElementsByName(radio_button_parent.firstChild.name);
for(var k = 0; k < oRadio.length; k++)
{
if(oRadio[k].checked)
{
var radio_button_value = document.getElementById(oRadio[k].id);
alert("From inside of ever = "+radio_button_value.nextSibling.innerHTML);
total_answer[i]=radio_button_value.nextSibling.innerHTML;
}
}
}
i=i+1;
}
alert("hello");
}
All I did is I replaced
if (questions == null)
{
flag=false;
alert("Value of flag = "+flag);
}
with
if (questions == null)
{
break;
}
Though My problem is Solved I still want to know why my previous code was not working because it was still suppose to work as it was correct. If anyone can point out the problem please do so I will appreciate it.

Related

sweetalert not working in Firefox only

I have used SweetAlert for showing alerts of validation and the code is below however its not working properly only in firefox. The alertbox starts appearing and then disappears and Javascript is bascially hung from that point. The code is as follows:
jQuery('.enroll-button').click(function (e) {
e.preventDefault();
var l = Ladda.create(this);
var tLeadType = jQuery('input[name="radioOpt"]:checked', '#sellBuyOpt').val()
var nSourceId = 0;
<?php if (isset($_GET["nsourceid"])){
echo 'nSourceId = '.$_GET["nsourceid"];
} ?>
var inputElements = [];
var tFirstName = jQuery("#firstName");
var tLastName = jQuery("#lastName");
var tEmailAddress = jQuery("#email");
var tCity = jQuery("#city");
var tState = jQuery("#state");
var tPhoneNumber = jQuery("#phoneNumber");
inputElements.push(tFirstName);
inputElements.push(tLastName);
inputElements.push(tEmailAddress);
inputElements.push(tCity);
inputElements.push(tState);
inputElements.push(tPhoneNumber);
//validations
var validated = true;
for(var i= 0; i < inputElements.length; i++){
if(inputElements[i].val().trim()===""){
inputElements[i].val("");
inputElements[i].attr("placeholder","This is required");
inputElements[i].css("border-color","#A33643");
validated = false;
}
if(i == 2){
var res = validateEmail(inputElements[i].val());
if(!res){
inputElements[i].val("");
inputElements[i].attr("placeholder","Valid Email required");
inputElements[i].css("border-color","#A33643");
validated = false;
}
}
if(i == 4 && inputElements[i].val() == "Select a state"){
sweetAlert("Oops...", "Please select a valid state!", "error");
validated = false;
}
if(i == 5 && !simpleClientPhoneValidator(inputElements[i].val())){
inputElements[i].val("");
inputElements[i].attr("placeholder","Invalid Phone Number");
inputElements[i].css("border-color","#A33643");
validated = false;
}

Javascript array push issue or loop issue

When I'm running my code I'm going into 'do' loop, then I'm entering input 'new' and then trying to add new array, but for some reason my code starting looping in if(answ == "new"). What am I doing wrong?
Here is my code:
var answ;
var arr = [];
do{
answ = prompt("What would like to do?");
if(answ == "new"){
var add = prompt("Add new todo: ");
add = arr.push(answ);
}
else if(answ == "list"){
for(var i=0; i<arr.length; ++i){
answ = answ + arr[i] + '<br>';
}
}
else if(answ == "delete"){
var choose = prompt("Which one (index)?");
delete arr[choose];
}
}while(answ !== "quit")
Don't run in browser in current form (never ending loop)
See if this helps you Mark.
there were some errors with you logic and storing values and also you were not showing the values, if what I suggest is right.
var answ;
var arr = [];
do {
answ = prompt("What would like to do?");
if (answ == "new") {
var add = prompt("Add new todo: ");
arr.push(add);
} else if (answ == "list") {
var output = '';
for (var i = 0; i < arr.length; ++i) {
output += arr[i] + '\r\n';
}
alert('listing:' + '\r\n' + output );
} else if (answ == "delete") {
var choose = prompt("Which one (index)?");
arr.splice(choose,1);
} else {
if(answ !== "quit")
alert('option invalid!');
}
} while (answ !== "quit")

TicTacToe Game in javascript error

Hi I am a newbie in javascript and was trying to program a Tic Tac Toe game using pure javascript..I have implemented most of the part,but am getting stuck up while trying to figure out the winning combination..
I want to check the innerHtml after player has clicked on the element and want check if the sequence matches,So that I can declare a winner..
In doing so I have failed..The below is the code I have written:-
var tile = function(r,c){
this.row = r;
this.col = c;
};
var player = function(name, sign){
this.name = name;
this.sign = sign
};
var players =[];
players[0]= new player('Surya','X');
players[1]= new player('Darshan','0');
var playerCounter=0;
var board = function(){
this.tiles =[];
//create tic and toe tile array
this.init = function(){
for(var i = 0; i<3; i++)
for(var j=0; j<3; j++)
this.tiles.push(new tile(i,j));
};
//Draw the tic tac toc board
this.drawBoard = function(){
var boardDiv = document.createElement('div');
boardDiv.className = 'board';
boardDiv.setAttribute('id','board');
var row=0;
var rowDiv= [];
for(var i = 0; i<3; i++)
{
rowDiv[i] = document.createElement('div');
rowDiv[i].className = 'row';
}
//9 tiles
for(var i = 0; i<this.tiles.length; i++)
{
var tileDiv = document.createElement('span');
tileDiv.className = 'tile';
tileDiv.setAttribute('id','tile['+i+']');
tileDiv.setAttribute('data-row',this.tiles[i].row);
tileDiv.setAttribute('data-col',this.tiles[i].col);
tileDiv.addEventListener('click',function(){
this.innerHTML = players[playerCounter].sign;
playerCounter= 1- playerCounter;
});
rowDiv[row].appendChild(tileDiv);
if(i==2 || i==5 || i==8)
row++;
}
for(var i = 0; i<3; i++)
{
boardDiv.appendChild(rowDiv[i]);
}
document.body.appendChild(boardDiv);
this.checkWinner = function(tile,players){
for(var z=0;z<=1;z++){
if(tile[0].innerHTML == players[z].sign && <------ Getting Error Here
tile[1].innerHTML == players[z].sign &&
tile[2].innerHTML == players[z].sign)
return true;
if(tile[3].innerHTML == players[z].sign &&
tile[4].innerHTML == players[z].sign &&
tile[5].innerHTML == players[z].sign)
return true;
if(tile[6].innerHTML == players[z].sign &&
tile[7].innerHTML == players[z].sign &&
tile[8].innerHTML == players[z].sign)
return true;
if(tile[0].innerHTML == players[z].sign &&
tile[3].innerHTML == players[z].sign &&
tile[6].innerHTML == players[z].sign)
return true;
if(tile[1].innerHTML == players[z].sign &&
tile[4].innerHTML == players[z].sign &&
tile[7].innerHTML == players[z].sign)
return true;
if(tile[2].innerHTML == players[z].sign &&
tile[5].innerHTML == players[z].sign &&
tile[8].innerHTML == players[z].sign)
return true;
if(tile[0].innerHTML == players[z].sign &&
tile[4].innerHTML == players[z].sign &&
tile[8].innerHTML == players[z].sign)
return true;
if(tile[2].innerHTML == players[z].sign &&
tile[4].innerHTML == players[z].sign &&
tile[7].innerHTML == players[z].sign)
return true;
else
console.log("outside");
}
};
isGameOver = this.checkWinner(2,1);
console.log(isGameOver)
};
};
var myBoard = new board();
myBoard.init();
myBoard.drawBoard();
myBoard.checkWinner();
I have pointed out where I am getting the error.When trying to find the value of innerHtml am getting error..which is Cannot read property 'sign' of undefined
Please help me out
You have to pass the parameters to the function checkWinner: tile, players when you call the function.
var tile = new Tile(0,1);
var player = new player('jiraya','X');
var myBoard = new board();
myBoard.init();
myBoard.drawBoard();
myBoard.checkWinner(tile, player);

Edit ajax loaded content

I have a HTML that loads a table from another page. I've got the CSS to work properly, but I can't edit the table using jQuery when it's pooled by the script, only when I have the table directly on the page. I'm guessing that maybe my changes are running before the load? I don't know..
I want to let you know that I'm not a programmer my self, but more of a curious person. I've searched around and found some things, but the lack of knowledge doesn't let me implement them. Hope you can help me.
The Script I use to read the data from the other page (p1.html)
<script type="text/javascript">
var TimerLoad, TimerChange;
var MaxNum, Rafraichir, Changement, ClassementReduit, ClassementReduitXpremier;
var UrlRefresh, UrlChange;
Rafraichir = 30000;
Changement = 150000;
MaxNum = 1;
ClassementReduit = 0;
ClassementReduitXpremier = 10;
function Load(url, target) {
var xhr;
var fct;
if (UrlChange) url = UrlRefresh;
else UrlRefresh = url;
UrlChange = 0;
if (TimerLoad) clearTimeout(TimerLoad);
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP")
} catch (e) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP")
} catch (e2) {
try {
xhr = new XMLHttpRequest
} catch (e3) {
xhr = false
}
}
}
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200)
if (ClassementReduit == 0) document.getElementById(target).innerHTML = xhr.responseText;
else document.getElementById(target).innerHTML = ExtraireClassementReduit(xhr.responseText)
};
xhr.open("GET", url + "?r=" + Math.random(), true);
xhr.send(null);
fct = function() {
Load(url, target)
};
TimerLoad = setTimeout(fct, Rafraichir)
}
function ExtraireClassementReduit(Texte) {
var i, j, CompteurTD, CompteurTR;
var ColPosition, ColNumero, ColNom, ColEcart1er;
var Lignes;
var NouveauTexte;
CompteurTR = 0;
ColPosition = -1;
ColNumero = -1;
ColNom = -1;
ColEcart1er = -1;
Texte = Texte.substring(Texte.indexOf("<tr"));
Lignes = Texte.split("\r\n");
NouveauTexte = '<table width="100%" cellpadding="0" cellspacing="0">';
for (i = 0; i < Lignes.length; i++)
if (Lignes[i].substring(0, 3) == "<tr") {
NouveauTexte += Lignes[i];
CompteurTD = 0
} else if (Lignes[i].substring(0, 4) == "</tr") {
CompteurTR++;
if (CompteurTR == ClassementReduitXpremier + 1) break
} else if (Lignes[i].substring(0, 3) == "<td") {
if (CompteurTR == 0)
if (Lignes[i].indexOf("\"Id_Position\"") != -1) {
ColPosition = CompteurTD;
NouveauTexte += Lignes[i].replace(/ width=".*"/i, "")
} else if (Lignes[i].indexOf("\"Id_Numero\"") != -1) {
ColNumero = CompteurTD;
NouveauTexte += Lignes[i].replace(/ width=".*"/i, "")
} else if (Lignes[i].indexOf("\"Id_Nom\"") != -1) {
ColNom = CompteurTD;
NouveauTexte += Lignes[i].replace(/ width=".*"/i, "")
} else {
if (Lignes[i].indexOf("\"Id_Ecart1er\"") != -1) {
ColEcart1er = CompteurTD;
NouveauTexte += Lignes[i].replace(/ width=".*"/i, "")
}
} else if (CompteurTD == ColPosition || CompteurTD == ColNumero || CompteurTD == ColNom || CompteurTD == ColEcart1er) NouveauTexte += Lignes[i];
CompteurTD++
}
NouveauTexte += "</table>";
return NouveauTexte
}
function Change() {
var Num, Index;
if (document.forms["Changement"].chkChangement.checked) {
Index = UrlRefresh.indexOf(".");
Num = parseInt(UrlRefresh.substring(1, Index)) + 1;
if (Num > MaxNum) Num = 1;
UrlRefresh = "p" + Num + ".html";
UrlChange = 1;
fct = function() {
Change()
};
TimerChange = setTimeout(fct, Changement)
} else if (TimerChange) clearTimeout(TimerChange)
};
</script>
Loading the table into the body
$(document).ready(Load('p1.html', 'result'));
The code I need to run after (it works with the table directly on page or even on a button, but I can't get to work on page load)
function show_hide_column(col_id, do_show) {
var stl;
if (do_show) stl = 'block'
else stl = 'none';
var tbl = document.getElementsByTagName('table')[0];
var index = document.getElementById(col_id).cellIndex;
var rows = tbl.getElementsByTagName('tr');
for (var row = 0; row < rows.length; row++) {
var cels = rows[row].getElementsByTagName('td')
cels[index].style.display = stl;
}
}
function hide() {
show_hide_column("Id_Position", false);
show_hide_column("Id_Equipe", false);
show_hide_column("Id_Vehicule", false);
}
I fired a console.log() message for every stage of the previous code, to know when exactly the table was added to the page, to then hide the columns. Got it to work.

Only JavaScript Dynamic Array Field Validation

I think so there is a problem with for statement??
Adjusted code again, but not alert popup is all the time even if all the input fields got values?
Hello I am trying to validate a dynamic array of fields on a form:
<form onsubmit="return checkReq();">
<input value="" type="hidden" name="slider[]" id=""/>
</form>
with the following JavaScript, but it doesn't work? Could you tell me please what I am doing wrong.
<script language="javascript">
function checkReq () {
var boxes = document.getElementsByName("slider[]");
var ret = true;
for (var x = 0; x < boxes.length; x++) {
if(boxes[x].value == '' || '0'){
ret = false;
break;
} else {ret = true;}
}
if (ret == false)
{
alert('Problem'); return ret;
}
}
</script>
I think this might help.
function checkReq () {
var boxes = document.getElementsByName("slider[]");
var ret = true;
for (var x = 0; x < boxes.length; x++) {
if(boxes[x].value == '' || boxes[x].value == '0'){
ret = false;
break;
} else {ret = true;}
}
if (ret == false)
{
alert('Problem'); return ret;
}
}
You always return after the first loop, so it doesn't go through each element (and thus redundant), is this intended?
Try this
You are trying to compare element instead of it's value JSFIDDLE
function checkReq () {
var boxes = document.getElementsByName("slider[]");
for (var x = 0; x < boxes.length; x++) {
if(boxes[x].value == '' || boxes[x].value == '0'){
alert('Problem'); return false;
}
else {return true;}
}
}

Categories