function includes in javascript - javascript

I want to get the same value on string after split
If I have the numbers (as a string): 1,6,18,2 and I use .includes I get an output which looks like this: 1,2,6,8,18
How can I get same with that string -> 1,2,6,18
This is my code in js :
trHTML = '';
total = 20;
var antrian = $('#antrian').val(); // 1,6,18,2
for(i = 1; i <= total; i++){
if(antrian.includes(i)){
trHTML += <button style="background-color: gray;"> '+ i +'</button>';
} else {
trHTML += <button style="background-color: red;"> '+ i +'</button>';
}
}
From that code I got button output button with number, if I consol.log(trHTML) the output is 1,2,6,18 but output in HTML is gray button 1,2,6,8,18 and others is red button
How can I got grey button with number 1,2,6,18 or same with console.log(trHTML) ?
Can someone help me or give me an example?

The reason why 8 is included in 1,6,18,2 is that there is an 8 in the string. One option is make antrian an array using split()
var trHTML = ''; //Add var
var total = 20; //Add var
var antrian = $('#antrian').val().split(","); //Add split() - this will return to [1,6,18,2]
for(var i = 1; i <= total; i++){ //Add var on i
if(antrian.includes(i.toString())){
trHTML += '<button style="background-color: gray;"> '+ i +'</button>';
} else {
trHTML += '<button style="background-color: red;"> '+ i +'</button>';
}
}

Related

Add button in javascript without using html

I'm trying to add a button in javascript file without using HTML bacsue I need to have it in the column inside the loop, but when I click on the button to call the function it shows the error that its looking on that button in HTML file!
how could I fix that?
function success(name) {
let info = "<div class='infoTable'>";
for (let i = 0; i < name.length; i++) {
info += "<div class='info'>";
info += "<div class='fcol'>" + (i+1) + "</div>";
info += "<div class='scol'>" + name[i].item + "</div>";
info += "<div class='fcol'>" + name[i].quantity + "</div>";
info += '<button onclick="deletee(\'' + name[i].ID + '\')"> Delete This<button />';
info += "</div>";
}
info += "</div>";
printItems.innerHTML = info;
}
this is the function
function deletee(id){
let url = "server/delete.php?id=" + id;
console.log(url);
fetch(url, { credentials: 'include' })
.then(response => response.text())
.then(getList)
}
this is the error
(index):1 Uncaught ReferenceError: deletee is not defined
at HTMLButtonElement.onclick ((index):1)
onclick # (index):1
The best solution in this case is using document.createElement: https://www.w3schools.com/jsref/met_document_createelement.asp
It's better practice than converting a string to DOM Elements.
Since you did not post all your code, we cannot assist further if we cannot see the function you are trying to execute.
The reason why I am suggesting using JS and not converting a string to DOM, is most IDE's will identify missing, misspelt, or incorrectly used functions. Which could've been your mistake.
Here is an example:
var colsToAdd = 5;
var rowsToAdd = 25;
function FillTable() {
//Get existing table or create a new one. Append to parent if create
var table = document.getElementById("testTable");
//Clear table
table.innerHTML = "";
//Create your rows using a for loop
for (var i = 0; i < rowsToAdd; i++) {
var row = document.createElement("TR");
table.appendChild(row);
//Create your columns using a for loop
for (var k = 0; k < colsToAdd; k++) {
{
var col = document.createElement("td");
row.appendChild(col);
if (k == colsToAdd - 1) {
var button = document.createElement("button");
button.type = "button";
//Button click event is an anonymous function
button.onclick =
function(r) {
return function() {
table.removeChild(r);
}
}(row)
button.innerHTML = "Delete";
col.appendChild(button);
} else {
col.innerHTML = "row " + i + " column " + k;
}
}
}
}
}
table {
border: 1px solid #000;
margin: 1em;
}
td {
border: 1px solid #000;
padding: 1em;
}
<div>
<h1>Heading</h1>
<button onclick="FillTable()">Fill table</button>
<table id="testTable">
</table>
</div>

Value not increasing in table in while clicked in javascript

I have a table and when I clicked on leftmost column's number like 1,2,3... I want their respective rightmost column 0 to increase like 1,2,3,4,5...(Increase by 1 on every click.)
var ms=document.getElementById('message');
window.onload = build;
var myArray = ["Laurence", "Mike", "John", "Larry", "Kim", "Joanne", "Lisa", "Janet", "Jane"];
var message = document.getElementById('message');
function build() {
var html = "<h1>My Friends Table</h1><table>";
for (var x = 0; x < myArray.length; x++) {
html += '<tr data-row="' + x + '" data-vote="0"><td class="box" >' + (x + 1) + '</td><td>' + myArray[x] + '</td><td>0</td></tr>';
}
html += '</table>';
document.getElementById('output').innerHTML = html;
var elbox = document.querySelectorAll('#output .box');
var a;
var v;
for (var x = 0; x < elbox.length; x++) {
elbox[x].onclick = function () {
console.dir(this);
a = this.closest('[data-row]').getAttribute('data-row');
console.log(myArray[a]);
message.innerHTML = myArray[a] + " is on row #" + a;
v = this.closest('[data-vote]').getAttribute('data-vote');
v++;
console.log(v);
this.parentElement.lastElementChild.innerText=v;
}
}
}
td {
border: 1px solid #ddd;
padding: 10px;
}
<html>
<head>
<title>Complete JavaScript Course</title>
</head>
<body>
<div id="message">Complete JavaScript Course</div>
<div id="output"></div>
</body>
</html>
I have set v++ but why the value of v is not increasing? I am still seeing value as 1. To update the innertext,I have used
this.parentElement.lastElementChild.innerText=v;
Since <tr> is parent of td and i used this.parentElement.lastElementChild.innerText=v; why its just stuck to 1 on every click?Why it is not increasing after one?
Every time you click it is based on data-vote attribute value of the first td of the row.
You do modify the innerText of the right column but after that you should do something like this to modify the data-vote attribute also:
this.parentElement.firstElementChild.dataset.vote=v;

