Switch input selection according to the time [duplicate] - javascript

This question already has answers here:
Check a radio button with javascript
(7 answers)
Closed 2 years ago.
I am currently writing a small program that saves workers as "IN" in the morning and saves "OUT", I want the program to switch the radio to "IN" in the morning and disables "OUT". The same thing in the afternoon, switch the radio to "OUT" and disables "IN"
function EnableDisable() {
var today = new Date();
var curHr = today.getHours();
if (curHr > 12) {
option1.disabled = true;
option1.disabled = false;
alert("come here");
} else {
option1.disabled = false;
option2.disabled = true;;
}
};
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-success active">
<input type="radio" class="form-control input-lg" name="status" value="in" id="option1" autocomplete="off" checked disabled="disabled"> In
</label>
<label class="btn btn-danger">
<input type="radio" name="status" value="out" id="option2" autocomplete="off" disabled="disabled"> Out
</label>
</div>

I recommend you split the functionality. You shouldn't try to handle multiplay states within the same method. Your project needs the following methods:
Init(h) the function you call once when you startup the project
CheckIn(input) the function that handles saving the checkIn time
CheckOut(input) the function that handles saving the checkOut time
Remaining functionality like disabling the IN button when it's not been checked before 12 should be its own method and could be handled with an interval.
Eventually, you would get something like this:
const init = (h) => {
const btnGroup = document.querySelector('.btn-group');
const btnSucess = btnGroup.querySelector('.btn-success input');
const btnDanger = btnGroup.querySelector('.btn-danger input');
const isMorning = h > 6 && h < 12;
const isAfternoon = h > 12 && h < 20;
if(isMorning) {
btnSucess.disabled = false;
btnDanger.disabled = true;
} else if(isAfternoon) {
btnSucess.disabled = true;
btnDanger.disabled = false;
} else {
btnSucess.disabled = true;
btnDanger.disabled = true;
}
}
const checkIn = (input) => {
input.disabled = true;
const today = new Date();
console.log(today.toString());
}
const checkOut = (input) => {
input.disabled = true;
const today = new Date();
console.log(today.toString());
}
const setup = () => {
const hours = new Date().getHours();
init(hours);
}
// Load
window.addEventListener('load', setup);
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-success active">
<input type="radio" class="form-control input-lg" name="status" value="in" id="option1" autocomplete="off" onInput="checkIn(this)"> In
</label>
<label class="btn btn-danger">
<input type="radio" name="status" value="out" id="option2" autocomplete="off" onInput="checkOut(this)" disabled> Out
</label>
</div>
This is of course not perfect code. You should check within your checkOut() function if there is a checkIn time saved. I recommend saving this time by using new Date().getTime() for doing this.
This should be enough to give you a headstart. I want to point out that your system currently isn't that flexible. If for example there is something that has to be checked-IN after 12 then you might have a problem. You should work on your business case what should happen if a user doesn't follow the model traject you have build.
Good Luck

Related

How to automatically select checkboxes if user input in "wall_amount" exceeds 3

