Receiving error after removing Option from Select using Javascript - javascript

I have a select element that I am adding option's to with js via an input text field. The value must be four digits and this part works fine. I can switch between the options to display information for each one also. This is done with the ctcSelect.addEventListener function. Everything works fine until I remove a selected option from the 'options' node list. Now my ctcSelect.addEventListener function seems to want to change both i and i+1 to true. Of course this throws and error when clicking on the last option it also changes two of the option custom attributes to true.
Hopefully someone can help me understand what I'm doing wrong.
let ctcInput = document.getElementById("ctcInput");
let ctcSelect = document.getElementById("ctcSelect");
let removeButton = document.getElementById("removeButton");
let options = document.getElementsByTagName("option");
ctcInput.addEventListener("keydown", (e) => {
if (isNaN(ctcInput.value) || ctcInput.value.length != 4) return;
if (e.code == "Enter" || e.code === "Tab") {
addCtc(Number(ctcInput.value));
}
});
removeButton.addEventListener("click", () => {
for (let i = 0; i < options.length; i++) {
if (options[i].dataset.active == "true") rmvCtc(options[i].value);
}
});
ctcSelect.addEventListener("change", () => {
console.log(options);
for (let i = 0; i < options.length; i++) {
console.log(i);
options[i].setAttribute("data-active", "false"); //set all to false if there's a change
options[i].addEventListener("click", () => {
options[i].setAttribute("data-active", "true"); //set the clicked one to true
});
}
});
function addCtc(ctcNum) {
if (ctcSelect.length > 6) return;
for (let i = 0; i < options.length; i++) {
if (ctcNum == options[i].value) {
return; //number already exist
}
}
let num = options.length;
let option = new Option(ctcNum + "", ctcNum);
if (options.length === 0) {
option.setAttribute("data-active", "true");
} else {
option.setAttribute("data-active", "false");
}
ctcSelect.add(option, undefined);
}
function rmvCtc(ctcNum) {
for (let i = 0; i < options.length; i++) {
if (options[i].value == ctcNum) {
options[i].remove();
}
}
if (options.length > 0) options[0].setAttribute("data-active", "true");
}
#ctcSelect {
width: 70px;
padding: 0;
}
<div>
<lable for="ctcInput">Add CtC #</lable>
<input type="text" id="ctcInput" name="ctcInput" class="input_boxes">
</div>
<div>
<label for="ctcSelect">Select Contact</lable>
<select name="ctcSelect" id="ctcSelect" class="input_boxes"></select>
</div>
<div>
<button type="button" id="removeButton">Remove</button>
</div>

Related

How to make multiple conditions inside single filter

I am trying to make a filter based on checkboxes.
The thing is js ignoring other conditions inside filter when one is active
filterData() {
return this.airlines.filter(x => {
if (this.filters.options.length != 0 || this.filters.airlines.length != 0) {
for (let i = 0; this.filters.options.length > i; i++) {
if (this.filters.options[i] == 0) {
return x.itineraries[0][0].stops == 0;
}
if (this.filters.options[i] == 1) {
return x.itineraries[0][0].segments[0].baggage_options[0].value > 0;
}
}
} else {
return x;
}
})
}
I know that return will stop the current loop, but is there any way to do it correctly?
Update-1: (When to filter record for every case checked OR case)
Replace for loop and all conditions in a single return by && for if and || condition for data:
var chbox = this.filters.options;
return $.inArray(0, chbox) != -1 && x.itineraries[0][0].stops == 0
|| $.inArray(1, chbox) != -1 && x.itineraries[0][0].segments[0].baggage_options[0].value > 0;
Hope this helps !!
$.inArray(value, arr) method will check for each checkboxes and will work for every checked ones .
Update-2 (When to filter record for every case checked AND case)
As per comment below, you are trying to use checkbox on demand so use below code:
var chbox = this.filters.options;
boolean condition = true;
if ($.inArray(0, chbox) != -1) {
conditon = conditon && x.itineraries[0][0].stops == 0;
}
if ($.inArray(1, chbox) != -1) {
conditon = conditon && x.itineraries[0][0].segments[0].baggage_options[0].value > 0;
}
return condition;
Your filter function is returning an object, which ideally should be a boolean value. Please refactor the code as below.
filterData() {
return this.airlines.filter(x => {
let result = false;
if (this.filters.options.length != 0 || this.filters.airlines.length != 0) {
for (let i = 0; this.filters.options.length > i; i++) {
if (this.filters.options[i] == 0) {
result = x.itineraries[0][0].stops == 0;
break;
} else if (this.filters.options[i] == 1) {
result = x.itineraries[0][0].segments[0].baggage_options[0].value > 0;
break;
}
}
}
return result;
})
}

