JavaScript Sudoku ID fields not registering - javascript

I decided to see if I can create an online Sudoku game using HTML, JavaScript, CSS and PHP. So far, I've created the grid but I'm stumped as to why when I try to use an alert box to show their input, I'm either getting "undefined" (when I use .value), blank (when I use .innerText) or the HTML object (when I use .innerHTML). Either I'm missing my coffee but I cannot figure out why neither seem to be working.
My intention is when the user clicks on "Evaluate!", each of the hidden fields (1 for each row) will be populated in a comma-separated format. PHP will receive the content and can break it apart using explode(",", $row), allowing each to be compared as separate arrays against each other. But that's for later.
To save time when reading my code, the problematic area seems to be within the initGrid() function as that's where I'm creating the attributes. I should note, I've checked the console log and there are no errors. Also, I'm trying to do all of this using only JavaScript, not jQuery.
Here's a JSFiddle, although for some reason, my alert boxes aren't working in it but they are in my browser (Chrome, same browser I'm using for JSFiddle).
Here is the troublesome initGrid() function:
function initGrid() {
var table = document.getElementById("mainTable").getElementsByTagName("tbody")[0];
var atts = ["a", "b", "c", "d", "e", "f", "g", "h", "i"];
for (var i = 0; i < atts.length; i++) {
var newRow = table.insertRow(i);
for (var j = 0; j < 9; j++) {
var newCell = newRow.insertCell(j);
newCell.innerHTML = document.getElementById("defaultButtons").innerHTML;
newCell.setAttribute("name", atts[i] + j);
newCell.setAttribute("id", atts[i] + j);
newCell.setAttribute("value", "");
newCell.setAttribute("onKeyUp", "appendData(this.id, this)");
}
}
}

It maybe isn't clear from your fiddle - but from clicking the "Evaluate" button populateAllHidden() is never being called. In Chrome there is an error logged in the console:
Uncaught ReferenceError: populateAllHidden is not defined
Instead of using onclick in the button:
<button type="button" onClick="populateAllHidden()">Evaluate!</button>
You can give it an ID, and then register an event listener at the same time you initialize the grid. So change the button to:
<button type="button" id="evaluateButton">Evaluate!</button>
In the onload, add the event listener:
window.onload = function () {
initGrid();
document.getElementById("evaluateButton").addEventListener("click", populateAllHidden, false);
};
Give that a go - it worked for me!

After a nice long nap (had only a few hours of sleep when I tried to create the sudoku puzzle), I re-visited it and realized how much of a mess it was. I've since made much more progress and am working on the PHP aspect of it to generate a puzzle. There's also a simple on-screen verification that tells the user whether their input was valid (i.e. a number) or not. Hopefully it can also help someone else, below is sudokuGrid.php:
I just finished writing the verify function and I still have to sort out a few things with it.
<!DOCTYPE html>
<html>
<head>
<meta charset = "UTF-8" />
<title>Online Sudoku</title>
<script type = "text/javascript">
function initGrid() {
var tBody = document.getElementById("mainTable").getElementsByTagName("tbody")[0];
var rowLetters = ["a", "b", "c", "d", "e", "f", "g", "h", "i"];
for(var i = 0; i < rowLetters.length; i++) {
var newRow = tBody.insertRow(i);
var rowLabel = newRow.insertCell(0);
rowLabel.innerHTML = rowLetters[i];
rowLabel.style.padding = "0px 4px 0px 4px";
rowLabel.style.fontWeight = "bold";
for(var j = 1; j < 10; j++) {
var newCell = newRow.insertCell(j);
var newName = rowLetters[i] + j;
newCell.innerHTML = "<input type = 'text' class = 'sudokuCells' value = '' name = " + newName + " maxLength = '1' onInput = 'verify(this)' id = " + newName + " />";
}
}
}
function verify(x) {
var valid = document.getElementById("valid");
var invalid = document.getElementById("invalid");
valid.style.visibility = "hidden";
invalid.style.visibility = "hidden";
if(!isNaN(parseInt((x.value).slice(0, 1)))) {
valid.style.visibility = "visible";
invalid.style.visibility = "hidden";
} else if(((x.value).slice(0, 1)).trim().length == 0) {
invalid.style.visibility = "hidden";
valid.style.visibility = "hidden";
} else {
invalid.style.visibility = "visible";
valid.style.visibility = "hidden";
alert("Sorry, that was an invalid character");
x.value = "";
}
}
function populateAllHidden() {
var rowLetters = ["a", "b", "c", "d", "e", "f", "g", "h", "i"];
for(var i = 0; i < rowLetters.length; i++) {
var hiddenRow = document.getElementById(rowLetters[i] + "_row");
for(var j = 1; j < 10; j++) {
if(j == 1) {
hiddenRow.value = document.getElementById(rowLetters[i] + j).value + ",";
continue;
} else if(j != 9) {
hiddenRow.value += document.getElementById(rowLetters[i] + j).value + ",";
continue;
} else {
hiddenRow.value += document.getElementById(rowLetters[i] + j).value;
}
}
}
document.getElementById("mainForm").submit();
}
window.onload = function() {
initGrid();
}
</script>
<style>
.sudokuCells
{
width: 15px;
}
#valid
{
color: #00FF00;
visibility: hidden;
}
#invalid
{
color: #FF0000;
visibility: hidden;
}
</style>
</head>
<body>
<div id = "mainTableContainer">
<table border = "1" cellpadding = "0" cellspacing = "0" id = "mainTable">
<thead>
<tr>
<th></th>
<th>a</th>
<th>b</th>
<th>c</th>
<th>d</th>
<th>e</th>
<th>f</th>
<th>g</th>
<th>h</th>
<th>i</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<div id = "statusContainer">
<p><strong><span id = "valid">Valid</span> <span id = "invalid">Invalid</span></strong></p>
</div>
<form action = "evaluate.php" method = "post" id = "mainForm" >
<input type = "hidden" name = "a_row" id = "a_row" value = "" />
<input type = "hidden" name = "b_row" id = "b_row" value = "" />
<input type = "hidden" name = "c_row" id = "c_row" value = "" />
<input type = "hidden" name = "d_row" id = "d_row" value = "" />
<input type = "hidden" name = "e_row" id = "e_row" value = "" />
<input type = "hidden" name = "f_row" id = "f_row" value = "" />
<input type = "hidden" name = "g_row" id = "g_row" value = "" />
<input type = "hidden" name = "h_row" id = "h_row" value = "" />
<input type = "hidden" name = "i_row" id = "i_row" value = "" />
</form>
<button type = "button" onClick = "populateAllHidden()" >Evaluate!</button>
</body>

Related

How to get filter value for each effect?

How to get filter value for each effect with % and px and only numbers without % and px.
In the codec I have listed 3 filters (of course there may be more).
What is the best way?
<button onclick="myFunction()">Try it</button><br><br>
<img id="myImg"
src="https://www.roadrunnerrecords.com/sites/g/files/g2000005056/f/sample-4.jpg"
width="300"
height="300"
style="filter:grayscale(100%) blur(5px) brightness(150%)" />
function myFunction() {
var grayscale = document.getElementById("myImg").style.filter;
var blur = document.getElementById("myImg").style.filter;
var brightness = document.getElementById("myImg").style.filter;
alert("grayscale value = , blur value= , brightness value= "); //without % and px
alert("grayscale value = , blur value= , brightness value= "); //with % and px
}
function myFunction() {
var effects = document.getElementById("myImg").style.filter.split(" ");
var imgFilter = {};
for (var i = 0; i < effects.length; ++i) {
var split = effects[i].split("(");
imgFilter[split[0]] = split[1].substring(0,split[1].length-1);
}
alert("grayscale value = "+imgFilter.grayscale+" , blur value= "+imgFilter.blur+", brightness value= "+imgFilter.brightness);//with % and px
alert("grayscale value = "+imgFilter.grayscale.replace(/[^\d.]/g,"")+" , blur value= "+imgFilter.blur.replace(/[^\d.]/g,"")+", brightness value= "+imgFilter.brightness.replace(/[^\d.]/g,""));//without % and px
} // How to add Hue-rotate???
Using string parsing techniques to separate out the needed parts and create an object:
function myFunction() {
var element = document.getElementById("myImg");
// split filter string into an array of effects
var effects = element.style.filter.split(" ");
var imgFilter = {};
for (var i = 0; i < effects.length; ++i) {
// use regex to match value before parenthesis and value inside
var matches = effects[i].match(/(.*)\((.*)\)/);
// create a key with the effect name (ex. "grayscale")
imgFilter[matches[1]] = {};
// set the withUnits value to the number that is in the parenthesis
imgFilter[matches[1]]["withUnits"] = matches[2];
// remove characters that are not digits or periods using regex
imgFilter[matches[1]]["withoutUnits"] = matches[2].replace(/[^\d.]/g,"");
}
//with % and px
for (var i = 0, log = ""; i < Object.keys(imgFilter).length; ++i) {
log += Object.keys(imgFilter)[i] + " value = " + imgFilter[Object.keys(imgFilter)[i]].withUnits + ", ";
}
alert(log);
//without % and px
for (var i = 0, log = ""; i < Object.keys(imgFilter).length; ++i) {
log += Object.keys(imgFilter)[i] + " value = " + imgFilter[Object.keys(imgFilter)[i]].withoutUnits + ", ";
}
alert(log);
}
<button onclick="myFunction()">Try it</button><br><br>
<img id="myImg"
src="https://www.roadrunnerrecords.com/sites/g/files/g2000005056/f/sample-4.jpg"
width="300"
height="300"
style="filter:grayscale(100%) blur(5px) brightness(150%) hue-rotate(180deg)" />
For the effects: "grayscale(100%) blur(5px) brightness(150%)", the object imgFilter that is created has these value:
{
"grayscale": {
"withUnits": "100%",
"withoutUnits": "100"
},
"blur": {
"withUnits": "5px",
"withoutUnits": "5"
},
"brightness": {
"withUnits": "150%",
"withoutUnits": "150"
}
}
You can access any particular value by using, for example imgFilter.grayscale.withUnits to get "100%" or imgFilter.blur.withoutUnits to get "5".
For accessing effects that contain hyphens (such as hue-rotate), you will need to access the value using quotes and brackets, for example, imgFilter["hue-rotate"].withUnits.
Adding hue-rotate to the version you are using in your edit:
function myFunction() {
var effects = document.getElementById("myImg").style.filter.split(" ");
var imgFilter = {};
for (var i = 0; i < effects.length; ++i) {
var split = effects[i].split("(");
imgFilter[split[0]] = split[1].substring(0,split[1].length-1);
}
alert("hue-rotate value = "+imgFilter["hue-rotate"]+" , grayscale value = "+imgFilter.grayscale+" , blur value= "+imgFilter.blur+", brightness value= "+imgFilter.brightness);//with % and px
alert("hue-rotate value = "+imgFilter["hue-rotate"].replace(/[^\d.]/g,"")+" , grayscale value = "+imgFilter.grayscale.replace(/[^\d.]/g,"")+" , blur value= "+imgFilter.blur.replace(/[^\d.]/g,"")+", brightness value= "+imgFilter.brightness.replace(/[^\d.]/g,""));//without % and px
}
<button onclick="myFunction()">Try it</button><br><br>
<img id="myImg"
src="https://www.roadrunnerrecords.com/sites/g/files/g2000005056/f/sample-4.jpg"
width="300"
height="300"
style="filter:grayscale(100%) blur(5px) brightness(150%) hue-rotate(180deg)" />
You'll need to parse it manually somehow, regex will do:
let filter = document.getElementById("myImg").style.filter;
let filterProps = Object.fromEntries(filter.split(" ").map((v) => {let m=v.match(/([a-z-]+)\((\d+)(%|px)\)/); return [m[1], m[2]]}));
filterProps.grayscale; // 100
filterProps.blur; // 5
filterProps.brightness; // 150

Improving Secure Password Generator

Simple Password Generator Example:
function randomPassword() {
var chars = "abcdefghijklmnopqrstuvwxyz" +
"ABCDEFGHIJKLMNOP" +
"1234567890" +
"#\#\-!$%^&*()_+|~=`{}\[\]:\";'<>?,.\/",
pass = "",
PL = 10;
for (var x = 0; x < PL; x++) {
var i = Math.floor(Math.random() * chars.length);
pass += chars.charAt(i);
}
return pass;
}
function generate() {
myform.row_password.value = randomPassword();
}
<form name="myform" method="post" action="">
<table width="100%" border="0">
<tr>
<td>Password:</td>
<td>
<input name="row_password" type="text" size="40">
<input type="button" class="button" value="Generate" onClick="generate();" tabindex="2">
</td>
</tr>
</table>
</form>
Improving Functionality Questions
1). Obtaining All Values Within Variable
Taking the base script above, how can I call chars.length and chars.charAt(i) where chars equals all the values within Chars?
var Chars = {};
Chars.abc = "abcdefghijklmnopqrstuvwxyz";
Chars.ABE = "ABCDEFGHIJKLMNOP";
Chars.Num = "1234567890";
Chars.Sym = "#\#\-!$%^&*()_+|~=`{}\[\]:\";'<>?,.\/";
2). Implementing a checkbox system for less advanced password
To generate a less advanced password, such as not including symbox via unchecking a checkbox, how can I make it so only Chars.abc, Chars.ABE, and Chars.Num values are used?
3). Equally Divide Password Length By Chars
Round down (Password length / Chars used ), ie; the example used in this question generates a 10 character password and uses all charecters, therefore there would be a minimum of 2 of each Chars.
The 3rd functionality is missing and will probably be way more sophisticated. But this is a simple solution to the 1st and 2nd ones.
var output = document.getElementsByTagName('output')[0];
var Chars = {};
Chars.length = 16;
Chars.abc = "abcdefghijklmnopqrstuvwxyz";
Chars.ABE = "ABCDEFGHIJKLMNOP";
Chars.Num = "1234567890";
Chars.NumRequired = true;
Chars.Sym = "#\#\-!$%^&*()_+|~=`{}\[\]:\";'<>?,.\/";
var generator = new randomPasswordGenerator(Chars);
var simpleGenerator = new randomPasswordGenerator({
length: 6,
abc: 'abc',
Num: '0'
});
var button = document.getElementsByTagName('button')[0];
button.addEventListener('click', clickFunction);
var checkbox = document.getElementsByTagName('input')[0];
function clickFunction () {
if (checkbox.checked) output.textContent = simpleGenerator.randomPassword();
else output.textContent = generator.randomPassword();
}
function randomPasswordGenerator(opts) {
for(var p in opts) this[p] = opts[p];
this.randomPassword = randomPassword;
}
function randomPassword() {
var chars = (this.abc || "") +
(this.ABE || "") +
(this.Num || "") +
(this.Sym || ""),
pass = [],
PL = this.length;
if (this.NumRequired) {
var r = Math.floor(Math.random() * this.Num.length);
var i = Math.floor(Math.random() * PL);
pass[i] = this.Num[r];
}
for (var x = 0; x < PL; x++) {
if(!pass[x]) {
var i = Math.floor(Math.random() * chars.length);
pass[x] = chars.charAt(i);
}
}
return pass.join('');
}
output {
margin: 12px;
display: block;
border-bottom: 1px solid
}
<button>Generate</button>
<input type="checkbox">Simple
<output></output>