How do you create a for loop using a variable in javascript?

I have a block of code under a div element "questionform" and want to allow the code to repeat, depending on the number of times the user would like it to, to eventually allow the user to make a quiz.
I have tried to create a bit of javascript in order to repeat just the question number for now, but it won't work.
<div id="myHTMLWrapper">
</div>
<script>
var wrapper = document.getElementById("myHTMLWrapper");
var number = prompt("Enter the number of questions");
for (var i = 0; i = number - 1; i++) {
myHTML += '<span class="test">Question' + (i + 1) + '</span><br/><br/>';
}
wrapper.innerHTML = myHTML
</script>
any help will be appreciated, and please dont just point out flaws and not tell me how to improve them.
You have two issues in your code. firstly, you have to declare the variable myHTML outside the loop with empty string. Secondly, in the loop i = number - 1 will prevent the iteration of the loop, try i < number
<div id="myHTMLWrapper">
</div>
<script>
var wrapper = document.getElementById("myHTMLWrapper");
var number = prompt("Enter the number of questions");
var myHTML = '';
for (var i = 0; i < number; i++) {
myHTML += '<span class="test">Question ' + (i + 1) + '</span><br/><br/>';
}
wrapper.innerHTML = myHTML;
</script>
Though, here starting the loop iteration value from 1 with i <= number is more meaningful as this will allow you to use the value directly (without the increment) in the htmlString:
<div id="myHTMLWrapper">
</div>
<script>
var wrapper = document.getElementById("myHTMLWrapper");
var number = prompt("Enter the number of questions");
var myHTML = '';
for (var i = 1; i <= number; i++) {
myHTML += '<span class="test">Question ' + i + '</span><br/><br/>';
}
wrapper.innerHTML = myHTML
</script>

displaying multiple arrays using javascript

these are my arrays
var CarType=["RM","BM","GM"];
var CarName=["Red Mustang","Black Mustang","Green Mustang"]
how would I create a simple function that when a button is pushed an alert would pop up that displays something like this:
RM = Red Mustang
BM = Black Mustang
GM = Green Mustang
Here's a working solution. Hope it helps!
function myFunction() {
var CarType=["RM","BM","GM"];
var CarName=["Red Mustang","Black Mustang","Green Mustang"];
var result = "";
for(var i in CarType){
result += [CarType[i] + " = " + CarName[i]] + "\n";
}
alert(result)
}
<button onclick="myFunction()">Click me</button>
I haven't tested this, but it should go something like this.
Your arrays must have same size for this to work and sorted
function display(carType, carName) {
var text = "";
for (i=0; i < carType.length; i++) {
text += carType[i] + " = " + carName[i] + "\n";
}
alert(text);
}
var CarType=["RM","BM","GM"];
var CarName=["Red Mustang","Black Mustang","Green Mustang"];
display(CarType, CarName);

Dynamically add bootstrap rows using modulo

I a trying to dynamically add rows and populate them with 3 col-sm-4 using a modulo against the number of objects in a returned object from a function.
Code:
function formatSeriesCard(series) {
var card = "";
console.log(countProperties(series));
for (var i=0; i < countProperties(series); i++) {
if (i % 3 == 0 ) {
card += "<div class=\"row\">";
}
card += "<div class='col-sm-4' data-id="+i+">";
card += "<div class='action-box'>";
card += "<h4>" + '"' + series.name + '"' + "</h4>";
card += "<p>";
Instead I'm getting each row nested within the previous. Thinking I need to test for the first one and last one. Thanks.
Here is something like what you want
Bootply : http://www.bootply.com/2xnJBpyVsS
JS :
var wantedcol=14;
var mycol='<div class="col-xs-4">mycol</div>';
var startRowLabel="<div class='row'>";
var endRowLabel="</div>";
var start = "";
var end="";
var toAppend="";
for(var i=0; i<wantedcol; i++){
start="";
if(i%3==0 || i==0){
start=startRowLabel;
}
end="";
if(i!=0 && (i%3==2 || i==wantedcol-1)){
end=endRowLabel;
}
console.log(start+mycol+end);
toAppend+=start+mycol+end;
}
$('.container').append(toAppend);
HTML:
<div class="container"></div>
Comment :
You just have to take care about when you have to insert the div.row opening and closing tags

Categories