Identify points in each quadrant of a canvas

How do you divide a canvas into four quadrants and then identify points drawn at random in each quadrant?

Here is my not so futile attempt:

var myCanvas = document.getElementById("showCanvas");
var myContext = myCanvas.getContext("2d");

var xAxis = [];
var yAxis = [];

for (var i = 0; i < 4; i++) {
  var x = Math.floor(Math.random() * 600);
  var y = Math.floor(Math.random() * 350);
  var r = 5;
  xAxis.push(x);
  yAxis.push(y);
  myContext.arc(x, y, r, 0, 2 * Math.PI, true);
  myContext.closePath();
  myContext.fill();
}

var startingPoint = xAxis[0] + ", " + yAxis[0];
var endingPoint = xAxis[3] + ", " + yAxis[3];
var horizontalSlash = myCanvas.width / 2;
var verticalSlash = myCanvas.height / 2;
var remainder = horizontalSlash % verticalSlash;

And the result should show up in these tags:

<h3>The starting point of the line is: <label id="sumPoints">e.g. top, right</label></h3>
<h3>The end point of the line is: <label id="sumPoints">e.g. bottom, left</label></h3>

how to set DTL(Django Tamplate language) for loop and value through javascript

I want to set django for loop to set value through javascript like this. is this correct way? or Is there any other way?

    var table = $('.checkbox-datatable').DataTable({
        'scrollCollapse': true,
        'autoWidth': false,
        'responsive': true,
        "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
        "language": {
            "info": "_START_-_END of TOTAL_ entries",
            searchPlaceholder: "Search",
            paginate: {
                next: '<i class="ion-chevron-right"></i>',
                previous: '<i class="ion-chevron-left"></i>'  
            }
        },
        'columnDefs': [{
            'targets': 0,
            'searchable': false,
            'orderable': false,
            'className': 'dt-body-center',
            'render': function (data, type, full, meta){
                return '<div class="dt-checkbox"><input type="checkbox" name=

"id[]" id="chkuser"  value="' +  {% for dd in departmentData %}{{dd.id}}{% endfor %} + '" /><span class="dt-checkbox-label"></span></div>';
        }
    }],
    'order': [[1, 'asc']]
});

how to do user authentication if user and admin is in a single collection in mongoose in nodejs express? does aggregation work

this is my schema

const mongoose = require ('mongoose');

const adminSchema = new mongoose.Schema({
    name:String,

    password:String,
    user:[{
        name:String,
        email:String,
        password:String
    }
    ]

})

var user = mongoose.model("Admin",adminSchema)
module.exports = user
;

admin login works properly
the problem is
admin can (its available outside as per the schema ) login as user and user is not able to login(cuz its inside as an array )
here is my data base collection:

> db.admins.find().pretty()    
{
        "_id" : ObjectId("62ad807e5c40fa9cdd5fb584"),
        "name" : "admin",
        "password" : "$2b$10$wJLM8sXoRbFjFlK6jyjEb.a6n60SlckVBfG1wbDd4A/0e5UOAABGC",
        "__v" : 0,
        "user" : [
                {
                        "name" : "jghuter",
                        "email" : "[email protected]",
                        "password" : "$2b$10$m3sna5erYQ4RJ95WIqP6MeAHvbTTfrsKn4F7y7yPpZoxvYcRltsba",
                        "_id" : ObjectId("62ad9d0c3b127dc669f423c7")
                }]}

load different vue component inside another vue component upon user selects an option from select list

In my vuejs application I have a component called

commonform.vue

In that form, I have a dropdown list to user to pick a schedule type.

Depending on the user’s type selection, rest of the form fields need to be changed.

I have three common fields for all the selected types.

user name, schedule name and schedule type , these fields are common and they are in the commonform.vue. But rest of the fields are going to be changed according to user’s schedule type selection…

I have created separate vue components for them as follows in order to avoid too many if-else logics in the commonform.vue,

typeonefields.vue and typetwofields.vue… etc

My question is,

How can I load these components inside fullform.vue depending on the schedule type selection?

This is my schedule type select

<cs-dashboard-select
                                        :options="[
                                            { value: '1', label: 'Type common'},
                                            { value: '2', label: 'Type one'},
                                            { value: '3', label: 'Type two'},
                                            { value: '4', label: 'Type three'},
                                        ]"
                                        name="schedule_type"
                                    > Select type
                                    </cs-dashboard-select>

If the user selects Type one, then the form fields should be like,

user name, schedule name, schedule type, type one field

If it’s type two then,

user name, schedule name, schedule type, type two field

Insert null object to objects of array javascript

i have an array :