Matching radio button selection with nested Array content in Javascript

UPDATE 6-25-2014
Any insight would be appreciated!
UPDATE 6-21-2014
I tried to make the radio variables, global so the 'if block' in the 'answerFwd' function could be compared to the correctAnswer Array, but that didn't work!
UPDATE 6-16-2014
ADDED JS FIDDLE
I am building a quiz and creating an array of radio buttons dynamically, and would like to match the selected button with the correct answer I have established in the question array.
html
<div id="responses">
<input type="radio" name="choices" class="radioButtons" value="0" id="choice0">
<div id="c0" class="choiceText">The Observers</div>
<input type="radio" name="choices" class="radioButtons" value="1" id="choice1">
<div id="c1" class="choiceText">The Watchers </div>
<input type="radio" name="choices" class="radioButtons" value="2" id="choice2">
<div id="c2" class="choiceText">The Sentinels</div>
<input type="radio" name="choices" class="radioButtons" value="3" id="choice3">
<div id="c3" class="choiceText">The Oa</div>
</div>
questions:
var allQuestions = [{
"question": "Who was Luke's wingman in the battle at Hoth?",
"choices": ["Dak", "Biggs", "Wedge", "fx-7"],
"correctAnswer": 0 }, {
"question": "What is the name of Darth Vader's flag ship?",
"choices": ["The Avenger", "Devastator ", "Conquest", "The Executor"],
"correctAnswer": 3 },{},{} //other questions];
var item = allQuestions[0];
var currentQuestion = 0;
var playersScore = 0;
//function which creates the buttons
function createRadioButtonFromArray(array) {
var len = array.length;
var responses = document.getElementById("responses");
responses.innerHTML = '';
for (var i = 0; i < len; i++) {
radio = document.createElement("input"); //Updated 6-21-2014 removed 'var'
radio.type = "radio";
radio.name = "choices";
radio.className = "radioButtons";
radio.value = i;
radio.id = "choice" + i;
ar radioText = document.createElement("div");
radioText.id = "c" + i;
radioText.className = "choiceText";
radioText.innerHTML = array[i];
responses.appendChild(radio);
responses.appendChild(radioText);
}
}
function answerFwd() {
var answerOutput = " ";
var itemAnswers = allQuestions;
var playerTally = 0; //Updated 6-9-2014
var playerFeedback = " "; //Updated 6-9-2014
var playerMessage = document.getElementById("playerMessage"); //Updated 6-9-2014
if (currentAnswer <= itemAnswers.length) {
currentAnswer++;
}
createRadioButtonFromArray(itemAnswers[currentQuestion].choices);
* Updated 6-9-2014 I am stumped; This doesn't work but I was encouraged I got a score tally on the page! Am I comparing the elements correctly? Updated 6-21-2014 This reversed the gain, where I had the tally render on the screen*
if (itemAnswers.correctAnswer === responses.id) { //Updated 6-21-2014
playerTally += 1;
playerFeedback += "<h5>" + playerTally + "</h5> <br/>";
playerMessage.innerHTML = playerFeedback;
}
}
At first I tried to debug this but had trouble finding where the error was coming from.
One thing I noticed was currentAnswer variable was only being set once. (when it was declared)
Another thing that would make this cleaner is storing each response to each question as a property of the questions object.
For example: {"question": "What is the registry of the Starship Reliant?","choices": ["NX-01", "NCC-1864", "NCC-1701", "NCC-2000"],"correctAnswer": 1,"selectedAnswer": 0}
This is a good example of why you may want to use object oriented programming. You can keep the global namespace clean, while also having tighter control over your variables.
I put together this Quiz Code using some object oriented principles:
JavaScript
var Quiz = function(questions) {
this.questions = questions;
this.$template = {
"header": document.querySelector(".question"),
"options": document.querySelector(".question-choices")
};
this.init();
}
Quiz.prototype = {
"init": function() {
this.question = 0;
this.generateQuestion();
this.bindEvents();
},
//gets called when this.question == this.questions.length, calculates a score percentage and alerts it
"score": function() {
var correctCount = 0;
this.questions.forEach(function(question){
if ( (question.selectedAnswer || -1) === question.correctAnswer ) correctCount += 1
})
alert("Score: " + ((correctCount / this.questions.length) * 100) + "%")
},
//Gets called during initialization, and also after a nav button is pressed, loads the question and shows the choices
"generateQuestion": function() {
var question = this.questions[this.question];
this.$template.header.innerHTML = question.question;
this.$template.options.innerHTML = "";
question.choices.forEach(this.createRadio.bind(this));
},
//Binds the previous, and next event handlers, to navigate through the questions
"bindEvents": function() {
var _this = this,
$nextBtn = document.querySelector(".question-navigation--next"),
$prevBtn = document.querySelector(".question-navigation--prev");
$nextBtn.addEventListener("click", function(e) {
//Go to the next question
_this.question++;
if ( _this.question == _this.questions.length ) {
_this.score();
} else {
_this.generateQuestion();
}
});
$prevBtn.addEventListener("click", function(e) {
_this.question--;
if ( _this.question <= 0 ) _this.question = 0
_this.generateQuestion();
});
},
//Create each individual radio button, is callback in a forEach loop
"createRadio": function(choice, index) {
var question = this.questions[this.question];
var radio = document.createElement("input");
radio.type = "radio";
radio.name = "options";
radio.id = "option-"+index;
if ( question.selectedAnswer === index ) {
radio.checked = true;
}
radio.addEventListener("click", function(e) {
question.selectedAnswer = index;
})
var radioText = document.createElement("label");
radioText.setAttribute("for", "option-"+index)
radioText.innerHTML = choice;
radioText.insertBefore(radio, radioText.firstChild);
this.$template.options.appendChild(radioText);
}
}
var q = new Quiz(allQuestions)

Using for loop to generate text boxes

I want to be able to enter a number into a text box and then on a button click generate that number of text boxes in another div tag and automatically assign the id
Something like this but not sure how to generate the text boxes and assign automatically assign the id
function textBox(selections) {
for (i=0; i < selections +1; i++) {
document.getElementById('divSelections').innerHTML = ("<form><input type="text" id="1" name=""><br></form>");
}
}
Try this one:
function textBox(selections){
selections = selections*1; // Convert to int
if( selections !== selections ) throw 'Invalid argument'; // Check NaN
var container = document.getElementById('divSelections'); //Cache container.
for(var i = 0; i <= selections; i++){
var tb = document.createElement('input');
tb.type = 'text';
tb.id = 'textBox_' + i; // Set id based on "i" value
container.appendChild(tb);
}
}
A simple approach, which allows for a number to be passed or for an input element to be used:
function appendInputs(num){
var target = document.getElementById('divSelections'),
form = document.createElement('form'),
input = document.createElement('input'),
tmp;
num = typeof num == 'undefined' ? parseInt(document.getElementById('number').value, 10) : num;
for (var i = 0; i < num; i++){
tmp = input.cloneNode();
tmp.id = 'input_' + (i+1);
tmp.name = '';
tmp.type = 'text';
tmp.placeholder = tmp.id;
form.appendChild(tmp);
}
target.appendChild(form);
}
Called by:
document.getElementById('create').addEventListener('click', function(e){
e.preventDefault();
appendInputs(); // no number passed in
});
JS Fiddle demo.
Called by:
document.getElementById('create').addEventListener('click', function(e){
e.preventDefault();
appendInputs(12);
});
JS Fiddle demo.
The above JavaScript is based on the following HTML:
<label>How many inputs to create:
<input id="number" type="number" value="1" min="0" step="1" max="100" />
</label>
<button id="create">Create inputs</button>
<div id="divSelections"></div>
See below code sample :
<asp:TextBox runat="server" ID="textNumber"></asp:TextBox>
<input type="button" value="Generate" onclick="textBox();" />
<div id="divSelections">
</div>
<script type="text/javascript">
function textBox() {
var number = parseInt(document.getElementById('<%=textNumber.ClientID%>').value);
for (var i = 0; i < number; i++) {
var existingSelection = document.getElementById('divSelections').innerHTML;
document.getElementById('divSelections').innerHTML = existingSelection + '<input type="text" id="text' + i + '" name=""><br>';
}
}
</script>
Note: Above code will generate the N number of textboxes based on the number provided in textbox.
It's not recommended to user innerHTML in a loop :
Use instead :
function textBox(selections) {
var html = '';
for (i=0; i < selections +1; i++) {
html += '<form><input type="text" id="'+i+'" name=""><br></form>';
}
document.getElementById('divSelections').innerHTML = html;
}
And be carefull with single and double quotes when you use strings
You have to change some code snippets while generating texboxes, Learn use of + concatenate operator, Check code below
function textBox(selections) {
for (var i=1; i <= selections; i++) {
document.getElementById('divSelections').innerHTML += '<input type="text" id="MytxBox' + i + '" name=""><br/>';
}
}
textBox(4); //Call function
JS Fiddle
Some points to taken care of:
1) In for loop declare i with var i
2) your selection + 1 isn't good practice at all, you can always deal with <= and < according to loop's staring variable value
3) += is to append your new HTML to existing HTML.
ID should be generate manually.
var inputName = 'divSelections_' + 'text';
for (i=0; i < selections +1; i++) {
document.getElementById('divSelections').innerHTML = ("<input type='text' id= " + (inputName+i) + " name=><br>");
}
edit : code formated
Instead of using innerHTML, I would suggest you to have the below structure
HTML:
<input type="text" id="id1" />
<button id="but" onclick="addTextBox(this)">click</button>
<div id="divsection"></div>
JS:
function addTextBox(ops) {
var no = document.getElementById('id1').value;
for (var i = 0; i < Number(no); i++) {
var text = document.createElement('input'); //create input tag
text.type = "text"; //mention the type of input
text.id = "input" + i; //add id to that tag
document.getElementById('divsection').appendChild(text); //append it
}
}
JSFiddle