IT Quiz - do not show anwers unless checkbox is selected

I am trying to make sure that at least two checkboxes are selected. If no checkboxes are selected, then an error message appears. This is what I have tried so far:
function quiz4() {
var a4 = document.getElementsByName('q4');
for (i = 0; i < a4.length; i++) {
if(a4[i].checked == false) {
document.getElementById('oCorrectAnswer4').innerHTML = "Please select your answers.";
}
}
if (document.getElementById('q41').checked && document.getElementById('q43').checked) {
document.getElementById('oCorrectAnswer4').innerHTML = "Correct: The answer is " + "<u>A) Keyboard and C) Finger Print Scanner</ul>";
inputs = document.getElementsByName('q4');
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].type == 'checkbox') {
inputs[i].disabled = true;
}//end of if
}//end of for
} else {
document.getElementById('oCorrectAnswer4').innerHTML = "Incorrect: The answer is " + "<u>A) Keyboard and C) Finger Print Scanner</ul>";
inputs = document.getElementsByName('q4');
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].type == 'checkbox') {
inputs[i].disabled = true;
}//end of if
}//end of for
}
}//end of q4
I know this does not work, as the for loop is bypassed (I guess), but I had to start somewhere.
Any help will be appreciated.

javascript check a box with value

I am trying to check boxes in JS. I wan't to only check when the value is equal to 0, if not don't check it. my code :
document.onreadystatechange = function check(e)
{
if (document.readyState === 'complete')
{
var inputElements = document.getElementsByTagName("input");
for(var i=0; i < inputElements.length; ++i)
{
if(document.getElementsByTagName("input")[i].value == "1")
{
document.getElementById("date").checked = false;
}
}
}
}
But it doesn't work. Can you help me?
thanks
What you are doing is, if the checkboxes have value of 1, then you are checking it. Make this change in the code and it should work. Also, you need to check if you are doing this on a checkbox and not on a radio or text:
if(document.getElementsByTagName("input")[i].value == 0 &&
document.getElementsByTagName("input")[i].getAttribute("type") == "checkbox")
{
document.getElementById("date").checked = true;
}
var eles = document.querySelectorAll("input[type='checkbox']");
var len = eles.length,
i = 0,
flag = true;
for (; i < len; i++) {
if (eles[i].value === "1") {
flag = false;
return;
}
}
if (flag) document.getElementById('date').checked = true;
If the value ( 0 or 1 ) is of an <input type='text'>, then change document.querySelectorAll("input[type='checkbox']"); to document.querySelectorAll("input[type='text']");

Checkboxes and trying to save the state of all checkboxes for the user when they return