I would like my program to automatically select all checkboxes (Specifically "Side 1, Side 2, Side 3 and Side 4") if the wall_amount input is above 3. How would this be done?
I have tried this on javascript lines 10-12. Thanks
HTML
<label for="wall_amount">Number of Walls</label>
<input type="number" value="1" min="1" max="4" step="1" id="wall_amount" name="wall_amount"></input>
<div>
Please choose where you want the walls placed
<label for="wall_side1">Side 1</label>
<input type="checkbox" id="wall_side1" name="wall_side1"></input>
<div style="display: inlineblock;">
<label for="wall_side2">Side 2</label>
<input type="checkbox" id="wall_side2" name="wall_side2"></input>
<img class="img2" src="images/reference.png" alt="Bouncy Castle">
<label for="wall_side3">Side 3</label>
<input type="checkbox" id="wall_side3" name="wall_side3"></input>
</div>
<label for="wall_side4">Side 4</label>
<input type="checkbox" id="wall_side4" name="wall_side4"></input>
</div>
Javascript
var base_length = Number(document.getElementById("base_length").value);
var base_width = Number(document.getElementById("base_width").value);
var walltype = Number(document.getElementById("walltype").value);
var checkbox_side1 = document.getElementById("wall_side1");
var checkbox_side2 = document.getElementById("wall_side2");
var checkbox_side3 = document.getElementById("wall_side3");
var checkbox_side4 = document.getElementById("wall_side4");
var wall_amount = Number(document.getElementById("wall_amount").value);
$("input:checkbox").click(function() {
let max = $("#wall_amount").val();
var bol = $("input:checkbox:checked").length >= max;
$("input:checkbox").not(":checked").attr("disabled", bol);
});
$("wall_amount").on('keyup', function () {
$('checkbox_side1').prop('checked', +$(this).val() > 3);
});
You can use the function setAttribute to check checkboxes. For example, this code (based on your example) will check your element with the id wall_side1.
checkbox_side1.setAttribute("checked", true)
Anyway, try adding this to your code as a function. Then add a conditional statement that runs the function every time your variable exceeds a certain amount.
I am still relatively new at answering questions so I hope this helps!
const checkboxes = [
"wall_side1",
"wall_side2",
"wall_side3",
"wall_side4"
].map((id) => document.getElementById(id));
const amountInput = document.getElementById("wall_amount");
amountInput.addEventListener("change", (event) => {
const value = parseInt(event.target.value || 0);
if (value === 4) {
checkboxes.forEach(
checkbox => {
checkbox.disabled = true;
checkbox.checked = true;
}
);
} else {
checkboxes.forEach(
checkbox => {
checkbox.disabled = false;
}
);
}
});

console out checked radio buttons

Im trying to console out a radio button with JS in order to see the value of the checked button. the Js seems to be without syntax error, but it returns undefined:
this is the HTML:
const firstName = document.querySelector('#FirstName');
const lastName = document.querySelector('#LastName');
const email = document.querySelector('#email');
const comments = document.querySelector('#comments');
let meeting1 = document.querySelector('#meetingtype1');
let meeting2 = document.querySelector('#meetingtype2');
let meeting3 = document.querySelector('#meetingtype3');
let meeting4 = document.querySelector('#meetingtype4');
let meeting;
if (meeting1.checked) {
meeting = meeting1.value;
console.log(meeting = "1");
} else if (meeting2.checked) {
meeting = meeting2.value;
console.log(meeting = "2")
} else if (meeting3.checked) {
meeting = meeting3.value;
console.log(meeting = "3")
} else if (meeting4.checked) {
meeting = meeting4.value;
console.log(meeting = "4")
}
const submitform = document.querySelector('#submitform');
submitform.addEventListener('click', function() {
console.log(` Name: ${firstName.value}, Last Name: ${lastName.value}, Email: ${email.value}, Comment: ${comments.value} Type of meeting: ${meeting}`);
});
<fieldset>
<legend>Would you like to meet for?</legend>
<label><input type="radio" id="meetingtype1" name=meetingtype value="coffee" > A coffee</label>
<label><input type="radio" id="meetingtype2" name=meetingtype value="zoom"> A zoom meeting</label>
<label><input type="radio" id="meetingtype3" name=meetingtype value="drive"> A drive to Eilat</label>
<label><input type="radio" id="meetingtype4" name=meetingtype value="chef"> A chef meal</label>
<button id="submitform" type="submit">Submit</button>
thank you very much!
Since you want to check the value/log it onto your console when you are going to click onto your button, make sure to use your if-else-statement inside of the EventListener and not outside of the function. If you write the if-else-statement in your way, it will be executed when the page loads the first time.
To print out your current value of the selected meeting change your JavaScript Code to this. I modified your provided code.
let meeting1 = document.querySelector('#meetingtype1');
let meeting2 = document.querySelector('#meetingtype2');
let meeting3 = document.querySelector('#meetingtype3');
let meeting4 = document.querySelector('#meetingtype4');
let meeting;
const submitform = document.querySelector('#submitform');
submitform.addEventListener('click', function () {
if (meeting1.checked){
meeting = meeting1.value;
} else if (meeting2.checked){
meeting = meeting2.value;
} else if (meeting3.checked){
meeting = meeting3.value;
} else if (meeting4.checked){
meeting = meeting4.value;
}
console.log(`Type of meeting: ${meeting}`);
});

