How to keep duplicates from being added to an array - javascript

var reservations = [];
function addReservation() {
//Gets Input from textboxes.
var nameChosen = document.getElementById("txtName").value;
var roomChosen = document.getElementById("selRoom").value;
//adds input into the array.
reservations[reservations.length] = roomChosen + " ";
reservations[reservations.length] = nameChosen + " ";
//Gets input from radio button.
for (i = 0; i < document.getElementsByName("Day[]").length; i++) {
if (document.getElementsByName("Day[]")[i].checked) {
reservations.push(document.getElementsByName("Day[]")[i].value);
}
}
for (i = 0; i < document.getElementsByName("Time[]").length; i++) {
if (document.getElementsByName("Time[]")[i].checked) {
reservations.push(document.getElementsByName("Time[]")[i].value);
}
}
}
How do I ensure that if the time and day cannot be added twice to the array?
Or easier yet, How do I ensure that the same name cannot be added twice to the array?

Test if the item is in the array first
if (!item in array) { array.push(item); }

I think that you are looking for a way to break out of the for loop after you hit the first match. One way to do this is to set i to the termination condition inside the if statement, which will exit the loop.
//Gets input from radio button.
for (i = 0; i < document.getElementsByName("Day[]").length; i++) {
if (document.getElementsByName("Day[]")[i].checked) {
reservations.push(document.getElementsByName("Day[]")[i].value);
i = document.getElementsByName("Day[]").length
}
}
for (i = 0; i < document.getElementsByName("Time[]").length; i++) {
if (document.getElementsByName("Time[]")[i].checked) {
reservations.push(document.getElementsByName("Time[]")[i].value);
i = document.getElementsByName("Time[]").length
}
}

Related

How to remove element on second click

I need to add elements to container on a first click and delete it on a second one. I guess I'm trying to make it super hard while there is a more elegant and clear solution. Fiddle Link
I was thinking of arrays to create a 1st array for clicked elements and the 2nd one for elements that are already in a container. Then filter the first array through the second one and delete those (unmatched) elements from my container.
var click = +$(this).data('clicks') || 0; // Check if contacts cliked first time
if (click % 2 == 1) { // 2nd click
fruits.splice($.inArray(name, fruits), 1); // Remove Name from an array
$(".test .single").each(function (index, elem) {
compArr.push($(this).text());
});
keyArr = fruits.filter(i => compArr.indexOf(i) !== -1);
var i = 0;
for (; i < keyArr.length; i++) {
$(".name").each(function () {
$(".single:not(:contains('" + keyArr + "'))").remove();
});
} // I guess problem is here
} else { // 1st click
fruits.push(name);
$('.test textarea').css({
'font-size': '12px',
'border': '0'
}).prop('placeholder', '').before('<span class="single">' + name + '></span>');
$('textarea').val('');
}
$(this).data('clicks', click + 1);
For me, this part doesn't work properly. But I would love to hear any of your suggestions even if the entire logic is wrong. Thanks!
var i = 0;
for (; i < keyArr.length; i++) {
$(".name").each(function () {
$(".single:not(:contains('" + keyArr + "'))").remove();
});
}
I've managed to fix it. Added this code:
let deleteSingle = $('.single');
for (let i = 0; i < deleteSingle.length; i++) {
for (let j = 0; j < arrayNewKeys.length; j++) {
if (deleteSingle[i].innerHTML.includes(arrayNewKeys[j])) {
deleteSingle.eq(i).addClass('a');
break;
} else {
deleteSingle.eq(i).removeClass('a');
}
}
}
$('.styleContacts:not(.a)').remove();
if ($('.test > .single.a:only-child')) {
$('.single.a').removeClass('a');
}
Instead of this:
var i = 0;
for (; i < keyArr.length; i++) {
$(".name").each(function () {
$(".single:not(:contains('" + keyArr + "'))").remove();
});
} // I guess problem is here

Changing DOM with Select Option and checking no of required fields

There is a webpage with certain number of required fields that needs to be filled in order to submit a form successfully.
The biggest indicator of required field is that it has a * and its label has a class 'required' in it.
The number of required fields change when we change dropdown value. I have written some javascript and jquery code that changes the dropdown value and then checks the number of required fields but for some reason(most probably DOM changes is taking time and code executes before that so actually the change in number of required fields is not reflected in page). However if I change the dropdown value manually and then run the checkRequired() function, it works fine but I want to automate the procedure. How can I achieve that?
var count = 0;
var allRequired = []; // total number of required fields in the page
var newRequired = []; // change in the no. of required fields
$('select').each(function(){
var id = $(this).attr('id');
$('#'+id+' option').each(function() {
$(this).attr('selected','selected');
if(count == 0){
getAllRequiredFields();
}
else{
setTimeout(() => {
checkRequired();
for (let index = 0; index < allRequired.length; index++) {
console.log('for else',allRequired[index]);
if(!newRequired.includes(allRequired[index])){
console.log('allRequired',allRequired[index]);
}
}
}, 3000);
}
count++;
})
});
function getAllRequiredFields(){
$('span.required').each(function () {
var text = $(this).parent().text()
var id = $(this).closest("td").attr('id').split("_label")[0];
allRequired.push(id);
});
}
function checkRequired() {
newRequired = [];
$('span.required').each(function () {
var text = $(this).parent().text()
var id = $(this).closest("td").attr('id').split("_label")[0];
newRequired.push(id);
});
for (let index = 0; index < allRequired.length; index++) {
console.log('for else',count);
if(!newRequired.includes(allRequired[index])){
console.log('allRequired',allRequired[index]);
}
}
}
Just added change event fixed my problem
$('#'+id+' option').each(function() {
$(this).attr('selected','selected');
$('#'+id).change();
if(count == 0){
getAllRequiredFields();
}
else{
setTimeout(() => {
checkRequired();
for (let index = 0; index < allRequired.length; index++) {
console.log('for else',allRequired[index]);
if(!newRequired.includes(allRequired[index])){
console.log('allRequired',allRequired[index]);
}
}
}, 3000);
}
count++;
})

