How can I disable other checkboxes(Dynamically Created) if I checked one?

How can I disable other checkbox if I clicked one I..e dynamically created checkbox using “input type=checkbox”

@if (ViewBag.Products != null)

{

foreach (var item in ViewBag.Products)

{

    <label class="PillList-item">

        <input id="Check" type="CheckBox" name="@item.ProductID"/>

        <span class="PillList-label" >

            @item.Products

            <span class="Icon Icon--checkLight Icon--smallest"><i class="fa fa-check"></i></span>



        </span>

      

    </label>





}

}

Saving updates into localstorage and having a history of previous inputs

I have the following code, and what I’m trying to do is save the chosen date and time with every button click to have a record of the previous inputs or sessions even after refreshing the page, additionally each session should be limited by 5 clicks tops.

function store()  {
    
    var time = document.querySelector("option").innerText;
    var date = document.querySelector("input").value;

    localStorage.setItem(JSON.stringify(time), date);
    console.log(localStorage);

    //store in object
    const items = { ...localStorage};
    console.log(Object.entries(items))
}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Performax Cinema</title>
</head>

<body>
    <input type="date" id="date" required/>
    
    <select id="time" class="form-control" required>
        <option value="0">10:00 AM - 12:00 PM</option>
        <option value="1">12:00 AM - 14:00 PM</option>
        <option value="2">14:00 AM - 16:00 PM</option>
        <option value="3">16:00 AM - 18:00 PM</option>
        <option value="4">18:00 AM - 20:00 PM</option>
        <option value="5">20:00 AM - 22:00 PM</option>
    </select>
    <button id="btn" onclick="store()">add</button>
    <script src="main.js"></script>
</body>

</html>

for loop array in vuejs

<p v-for="(product_value, product_key, product_index) in item.product">
    {{product_key}} :{{product_value}}
    <div v-for="(item_a,index_a) in product_value" :key="index_a">
        ss{{item_a}}
    </div>
</p>

data show in view

abc :[ { "Colorx": "1"... } ]
ao_so_mi :[ { "ColorBlue": "1" .... }, { "ColorRed": "1", .... } ]

database value

