Display a random string in a html form - javascript

I want to create a form where one of the values already has a random string filled in. I've tried PHP and javascript however it keeps displaying the variable name instead of the variable... Any help would be much as appreciated!
<form name="name" method="post" action="sendform.php">
<table width="450px">
<tr>
<td valign="top">
<label for="number">Number</label>
</td>
<td valign="top">
<input type="text" value="Insert random string here" maxlength="50" size="30">
</td>
</tr>
</table>
</form>
script:
<script>
function generateRandomString($length = 10) {
$characters =
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
</script>
php
function generateRandomString($length = 10) {
$characters =
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}

There are a lot of answers to this question, but none of them leverage a Cryptographically Secure Pseudo-Random Number Generator (CSPRNG).
The simple, secure, and correct answer is to use RandomLib and don't reinvent the wheel.
With a secure integer generator in place, generating a random string with a CSPRNG is a walk in the park.
function random_str($length, $keyspace = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
{
$str = '';
$max = mb_strlen($keyspace, '8bit') - 1;
for ($i = 0; $i < $length; ++$i) {
$str .= $keyspace[random_int(0, $max)];
}
return $str;
}
<form name="name" method="post" action="sendform.php">
<table width="450px">
<tr>
<td valign="top">
<label for="number">Number</label>
</td>
<td valign="top">
<input type="text" value="<?php echo random_str(10); ?>" maxlength="50" size="30">
</td>
</tr>
</table>
</form>

Do this
<?php $length = 10;
$randomString = substr(str_shuffle(str_repeat($x='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($length/strlen($x)) )),1,$length);
?>
<td valign="top">
<input type="text" value="<?php echo $randomString;?>" maxlength="50" size="30">
</td>
Output will be mix of number and alphabet like this: 10whDMtuLO
Also, set the length of the string in $length as per your need.

Try this..
<?php $rand = substr(str_shuffle("abcdefghijklmnopqrstuvwxyz"), 0, 7); ?>
.
.
.
<td valign="top">
<input type="text" value="<?php echo $rand; ?>" maxlength="50" size="30">
</td>

You can Refer this answer by Roko C. Buljan
function randNumber(len, an){
an = an&&an.toLowerCase();
var str="", i=0, min=an=="a"?10:0, max=an=="n"?10:62;
for(;i++<len;){
var r = Math.random()*(max-min)+min <<0;
str += String.fromCharCode(r+=r>9?r<36?55:61:48);
}
return str;
}
document.getElementById("foo").value = randNumber(10,'A');
<textarea id='foo' style='width:100%;height:200px'></textarea>

function for making sh1 hash
function sha1 ( str ) {
var rotate_left = function(n,s) {
var t4 = ( n<<s ) | (n>>>(32-s));
return t4;
};
var lsb_hex = function(val) {
var str="";
var i;
var vh;
var vl;
for( i=0; i<=6; i+=2 ) {
vh = (val>>>(i*4+4))&0x0f;
vl = (val>>>(i*4))&0x0f;
str += vh.toString(16) + vl.toString(16);
}
return str;
};
var cvt_hex = function(val) {
var str="";
var i;
var v;
for( i=7; i>=0; i-- ) {
v = (val>>>(i*4))&0x0f;
str += v.toString(16);
}
return str;
};
var blockstart;
var i, j;
var W = new Array(80);
var H0 = 0x67452301;
var H1 = 0xEFCDAB89;
var H2 = 0x98BADCFE;
var H3 = 0x10325476;
var H4 = 0xC3D2E1F0;
var A, B, C, D, E;
var temp;
str = this.utf8_encode(str);
var str_len = str.length;
var word_array = new Array();
for( i=0; i<str_len-3; i+=4 ) {
j = str.charCodeAt(i)<<24 | str.charCodeAt(i+1)<<16 |
str.charCodeAt(i+2)<<8 | str.charCodeAt(i+3);
word_array.push( j );
}
switch( str_len % 4 ) {
case 0:
i = 0x080000000;
break;
case 1:
i = str.charCodeAt(str_len-1)<<24 | 0x0800000;
break;
case 2:
i = str.charCodeAt(str_len-2)<<24 | str.charCodeAt(str_len-1)<<16 | 0x08000;
break;
case 3:
i = str.charCodeAt(str_len-3)<<24 | str.charCodeAt(str_len-2)<<16 | str.charCodeAt(str_len-1)<<8 | 0x80;
break;
}
word_array.push( i );
while( (word_array.length % 16) != 14 ) word_array.push( 0 );
word_array.push( str_len>>>29 );
word_array.push( (str_len<<3)&0x0ffffffff );
for ( blockstart=0; blockstart<word_array.length; blockstart+=16 ) {
for( i=0; i<16; i++ ) W[i] = word_array[blockstart+i];
for( i=16; i<=79; i++ ) W[i] = rotate_left(W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16], 1);
A = H0;
B = H1;
C = H2;
D = H3;
E = H4;
for( i= 0; i<=19; i++ ) {
temp = (rotate_left(A,5) + ((B&C) | (~B&D)) + E + W[i] + 0x5A827999) & 0x0ffffffff;
E = D;
D = C;
C = rotate_left(B,30);
B = A;
A = temp;
}
for( i=20; i<=39; i++ ) {
temp = (rotate_left(A,5) + (B ^ C ^ D) + E + W[i] + 0x6ED9EBA1) & 0x0ffffffff;
E = D;
D = C;
C = rotate_left(B,30);
B = A;
A = temp;
}
for( i=40; i<=59; i++ ) {
temp = (rotate_left(A,5) + ((B&C) | (B&D) | (C&D)) + E + W[i] + 0x8F1BBCDC) & 0x0ffffffff;
E = D;
D = C;
C = rotate_left(B,30);
B = A;
A = temp;
}
for( i=60; i<=79; i++ ) {
temp = (rotate_left(A,5) + (B ^ C ^ D) + E + W[i] + 0xCA62C1D6) & 0x0ffffffff;
E = D;
D = C;
C = rotate_left(B,30);
B = A;
A = temp;
}
H0 = (H0 + A) & 0x0ffffffff;
H1 = (H1 + B) & 0x0ffffffff;
H2 = (H2 + C) & 0x0ffffffff;
H3 = (H3 + D) & 0x0ffffffff;
H4 = (H4 + E) & 0x0ffffffff;
}
var temp = cvt_hex(H0) + cvt_hex(H1) + cvt_hex(H2) + cvt_hex(H3) + cvt_hex(H4);
return temp.toLowerCase();
}

Related

Generated row of table event listener not working instantly

I have a table like this :
I have added an event listener assetTableEvent() to each text box in the table. My issue is when I add new row to the table, i also add the corresponding event listener to it assetTableEvent(), but the total value does not pop while entering value, it shows only when next row has values entered.
function assetTableEvent() {
let total = 0;
for (var k = 0; k < document.getElementById("assetTable").rows.length; k++) {
var a = document.getElementById("v" + k);
var o = document.getElementById("o" + k);
var t = document.getElementById("t" + k);
if (a == null || o == null) {
continue;
}
if (a.value.length > 0 && o.value.length > 0) {
t.value = Number.parseInt(a.value - o.value);
total = (Number.parseInt(t.value) + Number.parseInt(total));
document.getElementById("totalAssets").value = Number.parseInt(total);
}
}
}
I even tried calling assetTableEvent() every time there is a change, but it just does not work. Can somebody help me in Javascript how to make dynamically added rows correspond to event listener like above rows.
HTML for Asset table:
<div id="calcContainer">
<div id = "headingText" >
Child Maintenance Calculator
</div>
<div id="startPage">
<button id="startBtn">Start</button>
</div>
<div id="asset">
<table id="assetTable">
<tr>
<th>Asset</th>
<th>Value</th>
<th>Own</th>
<th>Total</th>
</tr>
</table>
<div id="totalAssetsDiv">
<Label for ="totalAssets">Total Assets</Label>
<input type="number" id = "totalAssets" readonly="true">
<br>
</div>
<div id ="rowOps">
<br> <button id="addRow" class = "addDel">Add Row</button>
<button id="removeRow" class = "addDel1">Delete Row</button><br>
</div>
</div>
And add row event listener :
document.getElementById("addRow").addEventListener("click", function () {
var table = document.getElementById("assetTable");
var row = table.insertRow();
for (let j = 0; j < 4; j++) {
var tb = document.createElement("INPUT");
var value = "", idNum = "";
if (j == 0) {
tb.setAttribute("type", "text");
tb.value = value;
}
else {
tb.setAttribute("type", "number");
}
//Setting textbox id
switch (j) {
case 0:
idNum = "a";
break;
case 1:
idNum = "v";
break;
case 2:
idNum = "o";
break;
case 3:
idNum = "t";
break;
}
tb.id = idNum + (table.rows.length);
if (tb.id.includes('t')) {
tb.setAttribute("readOnly", "true");
}
tb.classList.add("assetTBox");
let cell = row.insertCell(j);
tb.addEventListener("input", assetTableEvent, false);
cell.appendChild(tb);
}
});
Trying to use incremental IDs is more work than it is worth, especially when you start removing rows.
I suggest you use classes instead and delegate the event listener to the table itself. When an input event occurs you get the closest row and query for the elements within that row for the row total, then query all of the rows totals for the master total
Basic example with functional add row
const table = document.querySelector('#myTable'),
cloneRow = table.rows[0].cloneNode(true);
table.addEventListener('input',(e) => {
if (e.target.matches('.qty, .price')) {
const row = e.target.closest('tr'),
price = row.querySelector('.price').valueAsNumber || 0,
qty = row.querySelector('.qty').valueAsNumber || 0;
row.querySelector('.amt').value = qty * price;
setTotalAmt()
}
});
document.querySelector('#add-row').addEventListener('click', (e) => {
table.appendChild(cloneRow.cloneNode(true))
});
function setTotalAmt() {
const sum = [...table.querySelectorAll('.amt')].reduce((a, el) => a + (+el.value || 0), 0)
document.querySelector('#total').value = sum;
}
<button id="add-row">
Add Row
</button>
Total:<input id="total" />
<table id="myTable">
<tr>
<td>Qty:
<input type="number" class="qty" value="0" />
</td>
<td>Price:
<input type="number" class="price" value="0" />
</td>
<td>Amt:
<input class="amt" readonly value="0" />
</td>
</tr>
</table>
#charlietfl 's solition is more elegant but if you wonder what is the problem in your code, you should change the < to <= in k < document.getElementById("assetTable").rows.length; part
function assetTableEvent() {
let total = 0;
for (var k = 0; k <= document.getElementById("assetTable").rows.length; k++) {
var a = document.getElementById("v" + k);
var o = document.getElementById("o" + k);
var t = document.getElementById("t" + k);
if (a == null || o == null) {
continue;
}
if (a.value.length > 0 && o.value.length > 0) {
t.value = Number.parseInt(a.value - o.value);
total = (Number.parseInt(t.value) + Number.parseInt(total));
document.getElementById("totalAssets").value = Number.parseInt(total);
}
}
}
Here is the working example:
document.getElementById("addRow").addEventListener("click", function () {
var table = document.getElementById("assetTable");
var row = table.insertRow();
for (let j = 0; j < 4; j++) {
var tb = document.createElement("INPUT");
var value = "", idNum = "";
if (j == 0) {
tb.setAttribute("type", "text");
tb.value = value;
}
else {
tb.setAttribute("type", "number");
}
//Setting textbox id
switch (j) {
case 0:
idNum = "a";
break;
case 1:
idNum = "v";
break;
case 2:
idNum = "o";
break;
case 3:
idNum = "t";
break;
}
tb.id = idNum + (table.rows.length);
if (tb.id.includes('t')) {
tb.setAttribute("readOnly", "true");
}
tb.classList.add("assetTBox");
let cell = row.insertCell(j);
tb.addEventListener("input", assetTableEvent, false);
cell.appendChild(tb);
}
});
function assetTableEvent() {
let total = 0;
for (var k = 0; k <= document.getElementById("assetTable").rows.length; k++) {
var a = document.getElementById("v" + k);
var o = document.getElementById("o" + k);
var t = document.getElementById("t" + k);
if (a == null || o == null) {
continue;
}
if (a.value.length > 0 && o.value.length > 0) {
t.value = Number.parseInt(a.value - o.value);
total = (Number.parseInt(t.value) + Number.parseInt(total));
document.getElementById("totalAssets").value = Number.parseInt(total);
}
}
}
<div id="calcContainer">
<div id = "headingText" >
Child Maintenance Calculator
</div>
<div id="startPage">
<button id="startBtn">Start</button>
</div>
<div id="asset">
<table id="assetTable">
<tr>
<th>Asset</th>
<th>Value</th>
<th>Own</th>
<th>Total</th>
</tr>
</table>
<div id="totalAssetsDiv">
<Label for ="totalAssets">Total Assets</Label>
<input type="number" id = "totalAssets" readonly="true">
<br>
</div>
<div id ="rowOps">
<br> <button id="addRow" class = "addDel">Add Row</button>
<button id="removeRow" class = "addDel1">Delete Row</button><br>
</div>
</div>

javascript table contents into array result weird

I am trying to read table contents into array using javsscript , but the results are weird
All content is split character wise, even complete cell contents.
What could be wrong?
function BTN_() {
var t = document.getElementById("TBL");
var G = document.getElementById("result");
var FF = [];
var R = t.rows.length; //TTL_rows
//FF += R ;
for (M = 0; M <= R - 1; M++) {
var TTL_row_cells = t.rows[M].cells.length;
for (C = 0; C <= TTL_row_cells - 1; C++) {
FF += t.rows[M].cells[C].innerHTML;
}
}
LN = FF.length;
document.write(LN + "<br/>");
for (V = 0; V <= LN - 1; V++) {
document.write(FF[V] + ",");
}
}
#TBL,
td {
border: 1px solid #cdcdcd
}
button {
font-size: 36px
}
<body style="font-size:36px">
<table id="TBL">
<tr>
<th>Heading1</th>
<th>Heading2</th>
</tr>
<tr>
<td>R1</td>
<td>R1</td>
</tr>
<tr>
<td>R2</td>
<td>R2</td>
</tr>
</table>
<div id="result"></div>
<hr />
<button onclick="BTN_()">Button</button>
</body>
result
24
H,e,a,d,i,n,g,1,H,e,a,d,i,n,g,2,R,1,R,1,R,2,R,2,
Instead of pushing data in array, you concat as a string. Here the cleanup you can do. Once push, then can join.
function BTN_() {
var t = document.getElementById("TBL");
var G = document.getElementById("result");
var FF = [];
var R = t.rows.length; //TTL_rows
//FF += R ;
for (M = 0; M <= R - 1; M++) {
var TTL_row_cells = t.rows[M].cells.length;
for (C = 0; C <= TTL_row_cells - 1; C++) {
FF.push(t.rows[M].cells[C].innerText)
}
}
LN = FF.length;
document.write(LN + "<br/>");
document.write(FF.join("<br/>"));
}
<table id="TBL">
<tr>
<th>Heading1</th>
<th>Heading2</th>
</tr>
<tr>
<td>R1</td>
<td>R1</td>
</tr>
<tr>
<td>R2</td>
<td>R2</td>
</tr>
</table>
<div id="result"></div>
<hr />
<button onclick="BTN_()">Button</button>

Velocity/Java script form not retaining the input

I am having trouble with velocity scripts which is not returning the childDoc(s) values after clicking the Apply button (child doc value disappears). I am new to Velocity and the Javascript.
Below is the part of the code that uses a form.
#set($levelRow = "levelRow")
#set($newLevelRow = "newLevelRow")
{pre}
<script>
function removeLevel(prefix) {
var levels = updateCommon(false, prefix);
var removeRow = document.getElementById(prefix + "levelRow" + levels);
removeRow.parentNode.removeChild(removeRow);
if(levels > 2)
setActionImageVisibility(levels - 1, "visible", prefix);
}
function addLevel(prefix) {
var levels = updateCommon(true, prefix);
var lastLevelRow = document.getElementById(prefix + "levelRow" + levels);
var newLevelRow = document.getElementById(prefix + "newLevelRow");
var newLevelInput = newLevelRow.getElementsByTagName("input")[0];
var toInsertRow = lastLevelRow.cloneNode(true);
toInsertRow.setAttribute("id", prefix + "levelRow" + (levels + 1));
var toInsertInputs = toInsertRow.getElementsByTagName("input");
var toInsertInput = null;
var toInsertOutput = null;
for (var i = 0; i < toInsertInputs.length; i++) {
var input_id = toInsertInputs[i].getAttribute("id");
if (input_id == (prefix + "query" + (levels))) {
toInsertInput = toInsertInputs[i];
} else if (input_id == (prefix + (levels))) {
toInsertOutput = toInsertInputs[i];
}
}
toInsertInput.setAttribute("id", prefix + "query" + (levels + 1));
toInsertInput.value = newLevelInput.value;
toInsertOutput.setAttribute("id", prefix + (levels + 1));
toInsertOutput.name = prefix + (levels + 1);
toInsertOutput.value = toInsertInput.value.replace("/#/", "/redirect/");
newLevelInput.value = "";
newLevelRow.parentNode.insertBefore(toInsertRow,newLevelRow);
setActionImageVisibility(levels, "hidden", prefix)
setActionImageVisibility(levels + 1, "visible", prefix)
}
function updateCommon(add,prefix) {
var levelsInput = document.getElementById(prefix + "levelsInput");
var levels = levelsInput.getAttribute("value") - 1 + 1;
if(add) {
levelsInput.setAttribute("value", levels + 1);
} else {
levelsInput.setAttribute("value", levels - 1);
}
return levels;
}
function setActionImageVisibility(level,visibility,prefix) {
var img = document.getElementById(prefix + "levelRow" + level).getElementsByTagName("img")[0];
img.style.visibility = visibility;
}
function submitFunction() {
var input_prefixes = new Array();
var docElements = document.getElementsByTagName("input");
for (docElement in docElements) {
var indexLevels = docElement.indexOf("levels");
var levelsAtEnd = (indexLevels + "levels".length) == docElement.length;
var hasPrefix = docElement.length > "levels".length;
if ((-1 < indexLevels) && levelsAtEnd && hasPrefix) {
input_prefixes.push(docElement.substring(0,indexLevels));
var input_prefix = docElement.substring(0,indexLevels);
var levelsInput = document.getElementsByName(docElement).item(0);
for (var i=1; i < parseInt(levelsInput.value) + 1; i++) {
var input = document.getElementById(input_prefix + "query" + String(i));
var output = document.getElementsByName(input_prefix + String(i)).item(0);
output.value = input.value.replace("/#/", "/redirect/");
}
}
}
}
</script>
{/pre}
#macro(loadParameter $id)
#set($_id = "$id")
#set($parameter = false)
#set($parameter = $request.getParameter($_id))
#end
#macro(VariableInputTable $paramBaseName $parametersRedirect)
#set($parameterPrefix = "${paramBaseName}")
#loadParameter("${parameterPrefix}levels")
#set($levels = $parameter)
#set($requiresParamInit = !$levels)
#if($requiresParamInit)
#set($defaultQueries = [""])
#set($levels = ${defaultQueries.size()})
#set($initParameters = "${parameterPrefix}levels=${levels}") ## this assumes that it is setting the only parameters on the page
#foreach($query in $defaultQueries)
#set($initParameters = "$initParameters&${parameterPrefix}${velocityCount}=$query")
#end
#set($parametersRedirect = "${parametersRedirect}${initParameters}")
#else
#set($int = 0)
#set($levels = $int.valueOf($levels))
#showTable()
#end
#end
#macro(showTable)
#set($queries = [])
#set($linkRoles = [])
#set($sorts = [])
<input id="${parameterPrefix}levelsInput" type="hidden" name="${parameterPrefix}levels" value="$levels"></input>
<table cellpadding="0" border=0>
#foreach($level in [1..$levels])
#loadParameter("${parameterPrefix}${level}")
<tr id="${parameterPrefix}${levelRow}$level">
<td style="border-width:1px;border-style:solid;padding:1px">
<input style="border-style:none" id="${parameterPrefix}query$level" type="text" size="50" oninput="submitFunction()" #if($parameter)value="$parameter.replaceAll('"','\\"')#end">
<input type="hidden" class="polarion-TextBox" name="${parameterPrefix}${level}" id="${parameterPrefix}${level}" style="width: 100%;">
</td>
<td style="vertical-align:middle;text-align:center;">
<img src="/polarion/ria/images/control/minus.gif" alt="Remove" title="Remove" style="cursor:pointer#if(($velocityCount != $levels) || (2 > $levels));visibility:hidden#end" onclick="removeLevel('${parameterPrefix}')" id="${parameterPrefix}removeImg$level"></img>
</td>
</tr>
#if($parameter)#set($void = $queries.add($parameter))#end
#set($void = $linkRoles.add([]))
#set($void = $sorts.add("id"))
#end
<tr id="${parameterPrefix}${newLevelRow}">
<td style="border-width:1px;border-style:solid;padding:1px">
<input style="border-style:none" id="${parameterPrefix}newQuery" type="text" size="50">
</td>
<td style="vertical-align:middle;text-align:center;">
<img src="/polarion/ria/images/control/plus.gif" alt="Add" title="Add" style="cursor:pointer" onclick="addLevel('${parameterPrefix}')"></img>
</td>
</tr>
</table>
#end
I think something wrong with below part.
<input style="border-style:none" id="${parameterPrefix}query$level" type="text" size="50" oninput="submitFunction()" #if($parameter)value="$parameter.replaceAll('"','\\"')#end">
<input type="hidden" class="polarion-TextBox" name="${parameterPrefix}${level}" id="${parameterPrefix}${level}" style="width: 100%;">
Form looks like:
I have managed to fix this by changing the code.
#if($parameter) #set( $childDocurl = $parameter.replaceAll('"','\\"'))#end
<input style="border-style:none" id="${parameterPrefix}query$level" type="text" size="50" value="${childDocurl}" oninput="submitFunction()" >
<input type="hidden" class="polarion-TextBox" name="${parameterPrefix}${level}" id="${parameterPrefix}${level}" value="${childDocurl}" style="width: 100%;">

minesweeper getAttribute of null error

Recently been creating minesweeper and came across a "Cannot read property 'getAttribute' of undefined" error on lines 19, 39, and 62 of my javascript code. I added the HTML to show where the javascript code is getting the variables from.
document.getElementById("begin").addEventListener("click", startGame);
let vertical;
let horizontal;
let DIFFICULTY;
let GG = false;
document.body.addEventListener('contextmenu', function(cm){e.preventDefault();});
function Winner(){
let ckCt = document.querySelectorAll('[clicked]').length;
let mCt = document.querySelectorAll('[mine]').length;
let cCt = horizontal * vertical;
if(cCt == ckCt + mCt){
GG = true;
return true;
}
return false;
}
function acrossTheBlock(cell){
let x = parseInt(cell.getAttribute('x'));
let y = parseInt(cell.getAttribute('y'));
//(x-1, y-1) (x, y-1) (x+1, y-1)
//(x-1, y) (x, y) (x+1, y)
//(x-1, y+1) (x, y+1) (x+1, y+1)
let nw = document.getElementById((x-1) + "_" + (y-1));
let n = document.getElementById((x) + "_" + (y-1));
let ne = document.getElementById((x+1) + "_" + (y-1));
let w = document.getElementById((x-1) + "_" + (y));
let e = document.getElementById((x+1) + "_" + (y));
let sw = document.getElementById((x-1) + "_" + (y+1));
let s = document.getElementById((x) + "_" + (y+1));
let se = document.getElementById((x+1) + "_" + (y+1));
return [nw, n, ne, w, e, sw, s, se];
}
function amt(count){
let z = 0;
let nextDoor = acrossTheBlock();
for(var n = 0; n < nextDoor.length; n++){
if(nextDoor[n] && nextDoor[n].hasAttribute("mine")){
count++
}
}
return count;
}
function findTheMine(e){
if(isNewGame){ this.removeAttribute("mine"); }
isNewGame = false;
if(this.classList.contains('flag')) { return; }
if(this.hasAttribute('clicked')) { return; }
if(this.hasAttribute("mine")){
//You lose!
isGameOver = true;
let bombs = document.querySelectorAll("[mine]");
for(var i = 0; i < bombs.length; i++){
bombs[i].className = "boom";
}
return;
}
this.setAttribute('clicked', true);
let BOOM = amt(this);
if(BOOM){
this.innerHTML = BOOM;
this.className = "c" + BOOM;
} else {
let nextDoor = acrossTheBlock(block);
for(var n = 0; n < nextDoor.length; n++){
if(nextDoor[n] && nextDoor[n].hasAttribute("mine")){
count++
}
}
}
isWin();
}
function IThinkIFoundTheMine(yay){
yay.preventDefault();
if(GG) { return; }
if(this.hasAttribute('clicked')) { return; }
if(this.classList.contains('flag')){
this.classList.remove('flag');
} else {
this.className = 'flag';
}
}
function getDifficulty(){
let radios = document.getElementsByName("difficulty");
for(var i = 0; i < radios.length; i++){
if(radios[i].checked){
return parseFloat(radios[i].value);
}
}
}
function startGame(){
vertical = parseInt(document.getElementById("vertical").value);
horizontal = parseInt(document.getElementById("horizontal").value);
DIFFICULTY = getDifficulty();
isNewGame = true;
isGameOver = false;
//clear out old gameboard (this allows for a new game.)
document.getElementById("minefield").innerHTML = "";
//dynamically build table.
var table = document.createElement("table");
document.getElementById("minefield").appendChild(table);
for(var r = 0; r < horizontal; r++){
var mineRows = document.createElement("tr");
table.appendChild(mineRows);
for(var c = 0; c < vertical; c++){
var textbox = document.createElement("td");
textbox.addEventListener("click", findTheMine);
textbox.addEventListener("contextmenu", IThinkIFoundTheMine);
textbox.setAttribute("id", c + "_" + r);
textbox.setAttribute("x", c);
textbox.setAttribute("y", r);
if(Math.random() < DIFFICULTY){
textbox.setAttribute("mine", true);
}
mineRows.appendChild(textbox);
}
}
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="minesweeper.css"/>
<title>Explosion</title>
</head>
<body>
<input id="horizontal" type="number" value="10">
<input id="vertical" type="number" value="10">
<input name="difficulty" value=".1" type="radio">Easy
<input name="difficulty" value=".2" type="radio" checked="true">Medium
<input name="difficulty" value=".3" type="radio">Hard
<input name="difficulty" value=".8" type="radio">Impossible
<button id="begin">Good Luck</button>
<div id="minefield"></div>
<script type="text/javascript" src="minesweeper.js"></script>
</body>
</html>
How can I fix this error?
On line 39 the script calls acrossTheBlock() without passing the argument (cell) needed to do cell.getAttribute() on the first two lines under that function.

how to pass php array on change of select in jQuery?

Let me tell you in brief what I am doing ..
I am doing pagination using a library where the pagination is just showing the 3 <li> at a time.
and What I am doing on that <li> is I have a php array with me and I am creating a table in that <li> that each <li> will have table with 8 rows so the 8 elements of the array has been displayed with the help of php code.
This is the code.
<?php
$data = array();
$no_of_Items = 8;
$k = 1;
for ($i = 1; $i <= 100; $i++) {
$data[$i - 1] = "striker" . $i;
}
?>
<select id="view" >
<option value="1">Midfielder</option>
<option value="2">Striker</option>
<option value="3">Defender</option>
<option value="4">Goal-Keeper</option>
</select>
<div id="pagination">
<ul id="demo">
<?php
$lis = ceil(count($data) / $no_of_Items);
for ($i = 1; $i <= $lis; $i++) {
?>
<li>
<table id="tbl-li">
<?php
for ($j = 1; $j <= $no_of_Items; $j++) {
if (empty($data[$k - 1])) {
break;
}
?>
<tr style="padding: 0; margin: 0;">
<td><?php echo $data[$k - 1]; ?></td>
<td>CHE</td>
<td>11.5</td>
<td>142</td>
</tr ><?php $k++; } ?>
</table>
</li>
<?php } ?>
</ul>
</div>
so what I am doing now is just passing the one array to the pagination div but i have 4 arrays for defender as well as for all the item contains in the select tag .
So my final question is how to provide to my code the php when I select the appropriate option from the select?
I have tried this but I know this will not going to work so any suggestion or any other way?
My js
var selectval;
$('#view').on('change', function () {
selectval = $(this).val();
});
if (selectval === 1)
{
<?php
for ($i = 1; $i <= 100; $i++) {
$data[$i - 1] = "midfielder" . $i;
}
?>
}
else if (selectval === 2) {
<?php
for ($i = 1; $i <= 100; $i++) {
$data[$i - 1] = "striker" . $i;
}
?>
}
else if (selectval === 3) {
<?php
for ($i = 1; $i <= 100; $i++) {
$data[$i - 1] = "defender" . $i;
}
?>
}
else if (selectval === 3) {
<?php
for ($i = 1; $i <= 100; $i++) {
$data[$i - 1] = "goalkeeper" . $i;
}
?>
}
Try This it will work..
$('#view').select(function(){
var valselect = $('#view').val();
console.log(valselect);
var data = [];
var i, j, k = 1;
var code = '';
var no_item = 8;
if (valselect === "1")
{
for (i = 1; i <= 50; i++) {
data[i - 1] = "Midfielder" + i;
}
console.log(data);
}
else if (valselect === "2")
{
for (i = 1; i <= 50; i++) {
data[i - 1] = "Striker" + i;
}
console.log(data);
}
else if (valselect === "3")
{
for (i = 1; i <= 50; i++) {
data[i - 1] = "Defender" + i;
}
console.log(data);
}
else if (valselect === "4") {
for (i = 1; i <= 50; i++) {
data[i - 1] = "Goal-keeper" + i;
}
console.log(data);
}
var lis = Math.ceil(data.length / no_item);
console.log(lis);
for (i = 1; i <= lis; i++)
{
console.log("outerloop="+i);
code += "<li><table id='tbl-li'>";
for (j = 1; j <= no_item; j++) {
console.log("j=" + j);
if (data[k - 1])
{
// console.log("k=" + k);
code += "<tr><td><img src='/img/info.png'>" + data[k - 1] + "</td><td>CHE</td><td>11.5</td><td>142</td></tr>";
k++;
}
else {
// console.log("val k=="+k);
break;
}
}
code += "</table></li>";
}
// console.log(code);
// $('#demo').append();
$('#demo').html(code);
});

Categories

Resources