How do I create different button for each item in an array / JavaScript

Here's my code:
var never = [1,2,3,4,7];
function please () {
for (var i = 0; i < never.length; i++) {
document.getElementById("more").innerHTML = "<button>" + never[i] + "</button>";
}
}
I have a button in my HTML that invokes this function but it only creates a button for the last item (7). How can I create a different button for each one of the items in the array? Any help is appreciated.
The best way is to append created buttons in container.Each by each
var never = [1,2,3,4,7];
function please () {
var more=document.getElementById("more");
for (var i = 0; i < never.length; i++) {
var butt=document.createElement("button");
butt.innerHTML=never[i];
more.appendChild(butt);
}
}
By appending to innerHTML instead of assigning, like
var never = [1,2,3,4,7];
function please () {
for (var i = 0; i < never.length; i++) {
document.getElementById("more").innerHTML += "<button>" + never[i] + "</button>";
}
}
please();
<div id="more">
</div>

Getting an infinite loop and can't see why - Javascript

I'm writing a simple little Connect 4 game and I'm running into an infinite loop on one of my functions:
var reds = 0;
var greens = 0;
function checkEmpty(div) {
var empty = false;
var clicked = $(div).attr('id');
console.log(clicked);
var idnum = parseInt(clicked.substr(6));
while (idnum < 43) {
idnum = idnum + 7;
}
console.log("idnum=" + idnum);
while (empty == false) {
for (var i = idnum; i > 0; i - 7) {
idnumStr = idnum.toString();
var checking = $('#square' + idnumStr);
var str = checking.attr('class');
empty = str.includes('empty');
console.log(empty);
var divToFill = checking;
}
}
return divToFill;
}
function addDisc(div) {
if (reds > greens) {
$(div).addClass('green');
greens++;
console.log("greens=" + greens);
} else {
$(div).addClass('red');
reds++;
console.log("reds=" + reds);
};
$(div).removeClass('empty');
}
$(function() {
var i = 1;
//add a numbered id to every game square
$('.game-square').each(function() {
$(this).attr('id', 'square' + i);
i++;
//add an on click event handler to every game square
//onclick functions
$(this).on('click', function() {
var divToFill = checkEmpty(this);
addDisc(divToFill);
})
})
})
Here is a link to the codepen http://codepen.io/Gobias___/pen/xOwNOd
If you click on one of the circles and watch the browser's console, you'll see that it returns true over 3000 times. I can't figure out what I've done that makes it do that. I want the code to stop as soon as it returns empty = true. empty starts out false because I only want the code to run on divs that do not already have class .green or .red.
Where am I going wrong here?
for (var i = idnum; i > 0; i - 7);
You do not change the i.
Do you want to decrement it by 7?
Change your for loop to the one shown below:
for (var i = idnum; i > 0; i -= 7) {
// ...
}
You also do not use loop variable in the loop body. Instead, you use idnum, I think this can be issue.
while (empty == false) {
for (var i = idnum; i > 0; i -= 7) {
idnumStr = i.toString(); // changed to i
var checking = $('#square' + idnumStr);
var str = checking.attr('class');
empty = str.includes('empty');
console.log(empty);
var divToFill = checking;
// and don't forget to stop, when found empty
if (empty) break;
}
}
I add break if empty found, because if we go to next iteration we will override empty variable with smallest i related value.
You can also wrap empty assignment with if (!empty) {empty = ...;} to prevent this override, but I assume you can just break, because:
I want the code to stop as soon as it returns empty = true
Offtop hint:
while (idnum < 43) {
idnum = idnum + 7;
}
can be easy replaced with: idnum = 42 + (idnum%7 || 7)
Change to this:
for (var i = idnum; i > 0; i = i - 7) {
You are not decrementing the i in your for loop
Building on what the others have posted You would want to change the value of empty inside the for loop. because obviously the string still checks the last string in the loop which would always return false.
while(empty==false){
for (var i = idnum; i > 0; i -= 7) {
// your other codes
if (!empty) {
empty = str.includes('empty');
}
}

How to delete 2 rows at a time using JavaScript

How to delete two rows at a time using JavaScript even though only for first row radio button exist?
Something like this:
1st row: (radiobutton) some textfield
2nd row: text field
On click of delete button, both the row should get deleted but the code which I have written is deleting only 1st row not 2nd one.
JavaScript code looks something like this:
function deleteReserveDetails() {
if (!document.forms[0].reserveRadiobutton) {
return;
} else {
var hidValue = parseInt(document.forms[0].Hd1Value.value);
var reserveRows = document.getElementById('reserveTable').getElementsByTagName('tr');
var headerNo = 1;
var radio = eval("document.forms[0].reserveRadiobutton");
if (radio.length == undefined) {
if (radio.checked) {
var hidValue1 = parseInt(document.forms[0].Hd1Value.value) - 1;
document.forms[0].Hd1Value.value = hidValue1;
document.getElementById('reserveTable').deleteRow(headerNo);
}
return;
}
var k = 0;
for (var j = 0; j < radio.length; j++) {
if (radio[j].checked) {
if (j == hidValue - 1) {
var hidValue2 = parseInt(document.forms[0].Hd1Value.value) - 1;
document.forms[0].Hd1Value.value = hidValue2;
}
document.getElementById('reserveTable').deleteRow(j + headerNo);
}
}
}
}
Could you please show me how to modify it to delete 2 rows at a time?

Categories

Resources