let data = {
 {date: 3, type: solid; total: 3},
 {date: 5, type: solid; total: 10}
}

is it possible to convert it into new array with output like this :

data: {
0: {date: 1, type: solid; total: null},
1: {date: 2, type: solid; total: null},
2: {date: 3, type: solid; total: 3},
3: {date: 4, type: solid; total: null},
4: {date: 5, type: solid; total: 10},
5: {date: 6, type: solid; total: null},
6: {date: 7, type: solid; total: null},
....
27: {date: 28, type: solid; total: null},
28: {date: 29, type: solid; total: null},
29: {date: 30, type: solid; total: null},
30: {date: 31, type: solid; total: null}
}

i want the length of new array is same as the total date of current month
thanks before

Reload Page From Iframe in JS

I have an iframe and I want to refresh the main page through it. I’ve tried functions such as window.location.reload() etc.. but it seems it doesn’t work.
I need to put the reload function on the iframe not on the main page.
I could get as much as document.referrer to get the main page.

Iframe codesandbox
SEE THIS

Main page codesandbox SEE THIS

 <div class="iframe-container">
      <iframe class="iframe-layout" src="https://zqdqmn.csb.app/"></iframe>
  </div>

Iframe Part

  <script>
  
    function redirectToGoogle() {
      const mainUrl = document?.referrer

      window.location.href = `${mainUrl}`

      // window.open(mainUrl,"_self")
    }

  </script>
</body>

How to Detect mousewheel Movement and Make It not Incremental

May you all have a good day Today!

I finally made my scrollable tab, but it’s not what I want. Because, when I scroll up one time it moves to the previous tab in which one scroll is one movement, it’s incremental. But, what I want is as much I scroll the mouse once, it changes to another tab. I already add the console.log to my code below. My reference is Fullpage JS and this landing page. Please go see it if you don’t understand my explanation. Please help me to get through this. So, here’s my code :

//Add & remove class tab, contents, & menu onclick & wheel
window.addEventListener('DOMContentLoaded', ()=> {
    let tabs = document.querySelectorAll('.tab');
    let content = document.querySelectorAll('.content');
    let firstTab = function(tabs) {tabs.classList.add('tab-active')};
    let firstContent = function(content) {content.classList.add('content-active')};
    let activeTab = 0;
  
    firstTab(tabs[0]);
    firstContent(content[0]);
        
    for (let i = 0; i < tabs.length; i++) {            
        tabs[i].addEventListener('click', () => tabClick(i));
        }

    function detect(e) {
        var delta = null,
            direction = false;
        if(!e) {e = window.event;}
        if(e.wheelDelta) {delta = e.wheelDelta / 60;
        } else if(e.detail) {delta = -e.detail / 2;}
        if(delta !== null) {
            direction = delta > 0 ? 'up' : 'down';}
        return direction;
    }

    function handle(direction) { //mousewheel to change tabs
        console.log(direction);
        if(direction == 'down') {
            if(activeTab >= tabs.length - 1) {
            activeTab = 0;
            tabClick(activeTab);
            } else {
            tabClick(activeTab + 1);
            }
        } else if(direction == 'up') {
            if(activeTab === 0) {
            activeTab = tabs.length - 1;
            tabClick(activeTab);
            } else {
            tabClick(activeTab - 1);
            }
            } else {
            // this means the direction of the mouse wheel could not be determined
        }
    }
    document.onmousewheel = function(e) {handle(detect(e));};
    if(window.addEventListener) {document.addEventListener
    ('DOMMouseScroll', function(e) {handle(detect(e));});
    }

        
        function tabClick(currentTab) {
          removeActive();
            //Add Active Class
            tabs[currentTab].classList.add('tab-active');
            content[currentTab].classList.add('content-active');
            activeTab = currentTab;
        }  
        function removeActive() {
          for (let i = 0; i < tabs.length; i++) {
            //Remove Active Class
            content[i].classList.remove('content-active');
            content[i].classList.add('content-show');
            setTimeout(function() {
              content[i].classList.remove('content-show');
            },1500);
            tabs[i].classList.remove('tab-active');
          }
         }
       })
        /* WHOLE CONTAINER */
        .container {
          width: 96vw;
          height: 96vh;
        }
        
        /* TABS */
        .tabs {
            display: flex;
            height: 50px;
            overflow: hidden;
            align-items: center;
            justify-content: center;
            width: 100%;
        }

        .tab {
            font-size: 14px;
            padding: 5px 10px;
            cursor: pointer;
            letter-spacing: 2px;
            text-alignment: center;
        }

        #red.tab-active {background-color: rgb(245, 66, 66);}
        #blue.tab-active {background-color: rgb(66, 135, 245);}
        #yellow.tab-active {background-color: rgb(245, 215, 66);}
        #green.tab-active {background-color: rgb(56, 235, 98);}
        #cyan.tab-active {background-color: rgb(79, 247, 219);}


        /* TAB CONTENTS */
        .contents {
            width: 100%;
            margin-top: 5px;
            height: 80%;
        }

        .content {
            width: 96%;
            height: 80%;
            display: none;
            padding: 0;
            margin: 0;
            border: none;
            position: absolute;
        }

        .content-show {
            display: flex;
            animation-name: fade-out;
            animation-duration: 2.5s;
        }
        
        @keyframes fade-out {
            0% {
                opacity: 1;
                display: flex;
            }
            99% {
                opacity: 0;
                display: flex;
            }
            100% {
                opacity: 0;
                display: none;
            }
        }

        .content-active {
            display: flex;
            border: none;
            justify-content: center;
            animation-name: fade-in;
            animation-duration: 2.5s;
        }

        @keyframes fade-in {
            0% {
                display: none;
                opacity: 0;
            }
            1% {
                display: block;
                opacity: 0.01;
            }
            100%{
                display: block;
                opacity: 1;
            }
        }

        #red.content-active {background-color: rgb(245, 66, 66);}
        #blue.content-active {background-color: rgb(66, 135, 245);}
        #yellow.content-active {background-color: rgb(245, 215, 66);}
        #green.content-active {background-color: rgb(56, 235, 98);}
        #cyan.content-active {background-color: rgb(79, 247, 219);}