Dynamic Div ID and Creating Elements Inside it

I am creating a dynamic Div where i can import values from the showModalDialog when it is closed. So after closing the modal, i get couple of values.
What i am trying to do here is:
I have couple of dynamic div's and against each div, i have a link to open a window.
After selection of the files they are return back to the parent window as comma separated.
I want to insert those values inside the div to which that popup was opened. but in this scenario i am facing the trouble. the Divid's are generated dynamically
Here is the Complete Code for Javascript + Jquery Based, I am getting the following error.
TypeError: theDiv.appendChild is not a function
[Break On This Error]
theDiv.appendChild(newNode);
<script type="text/javascript" src="JS/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
function eliminateDuplicates(arr,divID)
{
var i,
len=arr.length,
out=[],
obj={};
for (i=0;i<len;i++)
{
obj[arr[i]]=0;
}
for (i in obj)
{
out.push(i);
}
return out;
}
function GetElementsStartingWith(tagName, subString) {
var elements = document.getElementsByTagName(tagName);
var result = [];
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
if (element.id && element.id.substr(0, subString.length) == subString) {
result.push(element);
}
}
return result;
}
Test= function(str,divID)
{
var arrID = new Array();
arrID = str.split(',');
arrID = eliminateDuplicates(arrID);
var theDiv = $("#projectsList"+divID).attr('id'); //document.getElementById('projectsList');
alert(theDiv);
var cmp= $("#projectIDS"+divID).val(); //document.getElementById("projectIDS").value;
var cnp = $("#countProj"+divID);//document.getElementById("countProj")
var cproj;
if(cnp.val().length == 0)
cproj=0;
else
cproj=parseInt(cnp.val());
for (var j=0; j<arrID.length; j++)
{
if (parseInt(cproj) + 1 > 50)
{
alert("You cannot add more than 50 Project id's ");
return;
}
if( cmp!="" && cmp.indexOf(arrID[j])!=-1)
continue;
var newNode = document.createElement('div');
newNode.style.cssText = "background:#CCCCCC;border:1px solid #666666;width:100px;word-wrap:break-word;margin:3px;float:left;color:black;text-decoration:none!important;height:auto;vertical-align:middle;padding-top:2px;";
newNode.title = arrID[j]+" ";
newNode.innerHTML = '<input type=hidden name=Proj_' + j + ' ' + 'value=' + arrID[j] + '>' + arrID[j] + ' <b>X</b>';
theDiv.appendChild(newNode);
if(cmp.length == 0)
{
//document.getElementById("projectIDS").value=arrID[j]
$("#projectIDS"+divID).val(arrID[j]);
}
else
{
//document.getElementById("projectIDS").value = document.getElementById("projectIDS").value+","+arrID[j];
$("#projectIDS"+divID).val($("#projectIDS"+divID).val()+","+arrID[j]);
}
cproj = parseInt(cproj)+1;
//document.getElementById("countProj").value =cproj;
cnp.value(cproj);
}
}
removetext = function(par)
{
var strremove=par.text();
var strexist = document.getElementById("projectIDS").value;
strremove = strremove.replace(" X","");
tempRemove(strexist, strremove);
par.remove();
var cproj;
if(document.getElementById("countProj").value.length == 0)
cproj=0;
else
{cproj=parseInt(document.getElementById('countProj').value);
cproj=parseInt(cproj)-1;}
document.getElementById("countProj").value =cproj;
}
function tempRemove(strexist,strremove)
{
var b = strexist.indexOf(strremove);
var after = strexist.indexOf(",",b);
var newstrexist;
var before = strexist.lastIndexOf(",",b);
if(after!=-1)
{newstrexist=strexist.replace(strremove+',',"");}
else if(before!=-1)
{newstrexist=strexist.replace(','+strremove,"");}
else
{newstrexist= strexist.replace(strremove,"");}
document.getElementById("projectIDS").value=newstrexist;
//remove current friend
}
function openWindow(divID)
{
var lookUpAlys=window.showModalDialog("files.cfm?d=" + Math.random() + '&fileID=' + divID,window,"center=yes;dialogWidth:895px:dialogHeight:785px;status:no");
if(lookUpAlys.forename!=undefined)
{
var temp = lookUpAlys.forename;
Test(temp,divID);
}
}
</script>
</head>
<body>
<table width="100%" border="0" cellspacing="2" cellpadding="1">
<tr>
<td>Choose</td>
<td>Files</td>
<td>Action</td>
</tr>
<cfloop from="1" to="5" index="i">
<cfoutput>
<tr>
<td><input type="checkbox" name="getFile" id="getFile" value="#i#" /></td>
<td><div id="projectsList#i#" style="width:500px;height:60px;overflow-y:scroll;border:1px solid gray;"></div><input type="text" name="projectIDS#i#" id="projectIDS#i#" data-id="#i#" value="" /><input type="text" data-id="#i#" name="countProj#i#" id="countProj#i#" value="" /></td>
<td>Files</td>
</tr>
</cfoutput>
</cfloop>
</table>
</body>
</html>
so my apologies if i had entered the code incorrectly. Basically trying do it Classic Javascript Way
This does not do what I think you think it does:
var theDiv = $("#projectsList"+divID).attr('id'); //document.getElementById('projectsList');
You should do
var theDiv = $("#projectsList"+divID)[0];
to get the DOM element.
Or, for this scenario, just do
var theDiv = document.getElementById("projectsList" + divID);
Also, I'm not sure why you are mixing raw DOM operations and jQuery wrapped operations everywhere. Just stick to one of them, and be consistent.
var container = $('.itemsList');
var divSubmit = $(document.createElement('div'));
//assigning id to div
$(divSubmit).attr('id','itemTemplate');
$(divSubmit).css({"font-family":"Gotham, Helvetica Neue, Helvetica, Arial, sans-serif","position":"relative","height": "70px","clear" : "both","background-color":"#FFF","border-bottom": "0.09em solid #EBEBEB"});
//adding class to main container
$(divSubmit).addClass('itemTemplate');
//adding Child's name label and assigning id to it.
var Name = '<label class="lblName" id="lblName" for="Name">'+getName()+'</label>';
$(divSubmit).append(Name);
$(divSubmit).append(container);
Here's a sample code. first of all there is sample container called itemslist
that will contain the generated div.
divSubmit will be gernerate dynamically and append to container.
To find some div for click event. Lets say we want to get child name.
alert($($(this).find("label.lblName")).val());

Categories

Resources