Why js text to speech not taking more charachters?

Here i am using js text to speech with SpeechSynthesis and its working fine with limited amount of words/sentences, but the time i add all my blog paragraph which is more then 2-3k words its not working, its converting till some part and automatically being stop. So how can i add unlimited no of words or total page content converted to speech.
NOTE: I tried js speak() also, which worked fine but i want a pause/stop option so i used this. So if there any other working way then please suggest.
const msg = new SpeechSynthesisUtterance();
let voices = [];
const voicesDropdown = document.querySelector('[name="voice"]');
const options = document.querySelectorAll('[type="range"],[name="text"]');
const speakButton = document.querySelector('#speak');
const stopButton = document.querySelector('#stop');
msg.text = document.querySelector('[name="text"]').value;
function populateVoices() {
voices = this.getVoices();
voicesDropdown.innerHTML = voices.map(voice => `<option value="${voice.name}">${voice.name}(${voice.lang})</option>`).join('');
}
function setVoice() {
msg.voice = voices.find(voice => voice.name === this.value);
toggle();
}
function toggle(startOver = true) { //true is for it will not stop if language changes
speechSynthesis.cancel();
if (startOver) {
speechSynthesis.speak(msg);
}
}
function setOption() {
// console.log(this.name, this.value);
msg[this.name] = this.value;
toggle();
}
speechSynthesis.addEventListener('voiceschanged', populateVoices);
voicesDropdown.addEventListener('change', setVoice);
options.forEach(option => option.addEventListener('change', setOption));
speakButton.addEventListener('click', toggle);
<div class="voiceinator">
<select name="voice" id="voices">
<option value="">Select a voice</option>
</select>
<label for="rate">Rate:</label>
<input type="range" name="rate" min="0" max="3" value="1" step="0.1">
<label for="pitch">Pitch:</label>
<input type="range" name="pitch" min="0" max="2" value="1" step="0.1">
<textarea name="text"></textarea>
<button id="stop">Stop!</button>
<button id="speak">Speak</button>
</div>
It's a known bug. The workaround is to issue a resume every 14 seconds.
You can add this immediately after the line speechSynthesis.speak(msg):
let r = setInterval(() => {
console.log(speechSynthesis.speaking);
if (!speechSynthesis.speaking) {
clearInterval(r);
} else {
speechSynthesis.resume();
}
}, 14000);

Check if all radio buttons are clicked in vanilla JavaScript