function getFormState() {
var fields = document.getElementsByTagName('form')[0].elements;
if (fields.length === 0) {
return;
};
for (var i = 0; i <= fields.length - 1; i++) {
var name = fields[i].getAttribute('name');
if (document.getElementByTagName('name').checked === true) {
localStorage.setItem('name', "true");
} else {
localStorage.setItem('name', "false");
}
}
}
function fillFormState() {
var fields = document.getElementsByTagName('form')[0].elements;
if (fields.length === 0) {
return;
};
for (var i = 0; i <= fields.length - 1; i++) {
var name = fields[i].getAttribute('name');
getStatus = localStorage.getItem('name'); {
if (getStatus === "true") {
console.log("its checked");
document.getElementByTagName("name").setAttribute('checked', 'checked');
} else {
console.log("its not checked");
}
}
}
} // run the below functions when the web page is loadedwindow.onload = function () {
// check if HTML5 localStorage is supported by the browser
if ('localStorage' in window && window['localStorage'] !== null) {
// get the form state
getFormState();
// save the state of the form each X seconds (customizable)
setInterval('fillFormState()', 1 * 1000);
}
};
But it doesn't seem to work. And Im trying to figure out why. Im not very experienced with javascript so it might be quite obvious. Sorry for that. Im trying.
I'm guessing your localStorage is never being set because of this loop:
for (var i = 0; i <= fields.length - 1; i++) {
var name = fields[i].getAttribute('name');
if (document.getElementByTagName('name').checked === true) {
localStorage.setItem('name', "true");
} else {
localStorage.setItem('name', "false");
}
}
There is no document.getElementByTagName, and you are also searching for "name" instead of your variable name.
for (var i = 0; i <= fields.length - 1; i++) {
var name = fields[i].getAttribute('name');
if (fields[i].checked === true) { //Check the current field
localStorage.setItem(name, "true"); //Set the actual name, not "name"
} else {
localStorage.setItem(name, "false");
}
}

Mark unmark javascript?

I've got a function to select all checkboxes in a table:
<script type="text/javascript">
function checkAll() {
var tab = document.getElementById("logs");
var elems = tab.getElementsByTagName("input");
var len = elems.length;
for (var i = 0; i < len; i++) {
if (elems[i].type == "checkbox") {
elems[i].checked = true;
}
}
}
But I can't get it to uncheck them all if they are checked. How could I do that?
<th width='2%'>Mark</th>";
Also in javascript is it possible to rename "Mark" to "Un-Mark" if I execute checkAll()?
This should do both of the things u want:
function checkAll(obj) {
var tab = document.getElementById("logs");
var elems = tab.getElementsByTagName("input");
var len = elems.length;
for (var i = 0; i < len; i++) {
if (elems[i].type == "checkbox") {
if(elems[i].checked == true){
elems[i].checked = false;
}
else{
elems[i].checked = true;
}
}
}
if(obj.innerHTML == 'Mark') { obj.innerHTML = 'Unmark' }
else { obj.innerHTML = 'Mark' }
}
html:
<th width='2%'>Mark</th>";
1) why don't u use some js framework, like jQuery?
2) to remove checked, use elems[i].removeAttribute('checked') or set elems[i].checked = false;
3) to rename, you have to set it's innerHTML or innerText to Un-Mark
Add a little more logic to see if they're already checked. This will invert their current checked state.
for (var i = 0; i < len; i++) {
if (elems[i].type == "checkbox") {
if (!elems[i].checked) {
elems[i].checked = true;
}
else elems[i].checked = false;
}
}
If you just want to uncheck all, simply use:
elems[i].checked = false;
This will check them all regardless of their current state, or uncheck them all, depending on the current text of "Mark" or "Unmark".
<script type="text/javascript">
function checkAll(obj) {
var tab = document.getElementById("logs");
var elems = tab.getElementsByTagName("input");
var len = elems.length;
var state = obj.innerHTML == 'Mark';
for (var i = 0; i < len; i++) {
if (elems[i].type == "checkbox") {
elems[i].checked = state;
}
}
obj.innerHTML = state ? 'Mark' : 'Unmark';
}
And then the HTML changes to:
<th width='2%'>Mark</th>";
To uncheck, try:
elems[i].checked = false;
i sugest you use jquery, everything is easier.
with jquery you just have to do something like this (+/-):
$(function(){
$('a.ClassName').click(function(){
var oTbl = $('#tableID');
$('input[type="checkbox"]', oTbl).attr("checked", "checked")
});
})

Categories

Resources