<div class="container">
   <div class="tabs">
       <div id="red" class="tab">RED</div>
       <div id="blue" class="tab">BLUE</div>
       <div id="yellow" class="tab">YELLOW</div>
       <div id="green" class="tab">GREEN</div>
       <div id="cyan" class="tab">CYAN</div>
   </div>

   <div class="contents">
       <div id="red" class="content"></div>
       <div id="blue" class="content"></div>
       <div id="yellow" class="content"></div>
       <div id="green" class="content"></div>
       <div id="cyan" class="content"></div>
   </div>
</div>

Thanks A lot Guys..

Compare array in javascript and create a new array of elements which is being removed

I’ve got two color arrays and I want to return those objects which are in local array and are not available in API response.

API resposne array

[
    {
        "id": 25,
        "color": "#00ad02"
    },
    {
        "id": 28,
        "color": "#e1b12c"
    }

]

Local array

[
    {
        "id": 26,
        "color": "#00ad02",
    },
    {
        "color": "#e1b12c",
        "id": 28,
    }
]

Loop over both arrays and return the one which are not contained by the API response array. Here I am seeking output of id 25.

How to loop through an array of Objects, Keep count of one of the Object’s value and then return the one that occurs most

I have been trying to get the top n languages in an array of country objects and return the top n languages as an object of the language and it’s count value. I tried using two loops, one nested in the other but I got stuck.
Here is a short example of the array of country Objects…