For exercise, I've created a small HTML-CSS-JavaScript quiz. The quiz itself works but when I tried to edit a way to check if all radio buttons of the quiz are working (and if not, alert a message to the user), it became broken.
Here is the quiz, with the funcion that checks if the radio buttons are clicked:
let result = 0;
function right() {
result += 50;
}
function wrong() {
result -= 50;
}
function obcpq() {
if (document.querySelector('#quiz:not(:has(:radio:checked))').length) {
return alert("At least one group is blank");
} else {
function showScore() {
totalScore = result;
alert(totalScore);
}
}
}
<form id="quiz">
<label>Q1 - X?</label>
<input type="radio" onclick="right()">Yes
<input type="radio" onclick="wrong()">No
<br>
<label>Q2 - Y?</label>
<input type="radio" onclick="wrong()">Yes
<input type="radio" onclick="right()">No
<br>
<input type="button" onclick="obcpq()" />
<!-- One Button Chcked Per Question -->
</form>
I tried this code after reading of it in this QA session. I also found this session which deals with jQuery and I don't run jQuery on this HTML page.
Why isn't the condition working in my vanilla JavaScript version?
Looking at your HTML code, there's one proportion that can be useful to solve your problem: you want the same number of checked inputs as the number of labels that describe the boxes. When the numbers don't match it's the indicator that not all questions were answered:
let result = 0;
function right() {
result += 50;
}
function wrong() {
result -= 50;
}
function obcpq() {
const labelCount = document.querySelectorAll('#quiz label').length;
const checkedInputsCount = document.querySelectorAll("#quiz :checked").length;
if (labelCount !== checkedInputsCount) {
return alert("At least one group is blank");
} else {
function showScore() {
totalScore = result;
alert(totalScore);
}
}
}
<form id="quiz">
<label>Q1 - X?</label>
<input type="radio" onclick="right()">Yes
<input type="radio" onclick="wrong()">No
<br>
<label>Q2 - Y?</label>
<input type="radio" onclick="wrong()">Yes
<input type="radio" onclick="right()">No
<br>
<input type="button" onclick="obcpq()" />
<!-- One Button Chcked Per Question -->
</form>
Try to add every question in a separate div then loop through them and check if the group has at least one checked option radio, then use a flag to store the loop result and finally show the right message, like :
let result = 0;
function right() {
result += 50;
}
function wrong() {
result -= 50;
}
function obcpq() {
var groups = document.querySelectorAll('#quiz div');
var all_checked = true;
for (i = 0; i < groups.length; i++) {
if (groups[i].querySelectorAll(':checked').length==0) {
all_checked = false;
}
}
if (!all_checked) {
console.log('Check please all the radios');
} else {
console.log('showScore');
}
}
<form id="quiz">
<div>
<label>Q1 - X?</label>
<input type="radio" onclick="right()">Yes
<input type="radio" onclick="wrong()">No
</div>
<div> <label>Q2 - Y?</label>
<input type="radio" onclick="wrong()">Yes
<input type="radio" onclick="right()">No
</div>
<input type="button" onclick="obcpq()" value="CHECK"/>
<!-- One Button Chcked Per Question -->
</form>

jQuery Validate add Method dynamically

I have a form that uses jQuery validate, but the form is generated dynamically and I am trying to add an additional method for validating whether a date is before another, if that date has been used before.
The HTML is the following (with the names generated dynamically):
<div class="form-group">
<label class="control-label col-md-2">Read Date</label>
<div class="input-group col-md-4 date date-picker" data-date-format="dd/mm/yyyy">
<div class="input-icon right">
<i class="fa"></i>
<input type="text" class="form-control insert-val" readonly="" name="datepicker_16" aria-required="true" aria-invalid="false">
</div>
<span class="help-block">Enter the date of the reading</span>
<span class="input-group-btn">
<button class="btn default" type="button" style="margin-top: -18px;"><i class="fa fa-calendar"></i></button>
</span>
</div>
<input type="hidden" name="prevdate_16" class="form-control prev-date" value="29/05/2015">
With the following jQuery to validate the date field:
$('#readingForm .insert-val').each(function(){
var prevDate = $(this).parents('.form-group').find('.prev-date').val();
var useLTD = true;
if(prevDate !== ''){
$.validator.addMethod("less_than_date", function(value, element) {
var curDate = value;
var curarr = curDate.split('/');
var curDay = curarr[0];
var curMonth = curarr[1];
var curYear = curarr[2];
var ncurDate = new Date();
ncurDate.setFullYear(curYear, curMonth-1, curDay);
var prevarr = prevDate.split('/');
var prevDay = prevarr[0];
var prevMonth = prevarr[1];
var prevYear = prevarr[2];
var nprevDate = new Date();
nprevDate.setFullYear(prevYear, prevMonth-1, prevDay);
return ncurDate <= nprevDate;
}, "The reading date must be greater than the previous reading date.");
} else {
useLTD = false;
}
$(this).rules( "add", {
required: true,
minlength: 10,
dateITA: true,
less_than_date: useLTD
});
});
Before the I added the "add method", it correctly validated the date, but now it does not, and doesnt accept even if the date is greater than the previous date.
Really stumped on this one, any help would be greatly appreciated.
Ok, as soon as I posted this, I realised that the return was the wrong way round.
Should have been:
return nprevDate <= ncurDate;

Categories