I created an HTML array with some tr lines which need to be hidden by default and when user check the checkbox, the element is showed.
I have a Javascript function to show html element when checkbox is checked. It works but not when I use a loop.
I need that checkbox1 works on tr1, checkbox2 on tr2 ...
The PHP code which creates elements
<?php
if (isset($_SESSION['wordsListArray']))
{
$length = count($_SESSION['wordsListArray']);
for ($i = 0; $i < $length; $i++)
{
echo '<tr><td>' . htmlspecialchars($_SESSION['wordsListArray'][$i]) . '</td><td>' . htmlspecialchars($_SESSION['translationsListArray'][$i]) . '</td><td><input type="checkbox" id="checkboxId' . ($i+1) . '"/></td></tr>';
echo '<tr class="trHide" id="trHide' . ($i+1) . '"><td><input type="text" placeholder=' . $_SESSION['personel_language_array'][0] . '></td><td><input type="text" name="other" placeholder=' . $_SESSION['personel_language_array'][1] . '></td><td><button type="submit">Edit</button><button type="submit">Erase</button></td></tr>';
}
}
?>
This Javascript works but only on one element (getElementById is unique), but I need a loop to use different Id (trHide1, trHide2 ...)
var tr = document.getElementById("trHide1");
var check = document.getElementById("checkboxId1");
check.onchange = function() {
if(check.checked)
{
tr.style.display = 'contents';
}
else
{
tr.style.display = 'none';
}
};
I try this loop but it doesn't work.
for (var i = 1; i <= lengthWordList; i++)
{
var trId = 'trHide' + i;
var checkId = 'checkboxId' + i;
var tr = document.getElementById(trId);
var check = document.getElementById(checkId);
check.onchange = function() {
if(check.checked)
{
tr.style.display = 'contents';
}
else
{
tr.style.display = 'none';
}
};
}
Your code does not work because it overwrites the event and the selector
This could be worth it
var elemento=[];
for (var i = 1; i <= 2; i++)
{
var trId = 'trHide' + i;
var checkId = 'checkboxId' + i;
console.log(trId);
elemento.push(
{
tr:document.getElementById(trId),
check:document.getElementById(checkId),
event:function(){}
}
);
console.log(elemento[(i-1)]);
elemento[(i-1)].check.setAttribute('elemento',(i-1));
elemento[(i-1)].event = elemento[(i-1)].check.onchange = function() {
var valor = this.getAttribute('elemento');
if(elemento[valor].check.checked)
{
elemento[valor].tr.style.display = 'contents';
}
else
{
elemento[valor].tr.style.display = 'none';
}
};
}
var elemento=[];
for (var i = 1; i <= 2; i++)
{
var trId = 'trHide' + i;
var checkId = 'checkboxId' + i;
console.log(trId);
elemento.push(
{
tr:document.getElementById(trId),
check:document.getElementById(checkId),
event:function(){}
}
);
console.log(elemento[(i-1)]);
elemento[(i-1)].check.setAttribute('elemento',(i-1));
elemento[(i-1)].event = elemento[(i-1)].check.onchange = function() {
var valor = this.getAttribute('elemento');
if(elemento[valor].check.checked)
{
elemento[valor].tr.style.display = 'contents';
}
else
{
elemento[valor].tr.style.display = 'none';
}
};
}
<table>
<tr id="trHide1" style="display:none"><td>AAAA</td></tr>
<tr id="trHide2" style="display:none"><td>BBBB</td></tr>
</table>
<input type="checkbox" id="checkboxId1">
<input type="checkbox" id="checkboxId2">
Related
I'm trying to create a program where if the user enters a X-number between 1-9, and it takes that X-number and creates X-number of rows and columns. For example, if the user enters "5", the output should be something like this:
....1
...2.
..3..
.4...
5....
I cannot get it to show the output right now with the code I have. I am still new to JavaScript so any help is appreciated.
function drawSquare() {
let myArray1 = ["1"];
let myArray2 = [".1", "2."];
let myArray3 = ["..1", ".2.", "3.."];
let myArray4 = ["...1", "..2.", ".3..", "4..."];
let myArray5 = ["....1", "...2.", "..3..", ".4...", "5...."];
let myArray6 = [".....1", "....2.", "...3..", "..4...", ".5....", "6....."];
let myArray7 = ["......1", ".....2.", "....3..", "...4...", "..5....", ".6.....", "7......"];
let myArray8 = [".......1", "......2.", ".....3..", "....4...", "...5....", "..6.....", ".7......", "8......."];
let myArray9 = ["........1", ".......2.", "......3..", ".....4...", "....5....", "...6.....", "..7......", ".8.......", "9........"];
let l1 = myArray1.length;
let l2 = myArray2.lenght;
let l3 = myArray3.length;
let l4 = myArray4.length;
let l5 = myArray5.length;
let l6 = myArray6.length;
let l7 = myArray7.length;
let l8 = myArray8.length;
let l9 = myArray9.length;
let number = document.getElementById("textbox3")
let getNumber = number.value
if (getNumber != 1 || getNumber > 9) {
alert("You have entered an incorrect number");
} else if (getNumber = 1){
text = "<br>";
for (i = 0; i < l1; i++) {
text += "<br>" + myArray1[i] + "<br>";
}
}
}
<p>Enter a height for our square<input type="text" id="textbox3"><button id="drawSqaure" onclick="drawSquare()">Draw Square</button></p>
<p id="output2">Output goes here</p>
Little implementation using a textarea. It uses the number of rows to draw to know how many dots to draw, depending upon which row you are drawing.
document.getElementById('rowCount').addEventListener('input', function(e){
var rowCount = parseInt(e.target.value.trim() || '0', 10);
var textarea = document.getElementsByTagName('textarea')[0];
textarea.innerHTML = '';
for (var i = 1; i <= rowCount; i++) {
if (i > 1) textarea.innerHTML += "\n";
textarea.innerHTML += '.'.repeat(rowCount - i);
textarea.innerHTML += i;
textarea.innerHTML += '.'.repeat(i - 1);
}
});
<input type="number" id="rowCount" value="0" min="0">
<textarea></textarea>
To make it the way you clearly said on your question:
. . . . 1
. . . 2 .
. . 3 . .
. 4 . . .
5 . . . .
The solution is this:
$("#generate_square").click(function(){
let number = $("#number").val();
let square = $("#square_gen");
let str = "";
let number_shown = 1;
for(var dcolumns = 1; dcolumns<=number; dcolumns++){
for(var drows = 1; drows<=number; drows++){
if( drows === number_shown ){
str += number_shown+" ";
}else{
str +="0 ";
}
}
str += "<br>";
number_shown++;
}
square.append(str);
});
Here is a fiddle of it working:
https://jsfiddle.net/ndpe671c/1/
function drawSquare() {
var n = document.getElementById("textbox3").value;
n = parseInt(n);
var str = '<br/>';
for (var i = 0; i < n; i++ ) {
var x = n - 1;
for (var j = x; j >= 0; j--) {
if (j === i) {
str += i;
} else {
str += '.';
}
}
str += '<br/>';
}
// console.log(str);
$('#output2').html(str);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Enter a height for our square<input type="text" id="textbox3"><button id="drawSqaure" onclick="drawSquare()">Draw Square</button></p>
<p id="output2">Output goes here</p>
I make it simpler with jquery. Check it and tell me, if it's what you want.
I have this HTML code:
<div id="dadosalvaje" class="draconistone"><dl class="codebox"><dd><strong>Número aleatorio (1,10) : </strong>1</dd></dl></div>
<div id="dadosalvaje" class="draconistone"><dl class="codebox"><dd><strong>Número aleatorio (1,10) : </strong>3</dd></dl></div>
And i want to execute this JavaScript code on each one:
$(document).ready(function() {
//Arreglos
var zonas = ['draconistone','cessabit', 'valoran'];
var draconistone = ['bulbasaur', 'pikachu', 'squirtle'];
//Variables
var contenedor = $('#dadosalvaje');
var texto = contenedor.text().split(' ');
var resultado = texto.pop();
var zonaID = $('#dadosalvaje').attr('class');
for (var i = 0; i < zonas.length; i++) {
if (zonaID == zonas[i]) {
if (zonaID == 'draconistone') {
var pokemonSprite = draconistone[resultado - 1];
}
}
}
for (var i = 0; i < zonas.length; i++) {
if (zonas[i] == zonaID) {
contenedor.append('<img src="https://www.pkparaiso.com/imagenes/xy/sprites/animados/' + pokemonSprite + '.gif"><div class="salvajeNombre">' + pokemonSprite + '</div>');
contenedor.attr('id', 'salvajelisto');
}
}
});
It just affects the first element and I can't find the way to modify both of them.
Is there any way to modify every single element with the same ID ?
First you need to make unique id
You do not need the "draconistone" class
Inside the $(document).ready(function() { and }); tags make the code a function with an id parameter like this:
function name(id) {
//Arreglos
var zonas = ['draconistone','cessabit', 'valoran'];
var draconistone = ['bulbasaur', 'pikachu', 'squirtle'];
//Variables
var contenedor = $('#' + id);
var texto = contenedor.text().split(' ');
var resultado = texto.pop();
var zonaID = $('#' + id).attr('class');
for (var i = 0; i < zonas.length; i++) {
if (zonaID == zonas[i]) {
if (zonaID == 'draconistone') {
var pokemonSprite = draconistone[resultado - 1];
}
}
}
for (var i = 0; i < zonas.length; i++) {
if (zonas[i] == zonaID) {
contenedor.append('<img src="https://www.pkparaiso.com/imagenes/xy/sprites/animados/' + pokemonSprite + '.gif"><div class="salvajeNombre">' + pokemonSprite + '</div>');
contenedor.attr('id', 'salvajelisto');
}
}
}
Then execute the functions with the two different ids as parameters.
Maybe you can use $.each()
Like this
$('.draconistone').each(function() {
var zonaID = $(this).attr('class');
..
});
There is one for the same class
$( document).ready(function() {
$( ".draconistone" ).each(function( i ) {
var zonas = ['draconistone','cessabit', 'valoran'];
var draconistone = ['bulbasaur', 'pikachu', 'squirtle'];
//Variables
var texto = this.innerText.split(' ');
var resultado = texto.pop();
var zonaID = this.className;
for (var i = 0; i < zonas.length; i++) {
if (zonaID == zonas[i]) {
if (zonaID == 'draconistone') {
var pokemonSprite = draconistone[resultado - 1];
}
}
}
for (var i = 0; i < zonas.length; i++) {
if (zonas[i] == zonaID) {
this.innerHTML += '<img src="https://www.pkparaiso.com/imagenes/xy/sprites/animados/' + pokemonSprite + '.gif"><div class="salvajeNombre">' + pokemonSprite + '</div>';
this.id = 'salvajelisto';
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="dadosalvaje1" class="draconistone"><dl class="codebox"><dd><strong>Número aleatorio (1,10) : </strong>1</dd></dl></div>
<div id="dadosalvaje2" class="draconistone"><dl class="codebox"><dd><strong>Número aleatorio (1,10) : </strong>3</dd></dl></div>
currently Im trying to sort input name values of my table alphabetically. First I'm pushing values into array, then sorting that array alpabetically, but I can't plase that values separatly in input areas, hope you can help me find solution to this problem
alphabeitcally sorting function is written on the bottom side of my code
$(function(){
var tableHead =
"<table>" +
"<tr>" +
"<th class='sort'>Id <span class='downArrow'>↓</span> <span class='upArrow'>↑</span></th>" +
"<th id='sort_name'>Name sort</th>" +
"<th>Surname</th>" +
"<th>Birthday</th>" +
"<th>Filter</th>" +
"<th class='addList'>+</th>" +
"</tr>" +
"</table>";
$('body').html(tableHead);
var inputName = "<input type='text' class='name' placeholder='First name'>";
var inputSurname = "<input type='text' class='surname' placeholder='Surname'>";
var bDayDate ="<input type='date' class='bDayDate' placeholder='Bday'>";
var addList = $('.addList');
var downArrow = $(".downArrow");
var upArrow = $(".upArrow");
var name = $(".name");
var idNum = 0;
var arrNum = [];
var nameArr = [];
var sortedNameArr = [];
var sortedArr = [];
addList.on("click", function(){
idNum++;
var tr = $("<tr></tr>");
for(var i = 1; i <= 6; i++){
var td = $('<td></td>');
tr.addClass(""+ idNum);
switch (i){
case 1:
td.addClass(""+ idNum);
td.html(idNum);
break;
case 2: td.html(inputName);
break;
case 3: td.html(inputSurname);
break;
case 4: td.html(bDayDate);
break;
case 5: td.html(1);
break;
case 6:
td.html("Delete");
td.addClass('delete');
break;
default:
return console.log("OooPs!!");
}
tr.append(td);
}
arrNum.push(tr);
$('table').append(arrNum);
$('.delete').on("click", function(){
removeItem(this, arrNum, sortedArr);
});
for(var j = arrNum.length; j >= 0; j--){
sortedArr.push(arrNum[j]);
}
downArrow.on("click", function(){
$('table').append(sortedArr);
$('.delete').on("click", function(){
$(this).parent().remove();
});
});
upArrow.on("click", function(){
$('table').append(arrNum);
});
function removeItem(item, arr, sArr) {
var that = $(item).parent();
$(item).parent().remove();
for(var k = 0;k <arr.length; k++) {
if(arr[k] && that[0] === arr[k][0]) {
arr.splice(k,1);
} else {
// console.log(that[0]);
// console.log(arr[k][0])
}
}
// If you want delete when sort the table
for(var k = 0;k <sArr.length; k++) {
if(sArr[k] && that[0] === sArr[k][0]) {
sArr.splice(k,1);
} else {
// console.log("wrong!!")
}
}
}
});
$("#sort_name").on("click", function(){
var name = $(".name");
for(var n = 0; n < arrNum.length; n++){
nameArr.push($(name[n]).val());
}
nameArr.sort();
for(var n = 0; n < nameArr.length;n++){
console.log(nameArr[n])
}
});
});
I have a container where I dynamically add sections, I create items inside the section , that should be sortable, But Jquery sortable does not work inside dynamically created containers, while if I give the containers static it works,
Can anyone please share a solution.Thanks
https://jsfiddle.net/anubala/7ut5wk3j/1/
HTML:
<div class='row page-layout'>
<div class='col-md-10 col-md-offset-1' >
<div class="add_section_div">
<p>Add section</p>
</div>
<div id="contents">
</div>
</div>
</div>
JavaScript:
$(".wrap_body").sortable();
$(".add_section_div").on("click", function() {
var $section = "<div class='section_div'><div class='div_header clearfix'><p class='pull-left'>Add Wrap</p></div><div class='section_body div_body'></div></div>";
$("#contents").append($section);
})
$("body").on("click", ".section_div>.div_header", function() {
var $wrap = "<div class='wrap_div'><div class='div_header clearfix'><p class='pull-left'>Add Item</p></div><div class='wrap_body div_body clearfix'></div></div>";
$(this).parent().find('.section_body').append($wrap);
})
const regex = /^.*-\s*(.*)$/;
$("body").on("click", ".wrap_div>.div_header", function() {
var $item1 = "<div class='drag col-sm-";
var $item2 = "'><div class='item_div'><div class='div_header clearfix'><p class='pull-left'><span class='minus'><i class='fa fa-minus'></i></span><span class='plus'><i class='fa fa-plus'></i></span></p><p class='pull-left header_text'>";
var $item3 = "</p></div><div class='div_body'></div></div></div>";
var length_item = $(this).parent().find(".wrap_body .item_div").length;
var count = 0;
for (i = 0; i < length_item; i++) {
if ($(this).parent().find(".wrap_body>div:eq('" + i + "')")) {
console.log($(this).parent().find(".wrap_body>div:eq('" + i + "')"))
var col_count_text = $(this).parent().find(".wrap_body>div:eq('" + i + "')").attr('class');
count += parseInt(find_col_count(col_count_text));
}
}
var current_col_count = 12 - (count % 12);
if (count < 12) {
$(this).parent().find('.wrap_body').append($item1 + current_col_count + $item2 + "col-sm-" + current_col_count + $item3);
}
})
function find_col_count(col_text) {
var col_count = regex.exec(col_text);
col_count.forEach((match, groupIndex) => {
count1 = match;
});
return count1;
}
$("body").on("click", ".plus", function() {
var $parent = $(this).parent().parent().parent().parent();
var col_count_text = $parent.attr('class');
var length_item = $parent.parent().find(".item_div").length;
var count = 0;
for (i = 0; i < length_item; i++) {
if ($parent.parent().find(".item_div:eq('" + i + "')").parent()) {
var col_count_text = $parent.parent().find(".item_div:eq('" + i + "')").parent().attr('class');
count += parseInt(find_col_count(col_count_text));
}
}
var col_count_text = $parent.attr('class');
var col_count = find_col_count(col_count_text);
if (count < 12) {
var col_count_new = "col-sm-" + (++col_count);
var col_count_drag = "drag " + col_count_new;
$parent.attr("class", col_count_drag);
$parent.find(".header_text").html(col_count_new);
}
});
$("body").on("click", ".minus", function() {
var $parent = $(this).parent().parent().parent().parent();
var col_count_text = $parent.attr('class');
var col_count = find_col_count(col_count_text);
if (col_count > 1) {
var col_count_new = "col-sm-" + (--col_count);
var col_count_drag = "drag " + col_count_new;
$parent.attr("class", col_count_drag);
$parent.find(".header_text").html(col_count_new);
}
});
You probably may have found the solution already but to solve this issue you only need to move this line
$(".wrap_body").sortable();
To where you actually append the .wrapper_body to the body as following:
$("body").on("click", ".section_div>.div_header", function() {
var $wrap = "<div class='wrap_div'><div class='div_header clearfix'><p class='pull-left'>Add Item</p></div><div class='wrap_body div_body clearfix'></div></div>";
$(this).parent().find('.section_body').append($wrap);
$(".wrap_body").sortable();
});
This should solve your problem. See JsFiddle
I am building a form sending function in JavaScript, and I have run into a problem where it executes an else if statement every time. Here is my script:
this.submit = function() {
var url = this.url + "?";
for(el in this.elements) {
var e = $(this.elements[el]);
var n = this.names[el];
if(n === "submit")
{
window.alert("submit");
}
else
{
url += n + "=";
}
if(el == "#dropdown")
{
var options = e.children();
for(var i = 0; i < options.length; i++) {
var option = $('#' + options[i].id);
if(option.attr('selected'))
{
url += option.attr('name');
url += "&";
window.alert("dropdown worked");
break;
}
}
}
else if(el != "#submit") {
url += e.attr('value');
url += "&";
window.alert("input worked");
}
}
window.location.href = url;
};
The problem being that the else if(el != "#submit"){} runs even when the id in question is "#submit". Does anyone know why this doesn't work?
To help, here is my php document, and the rest of the form constructer:
php:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<?php if(!$_GET): ?>
<form id="form1">
<input type="text" id="input1" name="name"/>
<br>
<select id="dropdown" name="color">
<option id="null" name="null"></option>
<option id="opt1" name="blue">blue</option>
<option id="opt2" name="yellow">yellow</option>
</select>
<br>
<button type="submit" id="submit" name="submit"onclick="form1.submit()">Submit data</button>
</form>
<script src="http://charlie/form.js"></script>
<script>
var form1 = new form("form1");
form1.setElements();
form1.logElements();
</script>
<?php elseif(!(isset($_GET['name']) || isset($_GET['color']))): ?>
<p style="color:red">ERROR! form.js failed</p>
<?php else: ?>
<p><?= $_GET['name'] ?></p>
<p><?= $_GET['color'] ?></p>
<?php endif; ?>
</body>
</html>
form constructer:
function form(id) {
this.id = "#" + id;
this.url = window.location.href;
this.elements = [];
this.names = [];
this.setElements = function() {
var elements = [],names = [],children = $(this.id).children();
for(var i = 0; i < children.length; i++) {
var childid = children[i].id;
if(childid)
{
elements.push('#' + childid);
}
}
this.elements = elements;
for(var e in this.elements) {
names.push($(this.elements[e]).attr('name'));
}
this.names = names;
};
this.logElements = function() {
for(var e in this.elements) {
console.log(this.elements[e]);
}
for(var n in this.names) {
console.log(this.names[n]);
}
};
this.submit = function() {
var url = this.url + "?";
for(el in this.elements) {
var e = $(this.elements[el]);
var n = this.names[el];
if(n === "submit")
{
window.alert("submit");
}
else
{
url += n + "=";
}
if(el == "#dropdown")
{
var options = e.children();
for(var i = 0; i < options.length; i++) {
var option = $('#' + options[i].id);
if(option.attr('selected'))
{
url += option.attr('name');
url += "&";
window.alert("dropdown worked");
break;
}
}
}
else if(el != "#submit") {
url += e.attr('value');
url += "&";
window.alert("input worked");
}
}
window.location.href = url;
};
}
Turning my comment into an answer with some code. The "in" operator in Javascript iterates over properties not the elements at each index. To make your current code work, change the code to the following:
var el;
var elementCount = this.elements.length;
for (var i = 0; i < elementCount; i++) {
el = this.elements[i];
This will produce the expected behavior.
The for...in loop is the cause. el tkaes the values 0, 1, 2 ...you need to compare this.elements[el] instead of el :
if(this.elements[el] == "#dropdown") ...
else if(this.elements[el] != "#submit") {
...