{"abc":[{"Colorx":"1" ... }],"ao_so_mi":[{"ColorBlue":"1" .... },{"ColorRed":"1", ... }
return data 
this.$set(this,'items',response.data.product.data);
    for (var i = 0; i < this.items.length; i++) {
        this.items[i].product = JSON.parse(this.items[i].product);
i wanna show same : 
+item #abc : 
- Colorx : qty 1
+item #ao_so_mi : 
- ClolorBlu: qty 1
- ColorRed: qty 1

it took up quite a bit of my time, thanks for any help

Attribute undefined in custom directive in angularjs

I am creating a custom directive in angularjs, but for some attributes i am receiving undefined value.

function processinfo(ProcessInfoService, $timeout) {
        console.log("processInfo directive");
        return {
            restrict: 'E',
            scope: {
                start: '=',
                end: '=',
                uuid: '='
            },
            templateUrl: 'k2-modules/js/directives/templates/processInfoTemplate.html',
            controller: function($scope) {
                var self = this;
                console.log($scope.uuid);   // undefined
                console.log($scope.end);    // 164982555555
                console.log($scope.start);  // 0
                self.processData = ProcessInfoService.getInfo($scope.start, $scope.end);
            }
        }
    }
<processinfo start="0" end="164982555555" uuid="a57cf6f8"></processinfo>

For uuid I am getting undefined but for end and start values everything is working fine. I don’t know why this is happening since syntax is same for all three. Any help will be appreciated

Counting values below a threshold Javascript looping

this could be a very silly question. I am calculating flat rate and overtime pay. My aim is to count hours below a threshold of 2250 minutes for a certain overtime type. Lets say there is overtime type 1 and type 2. I can count the value fine for type 1 for example using a for loop, but once the conditions of the for loop are exceeded i lose the value (of course). But im wondering if there is a way to retain the value before it was exceeded, because i want to use it in a calculation.

let hours = 0
for (let i = data.type1 + data.type2; i < 2250; i+=data.type1) {
                        hours = data.type1                      
                                                
                    }

console.log(hours)

The above for loop gives an answer of 1800 before it gets exceeded, and obviously once the conditions are no longer valid its gone. Im wondering what I can do to not lose the value of 1800, im guessing I may need to look at other configurations, but any help will be great

Copy to clipboard functionality making page jump to the bottom

I am using the CopyToClipboard functionality found on this site. Url in the comments in the code below. This works, but in Chrome/Brave/Opera browsers, it makes the page jump to the bottom. My own trigger for the code is also below. I’m trying to trigger this from a span, but having it as an a (link) element does the same thing. Page jumps to the bottom.

// Usage: copyToClipboard('some text')
// https://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript/69609643#69609643
 function copyToClipboard(text) {
    var doc = document;

    // Create temporary element
    var textarea = doc.createElement('textarea');
    textarea.style.position     = 'absolute';
    textarea.style.opacity      = '0';
    textarea.style.left         = "-9999px";
    textarea.textContent        = text;

    doc.body.appendChild(textarea);
    textarea.focus();
    textarea.setSelectionRange(0, textarea.value.length);

    // Copy the selection
    var success;
    try {
        success = doc.execCommand("copy");
    }
    catch(e) {
        success = false;
    }
    textarea.remove();
    return success;
}

My HTML that calls this function:

<span class="">
<span tabindex="0" class="uk-button"
onclick="copyToClipboard('URL_GOES_HERE')"
data-uk-tooltip="My tooltip content; ">     
<img src="SVG_ICON_HERE" width="20"/>
</span>  
</span>

Why is the JS making the page jump?

How to reset a string variable after for js

How to reset a string variable after for, I want to insert through innerHTML the selected value from the pressed checkbox, by pressing the button in . But I don’t understand how best to reset the variable, but it wouldn’t duplicate the past values + the present ones.

<div class="container">
   <div class="el"></div>  
       <label for="checkbox1">carWashing</label>
       <input type="checkbox" value="carWashing" id="checkbox1" name="checkbox1">
   </div>  
   <div class="el"></div>  
       <label for="checkbox2">suspensionDiagnostics</label>
       <input type="checkbox"  value="suspensionDiagnostics id="checkbox2" name="checkbox2">
    </div>  
    <div class="el"></div>  
       <label for="checkbox3">replacingFilters</label>
      <input type="checkbox" id="checkbox3" value="replacingFilters" name="checkbox3">
    </div>  
</div>
<button class="btn" id="btn"></button>

<div class="l">
    <ul class="ul" id="ul">

    </ul>
</div>

<script>
let ul = document.getElementById("ul")
let check1 = document.getElementById("checkbox1")
let check2 = document.getElementById("checkbox2")
let check3 = document.getElementById("checkbox3")
let sumLi=''
let checkboxesAll = new Array(check1,check2,check3)
//let checkboxesAll = new Array (document.getElementsByName('checkbox'));
console.log(checkboxesAll)

function start() {
  for (let index = 0; index < checkboxesAll.length; index++) {
     if (checkboxesAll[index].checked) {
         sumLi+='<li>'+ checkboxesAll[index].value + '</li>'
     } else {
         console.log('не нажат')
     }
  }
  console.log(sumLi)
  const arr=sumLi.split("</li>")
  console.log(sumLi)

   ul.innerHTML+=sumLi
 }

document.getElementById('btn').onclick = start;

Angular How to change the label of a mat table at runtime

I have an angular mat table with pagination like in their official documentation: https://material.angular.io/components/table/examples . How could I change at runtime the value of a label? The table is created but I want to change a value in the table’s header without recreating the table. Is there any possibility? For example, in the table below I want to change the value for the header and instead to have “Symbol” to have “something” without recreating the whole tabel. So just a change of a label.

  <table mat-table [dataSource]="dataSource">

    <!-- Position Column -->
    <ng-container matColumnDef="position">
      <th mat-header-cell *matHeaderCellDef> No. </th>
      <td mat-cell *matCellDef="let element"> {{element.position}} </td>
    </ng-container>

    <!-- Name Column -->
    <ng-container matColumnDef="name">
      <th mat-header-cell *matHeaderCellDef> Name </th>
      <td mat-cell *matCellDef="let element"> {{element.name}} </td>
    </ng-container>

    <!-- Weight Column -->
    <ng-container matColumnDef="weight">
      <th mat-header-cell *matHeaderCellDef> Weight </th>
      <td mat-cell *matCellDef="let element"> {{element.weight}} </td>
    </ng-container>

    <!-- Symbol Column -->
    <ng-container matColumnDef="symbol">
      <th mat-header-cell *matHeaderCellDef> Symbol </th>
      <td mat-cell *matCellDef="let element"> {{element.symbol}} </td>
    </ng-container>

    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
  </table>

  <mat-paginator [pageSizeOptions]="[5, 10, 20]"
                 showFirstLastButtons 
                 aria-label="Select page of periodic elements">
  </mat-paginator>
</div>

How to call a function on radio button to update api

I have this survey screen whis fetch questions from api and renders them usin Flatlist component passing them to another component which renders a single question like this.

const state = useSelector(state => state);
  const data = state.questions;
  useEffect(() => {
    dispatch(fetchQuestions(state.user.id));
  }, []);

and then pass this data to Flatlist like this:

  <FlatList
      data={data}
      keyExtractor={(item, index) => 'unique' + index}
      showsVerticalScrollIndicator={false}
      renderItem={({item, index}) => {
        return (
          <Items
            question={item.question}
            answer={item.answer}
            questionId={item.id}
          />
        );
      }}
    />

this is my item component:

const Header = props => {
  const [radioStatus, setRadioStatus] = useState(props.answer);
  const dispatch = useDispatch();
  const state = useSelector(state => state);
  const updateStatus = ans => {
    const questionId = props.questionId;
    const data = {
      questionId,
      answer: radioStatus,  
    };
    dispatch(addQuestions(data));
  };
  useEffect(() => {
    updateStatus();
  }, [radioStatus]);
  return (
    <View style={styles.container}>
      <Text style={styles.question}>{props.question}</Text>
      <View
        style={[
          styles.row,
          {
            marginTop: heightPercentageToDP(2),
          },
        ]}>
        <RadioButton.Android
          value="first"
          status={radioStatus == 'yes' ? 'checked' : 'unchecked'}
          // onPress={() => setRadioStatus('yes')}
          onPress={() => {
            setRadioStatus('yes');
            updateStatus('yes');
          }}
          color={colors.lightBlack}
        />
        <Text style={styles.option}>{'Yes'}</Text>
      </View>
      <View style={styles.row}>
        <RadioButton.Android
          value="second"
          status={radioStatus == 'no' ? 'checked' : 'unchecked'}
          // onPress={() => setRadioStatus('no')}
          onPress={() => {
            setRadioStatus('no');
            updateStatus('no');
          }}
          color={colors.lightBlack}
        />
        <Text style={styles.option}>{'No'}</Text>
      </View>
    </View>
  );
};

I want to submit answers through api when submit is pressed but i don’t understand how to update each question individually. I have tried storing every answer to global state and then updating that state on each radio btn press but questions are ushed into state redundently like if answers on one question is alredy there it will be pushed again on button press.
This is the UI..
All i want to do is fetch questions and their answers if user have already responded show them here and if user updates, update them by calling a function on submit button.

Helper firebase.firestore query function keeps returning undefined even though I want it to return a boolean

My over all goal is to see if a user has made a session in the past on the site. I want to make a helper function that returns a boolean depending on if a user has created a session or not. I am using firebase.firestore() and firebase.auth() for this project. My plan is to query firestore and get an array of emails that are correspond to all the sessions. Then I will loop through all those emails. If one matches the firebase.auth().currentUser.email then I will return true. If it doesnt match then I will return false.

The function keeps returning undefined. I thought it was because you cannot have a break in a forEach loop which is what I was using before.

How to break out of the querySnapshot forEach loop method?

After I read this post I converted my forEach loop into a regular for loop. This did not fix the problem and it keeps returning undefined instead of a boolean.

  // inputs in a user email
  // outputs a boolean 
  // (t if they have made a session)
  // (f if they haven't made a session)
  function madeSessionHelper (userMail) {
    let res;
    firebase.firestore().collection('sessions')
    .get()
    .then((querySnapshot) => {
      for (let i in querySnapshot.docs) {
        const doc = querySnapshot.docs[i]
        if (doc.data().Goal_Email === userMail) {
          res = true;
          break;
        } else {
          res = false;
          break;
        }
      }
      return res;
    })
  }
  console.log(madeSessionHelper("[email protected]"))

req.body returns undefined when I use express router, even though I used express.urlencoded

Here is my server.js code:

const express = require("express");
const articleRouter = require("./routes/articles");
const app = express();

app.set("view engine", "ejs");

app.use("/articles", articleRouter);

app.use(express.urlencoded({ extended: true }));

app.get("/", (req, res) => {
  const articles = [
    {
      title: "Test Article 1",
      createdAt: new Date(),
      description: "Test description 1",
    },
    {
      title: "Test Article 2",
      createdAt: new Date(),
      description: "Test description 2",
    },
  ];
  res.render("articles/index", { articles: articles });
});

// app.post("/articles", (req, res) => {
//   console.log(req.body);
// });

app.listen(3000, () => {
  console.log("Listening on port 3000...");
});

This code (which I commented) works fine

app.post("/articles", (req, res) => {
  console.log(req.body);
});

But when I try to do the same thing with router, it returns undefined. Here is my articles.js code from routes folder:

const express = require("express");
const router = express.Router();

router.get("/new", (req, res) => {
  res.render("articles/new");
});

router.post("/", (req, res) => {
  console.log(req.body);
});

module.exports = router;

Here id new.ejs code, where the from is:

<body>
  <div class="container">
    <h1 class="mb-4">New Article</h1>
    <form action="/articles" method="post">
      <%- include('_form_fields') %>
    </form>
  </div>
</body>

The problem occurs only when I try to do this in router file. I would be very thankful if anyone can tell me what exactly am I doing wrong?

my function return null when I initiate value correctly(node.js, passport.js, express.js)

recently I’m making login authentication and had a problem, I used jwt as a token for security especially issued two tokens for better security(refresh token, access token).

What I was trying to is ‘pass different token passport’s jwtstrategy depends on the situation.

So, If the refresh token and the access token are both valid, I just pass the access token to jwtstrategy
when the refresh token is valid but the access token expired I issue a new token and pass it to jwtstrategy

However, the problem is even I put valid value to return it doesn’t return anything.
let me show you code.

const tokenCheck = async (req,res) => {
    let jwtoken = null
        //when both token are valid
    if (req && verifyToken('access',req.cookies['accessToken']) && verifyToken('refresh',req.cookies['refreshToken'])) {
   
       
        accessToken = req.cookies['accessToken'];
        jwtoken = accessToken;
        console.log('jwtoken : '+ jwtoken);
        return jwtoken
        
        //when only refresh token is valid
        //issue new access token
    } else if (req && !verifyToken('access', req.cookies['accessToken']) && verifyToken('refresh', req.cookies['refreshToken'])) { 
        console.log('you need new access token')
        const refreshTokenInfo = verifyToken('refresh',req.cookies['refreshToken']);
        await User.findById({ _id: refreshTokenInfo.id })
            .then(user => { 
                const Payload = {
                id: user.id,
                userid: user.userid,
                role: user.role
                }
                jwt.sign(Payload, JWT_ACCESS_SECRET, { expiresIn: JWT_ACCESS_EXPIRATION_TIME }, (err, accessToken) => { 
                    if (err) {
                            console.log(err)
                    }
                    console.log(res)
                    console.log('new accesstoken : ' + accessToken)
                    res.cookie('accessToken', accessToken,{ httpOnly: true});
                    jwtoken = accessToken;
                });
                return  jwtoken
            })  
    }
        return null

    }

when I log token with ‘console.log(‘jwtoken : ‘+ jwtoken);’ right before I return jwtoken
it logged well without problem

module.exports = passport => {

    const opts = {};
    opts.jwtFromRequest =  tokenCheck;
    opts.secretOrKey = JWT_ACCESS_SECRET
    opts.passReqToCallback = true;
    
    passport.use(new JwtStrategy(opts,(req,jwt_payload, done) => {
        // console.log(passport);
       
        

        console.log(req)
      console.log(jwt_payload);
        User.findById(jwt_payload.id)
            .then(user => {
                if(user) {
                    return done(null, user)
                }
              
                return done(null, false);
            })
            .catch(err => console.log(err)
           
            );
    }));
};

However, I couldn’t get any value in here and it doesn’t log nothing

can you explain what is wrong with my code and how to solve it?

thx for reading, your help will be appreciated.

Component shows old state after action happened

After action is happened component gets an old state anyway. I’m not mutating the state btw. The changes appears only after I refresh the page

My component TodoList.tsx
Here’s I’m trying to get state via useEffect hook


export const TodoList: FC = () => {
    const {
        todoList, isLoading, isError, message
    } = useTypedSelector(
        (state) => state.todo
    )

    console.log(todoList)

    const { getTodo, reset } = useActions()

    useEffect(() => {
        getTodo()
        console.log("render")
        if (isError) {
            console.log(message)
        }
        return () => {
            reset()
        }
    }, [])

    const statusHandler = (event: React.ChangeEvent<HTMLParagraphElement>) => {
        const status = event.target.innerText
        if (status === "completed") {
            getTodo({ complete: true })
        } else if (status === "uncompleted") {
            getTodo({ complete: false })
        } else if (status === "all") {
            getTodo()
        }
    }

    return (
        <>
        ...
        </>
    )
}


my Reducer
I’m not mutating the state also.

const initialState: TodoState = {
  todoList: [],
  isError: false,
  isSuccess: false,
  isLoading: false,
  message: ""
}

export const todoReducer = (state = initialState, { type, payload }: TodoAction): TodoState => {
  switch (type) {
    case "GET_TODOS":
      return { ...state, isLoading: true }
    case "GET_TODOS_SUCCESS":
      return { ...state, isLoading: false, isSuccess: true, todoList: payload }
    case "GET_TODOS_ERROR":
      return { ...state, isLoading: false, isError: true, message: payload.error }
    case "CREATE_TODO":
      return { ...state, isLoading: false }
    case "CREATE_TODO_SUCCESS":
      return { ...state, isLoading: false, isSuccess: true, todoList: [...state.todoList, payload]}
    case "CREATE_TODO_ERROR":
      return { ...state, isLoading: false, isError: true, message: payload.error }
    case "TOGGLE_TODO":
      return { ...state, isLoading: true }
    case "TOGGLE_TODO_SUCCESS":
      return {
        ...state, isLoading: false, isSuccess: true, todoList: state.todoList.map((todo: ITodoItem) => {
          if (todo._id === payload.id) {
            console.log(payload)
            return {
              ...todo,
              complete: !todo.complete
            }
          }
          return todo
        })
      }
    case "TOGGLE_TODO_ERROR":
      return { ...state, isLoading: false, isError: true, message: payload.error }
    case "DELETE_TODO":
      return { ...state, isLoading: true }
    case "DELETE_TODO_SUCCESS":
      return {
        ...state, isLoading: false, isSuccess: true, todoList: state.todoList.filter(
          (todo: ITodoItem) => todo._id !== payload.id
        )
      }
    case "DELETE_TODO_ERROR":
      return { ...state, isLoading: false, isError: true, message: payload.error }
    case "EDIT_TODO":
      return { ...state, isLoading: true }
    case "EDIT_TODO_SUCCESS":
      return {
        ...state, isLoading: false, isSuccess: true, todoList: state.todoList.map((todo: ITodoItem) => {
          if (todo._id === payload.id) {
            return {
              ...todo,
              text: payload.text
            }
          }
          return todo
        })
      }
    case "EDIT_TODO_ERROR":
      return { ...state, isLoading: false, isError: true, message: payload.error }
    case "RESET_TODOS":
      return { ...state, todoList: state.todoList }
    default:
      return state
  }
}

my action creator
Here I’m making a request from my own api.

...
export const getTodo = (data?: GetTodos) => {
    return async (dispatch: Dispatch<TodoAction>): Promise<void> => {
        try {
            dispatch({ type: "GET_TODOS", payload: {} })
            let response
            if (data) {
                response = await todoService.getTodo((<any>data).complete)
            }
            response = await todoService.getTodo()
            console.log(response)
            dispatch({ type: "GET_TODOS_SUCCESS", payload: response })
        } catch (err) {
            dispatch({
                type: "GET_TODOS_ERROR",
                payload: { error: "Cannot fetch the todos. Please try again later" }
            })
        }
    }
}

export const createTodo = (payload: CreateTodo) => {
    return async (dispatch: Dispatch<TodoAction>): Promise<void> => {
        try {
            dispatch({ type: "CREATE_TODO", payload: payload })
            const response = await todoService.createTodo(payload)
            dispatch({ type: "CREATE_TODO_SUCCESS", payload: response })
        } catch (err) {
            dispatch({
                type: "CREATE_TODO_ERROR",
                payload: { error: "Cannot create todo. Please try again later" }
            })
        }
    }
}

export const toggleTodo = (payload: ToggleTodo) => {
    return async (dispatch: Dispatch<TodoAction>): Promise<void> => {
        try {
            const response = await todoService.updateTodo(payload.id, { complete: payload.complete })
            dispatch({ type: "TOGGLE_TODO_SUCCESS", payload: response })
        } catch (err) {
            dispatch({
                type: "TOGGLE_TODO_ERROR",
                payload: { error: `${err}` }
            })
        }
    }
}
...
}

all code is here: https://github.com/maridoroshuk/todos-ts

the issue

How to click on a div in a chessboard using componenents in react?

I am trying to code a chessboard in order to prepare for an interview from this – challenge

I want it to look like this –

enter image description here

When you click on any tile of the chessboard all the diagonals change color to red.

Till I have achieved to display the chessboard using 2d for loop and tile component.

This is how I have done it –

app.js

import Chessboard from './Chessboard'

function App() {
  return (
    <div className="app">
      <Chessboard/>
    </div>
  );
}

export default App;

chessboard.js

import React from "react";
import '../Chessboard.css';
import Pixel from "./Pixel";

const horizontalAxis = [ "a", "b","c","d","e","f","g","h"]
const verticalAxis = [ "1", "2","3", "4","5","6","7","8"]

function Chessboard() {

    let board=[]

    for (let j = verticalAxis.length - 1; j >= 0; j--) {
        for (let i = 0; i < horizontalAxis.length; i++) {
            if((i+j)%2===0)
            {
                board.push(<Pixel key={i.toString()+j.toString()} selectedColor="black"/>)
            }
            else
            {
                board.push(<Pixel key={i.toString()+j.toString()} selectedColor="white"/>)                // board.push(<div className="tile white-tile"></div>)
            }
            
        }
    };

  return (
    <div id="chessboard">
        {board}
    </div>
  );
}

export default Chessboard;

Pixel.js

export default function Pixel(props){
    
    const {selectedColor} = props
    
    return (<div className="tile" style={{ backgroundColor: selectedColor }}></div>)
}

pixel css

.tile{
    width: 100px;
    height: 100px;
}

This looks like this

enter image description here

Now this where I am stuck, how do I make the tiles clickable?

I tried onClick function and using events like this

    function test(_e){
        console.log("works")
    }

    for (let j = verticalAxis.length - 1; j >= 0; j--) {
        for (let i = 0; i < horizontalAxis.length; i++) {
            if((i+j)%2===0)
            {
                board.push(<Pixel onClick={e => test(e)} key={i.toString()+j.toString()} selectedColor="black"/>)
            }
            else
            {
                board.push(<Pixel key={i.toString()+j.toString()} selectedColor="white"/>)                // board.push(<div className="tile white-tile"></div>)
            }
            
        }
    };

this should console log message when you click on black tiles but this does not work.

I am stuck as to I have no idea on how to display the diagonal red colour on clicking of a tile.

What can I do to solve this?