const countries = [
{
 name: 'Afghanistan',
 capital: 'Kabul',
 languages: ['Pashto', 'Uzbek', 'Turkmen'],
 population: 27657145,
 flag: 'https://restcountries.eu/data/afg.svg',
 currency: 'Afghan afghani'
},
{
 name: 'Åland Islands',
 capital: 'Mariehamn',
 languages: ['Swedish'],
 population: 28875,
 flag: 'https://restcountries.eu/data/ala.svg',
 currency: 'Euro'
},
{
 name: 'Albania',
 capital: 'Tirana',
 languages: ['Albanian'],
 population: 2886026,
 flag: 'https://restcountries.eu/data/alb.svg',
 currency: 'Albanian lek'
},
{
 name: 'Algeria',
 capital: 'Algiers',
 languages: ['Arabic'],
 population: 40400000,
 flag: 'https://restcountries.eu/data/dza.svg',
 currency: 'Algerian dinar'
},
{
 name: 'American Samoa',
 capital: 'Pago Pago',
 languages: ['English', 'Samoan'],
 population: 57100,
 flag: 'https://restcountries.eu/data/asm.svg',
 currency: 'United State Dollar'
},
{
 name: 'Andorra',
 capital: 'Andorra la Vella',
 languages: ['Catalan'],
 population: 78014,
 flag: 'https://restcountries.eu/data/and.svg',
 currency: 'Euro'
},
{
 name: 'Angola',
 capital: 'Luanda',
 languages: ['Portuguese'],
 population: 25868000,
 flag: 'https://restcountries.eu/data/ago.svg',
 currency: 'Angolan kwanza'
},
{
 name: 'Anguilla',
 capital: 'The Valley',
 languages: ['English'],
 population: 13452,
 flag: 'https://restcountries.eu/data/aia.svg',
 currency: 'East Caribbean dollar'
},const countries = [
{
 name: 'Afghanistan',
 capital: 'Kabul',
 languages: ['Pashto', 'Uzbek', 'Turkmen'],
 population: 27657145,
 flag: 'https://restcountries.eu/data/afg.svg',
 currency: 'Afghan afghani'
},
{
 name: 'Åland Islands',
 capital: 'Mariehamn',
 languages: ['Swedish'],
 population: 28875,
 flag: 'https://restcountries.eu/data/ala.svg',
 currency: 'Euro'
},
{
 name: 'Albania',
 capital: 'Tirana',
 languages: ['Albanian'],
 population: 2886026,
 flag: 'https://restcountries.eu/data/alb.svg',
 currency: 'Albanian lek'
},
{
 name: 'Algeria',
 capital: 'Algiers',
 languages: ['Arabic'],
 population: 40400000,
 flag: 'https://restcountries.eu/data/dza.svg',
 currency: 'Algerian dinar'
},
{
 name: 'American Samoa',
 capital: 'Pago Pago',
 languages: ['English', 'Samoan'],
 population: 57100,
 flag: 'https://restcountries.eu/data/asm.svg',
 currency: 'United State Dollar'
},
{
 name: 'Andorra',
 capital: 'Andorra la Vella',
 languages: ['Catalan'],
 population: 78014,
 flag: 'https://restcountries.eu/data/and.svg',
 currency: 'Euro'
},
{
 name: 'Angola',
 capital: 'Luanda',
 languages: ['Portuguese'],
 population: 25868000,
 flag: 'https://restcountries.eu/data/ago.svg',
 currency: 'Angolan kwanza'
},
{
 name: 'Anguilla',
 capital: 'The Valley',
 languages: ['English'],
 population: 13452,
 flag: 'https://restcountries.eu/data/aia.svg',
 currency: 'East Caribbean dollar'
}]

And this is what I’m expecting to get


// My output should look like this
console.log(mostSpokenLanguages(countries, 5))
/*[
{country: 'English',count:91},
{country: 'French',count:45},
{country: 'Arabic',count:25},
{country: 'Spanish',count:24},
{country:'Russian',count:9}
]*/

This is what I tried


const mostSpokenLanguage = (arr, count) => {
let languageCountObjArr = [];
let languagesArr = arr.map(countryObj => countryObj.languages);
console.log('Languages Array', languagesArr);
languagesArr.forEach(languageArr => {
 for (let i = 0; i < languageArr.length; i++) {
   /* I GOT STUCK HERE
     let langObj = {
     country: languageArr[i],
     count: 1
   };
   if (languageCountObjArr[i].country === languageArr[i]) {
     let
   }*/
   languageCountObjArr.push(langObj);
 }
});
languageCountObjArr = languageCountObjArr.slice(count);
return languageCountObjArr;
};

I just started JavaScript a couple of weeks now and this stuff has been giving me worries. Please I would be very happy if I can get the answer to this question.

How to select all elements with a class name and change its border [duplicate]

const signUpInfo = document.getElementById('SignUpInfo');
const signUpName = document.getElementById('signUpName');
const signUpEmail = document.getElementById('signUpEmail');
const signUpPass = document.getElementById('signUpPass');

signUpInfo.addEventListener('click', () => {
    if(signUpName.value == "" || signUpEmail.value == "" || signUpPass.value == ""){
        document.getElementById('emptyInput').style.color = "red"
        document.getElementsByClassName('.signUpInput').style.border = "1px solid red"
    }
});
        <div class="form-container sign-up-container">
            <form action="#">
                <h1>Create Account</h1>
                <span id="emptyInput">Please fill out the following fields</span>
                <input type="text" class="signUpInput" id="signUpName" placeholder="Name" />
                <input type="email" class="signUpInput" id="signUpEmail"placeholder="Email" />
                <input type="password" class="signUpInput" id="signUpPass"placeholder="Password" />
                <input type="password" class="signUpInput" placeholder="Confirm Password" />
                <button id="SignUpInfo">Sign Up</button>
            </form>
        </div>

All I need to do is if all fields are empty I want the text to turn red which works and I also want the border of the input to be red.

Make a TextBox required if a certain Radio button is selected

I want to attain that a textbox will be changed to required=”true” if a certain radio value is selected as Cash

this is my html form:

<label class="radio"> <input type="radio" name="payment" value="Cash" id="cashpayment" checked><span><img width="30" src="images/icons8-cash-in-hand-48.png"/></span></label>
<label class="radio"> <input type="radio" name="payment" value="SD" id="sdpayment"><span><img width="30" src="images/icons8-budget-48.png"/></span></label>
<label class="radio"> <input type="radio" name="payment" value="Budget" id="budgetpayment"><span><img width="30" src="images/icons8-office-48.png"/></span></label>

here is my jQuery code (jQuery v3.3.1)

$(document).ready(function(){
    $("input[name='type']:radio").change(function(){
        if($(this).val() == 'Cash')
        {
          $('#cashtender').attr('required');
        }
        else if($(this).val() == 'SD')
        {
          $('#cashtender').removeAttr('required');
        }
        else if($(this).val() == 'Budget')
        {
          $('#cashtender').removeAttr('required');
        }
    });
});

it’s not working. please help

Jquery event not working after append html

I have ajax request and when the ajax success I’m replacing the content using html from the ajax response.

The controller is like this:

$html = view('payroll-cutoff.data-attendance-group', compact('payroll_group', 'payroll_cutoff_group'))->render();
return response()->json([
    'success' => true,
    'data' => $html,
]);

Inside ajax success, I have some code to manipulate the view. But somehow after I successfully replacing the html content of tbody, the jquery event not working anymore even though when I inspect the element I successfully replacing the content using html from ajax response.

 success:function(response){
         // thisObj = '.process-attendance'
         let element = response.data;
         let el_data = $(element).filter('.group-payroll').find('.body-component').html();
         thisObj.closest('table').find('tbody').html(el_data);

         // code bellow not working
         thisObj.closest('table').find('thead').addClass('done-group');
         thisObj.closest('table').find('tbody').addClass('done-group');
        },

For example is I have this on click function, but it’s not working anymore after ajax success.

$(".show-emp").click(function () {
   showEmployee($(this));
});

function showEmployee(el)
{
    $(el).closest('tbody').find('.employee').toggle();
    $(el).closest('tbody').find('.employee-head').toggle();
}

And this is the view:

<table class="table group-payroll">
    <thead class="head-component">
        <tr>
            <th colspan="7"></th>
        </tr>
    </thead>
    <tbody class="body-component">
        <tr>
            <td style="width: 100%" colspan="7">
                <a href="javascript:void(0)" class="btn btn-sm mb-2 checkall process-attendance">Process Attendance</a>
                <a href="javascript:void(0)" class="btn btn-sm mb-2 checkall me-5 show-emp"></a>5 Employee
            </td>
        </tr>
        <tr class="employee-head" style="display: none">
            <td>No</td>
            <td>Name</td>
            <td>HK</td>
            <td>IN</td>
        </tr>
        <input type="hidden" class="process-done" value="">
        <input type="hidden" name="employee_id[]" class="employee_id" value="">
        <tr class="employee" style="display: none">
            <td></td>
            <td></td>
            <td></td>
            <td></td>
        </tr>
    </tbody>
</table>

problems with variable value that initializes with wrong value not following condition

I am trying to make a method that checks if my screen is in share mode, so I made a logic that if my variable this.share is TRUE, it is shared, but if the variable this.share is FALSE, the screen is not shared.

When loading the screen, the method is called, and even though my condition is correct, the return of the variable is wrong, the return only appears as correct, after the screen loads and I perform some action like clicking a button for example, I think it may have to do with loading, or asyncs functions.

For example, the expected return is TRUE, but when loading the variable the return is FALSE and after an action the variable returns TRUE,

declaration:

this.shareKey

method to check.

      this.router.events.subscribe((event: any) => {
        let r = this.route;
        while (r.firstChild) {
          r = r.firstChild;
        }
        r.params.subscribe((param) => {
          this.shareKey =
            param.secretkey != null || param.secretkey != undefined;
        });
      });

I tried to do this by calling it in a service, but it didn’t work.

How can you concatenate or group multiple strings within the same array?

If given an array of elements let array = ['apple', 'banana', 'salami', 'cheese']

What is the best practice to get this result : ['applebanaa' , 'salamicheese']

My first thought was to use reduce which works but it concatenates every string into one long string. See example below

```let array = ['apple', 'banana', 'salami', 'cheese']"

array.reduce((a,b) => a + b);

output : applebanaasalamicheese```

I feel like I am on the right track here. Maybe I need to do something to the equation within the parenthesis of reduce to get the result I am looking for?

I am relatively new to Javascript, but I hope that this question is clear enough to follow. Thanks in advance for any help!

Best Regards