How to handle the conditional check box selection in JavaScript? - javascript

We have three checkboxes as Left, Right, Both.
When selecting Left and Right, Both should be disabled.
However, on checking the right and left; checkbox for Both is not disabling. (or) alert('Hello 1') is not firing.
document.getElementById('Left').disabled = false;
var isLeft = document.getElementById('Left').checked;
document.getElementById('Right').disabled = false;
var isRight = document.getElementById('Right').checked;
document.getElementById('Both').disabled = false;
var isBoth = document.getElementById('Both').checked;
if (isLeft == true && isRight == true)
{
alert('Hello 1');
document.getElementById('Both').checked = false;
document.getElementById('Both').disabled = true;
}
Below is the original code in my JavaScript file
if ($("input:radio[name='Swelling']:checked").length > 0) {
var isChecked = document.getElementById("SwellingYes").checked;
if (isChecked === true)
{
document.getElementById('Left').disabled = false;
let isLeft = document.getElementById('Left').checked;
document.getElementById('Right').disabled = false;
let isRight = document.getElementById('Right').checked;
document.getElementById('Both').disabled = false;
let isBoth = document.getElementById('Both').checked;
if (isLeft && isRight) {
alert('Hello 1');
document.getElementById('Both').checked = false;
document.getElementById('Both').disabled = true;
}
if (isBoth) {
document.getElementById('Left').checked = false;
document.getElementById('Right').checked = false;
document.getElementById('Left').disabled = true;
document.getElementById('Right').disabled = true;
}
}
}

You need to listen on each checkbox's change event, then run your code, like so:
document.addEventListener('DOMContentLoaded', function () {
Array.prototype.slice.call(document.querySelectorAll('input[type="checkbox"]')).forEach(function (checkbox) {
checkbox.addEventListener('change', function () {
document.getElementById('Left').disabled = false;
var isLeft = document.getElementById('Left').checked;
document.getElementById('Right').disabled = false;
var isRight = document.getElementById('Right').checked;
document.getElementById('Both').disabled = false;
var isBoth = document.getElementById('Both').checked;
if (isLeft == true && isRight == true) {
alert('Hello 1');
document.getElementById('Both').checked = false;
document.getElementById('Both').disabled = true;
}
});
});
});
Left:
<input type="checkbox" id="Left" />
Right:
<input type="checkbox" id="Right" />
Both:
<input type="checkbox" id="Both" />
If you are only supporting modern browsers, you can use a bit of syntactic sugar here as well:
document.addEventListener('DOMContentLoaded', () => {
[...document.querySelectorAll('input[type="checkbox"]')].forEach((checkbox) => {
checkbox.addEventListener('change', () => {
document.getElementById('Left').disabled = false;
let isLeft = document.getElementById('Left').checked;
document.getElementById('Right').disabled = false;
let isRight = document.getElementById('Right').checked;
document.getElementById('Both').disabled = false;
let isBoth = document.getElementById('Both').checked;
if (isLeft == true && isRight == true) {
alert('Hello 1');
document.getElementById('Both').checked = false;
document.getElementById('Both').disabled = true;
}
});
});
});
Left:
<input type="checkbox" id="Left" />
Right:
<input type="checkbox" id="Right" />
Both:
<input type="checkbox" id="Both" />
If you wanted to also disable Left and Right, when Both were checked, you could do that, furthermore, it would be wise to not keep querying the dom for your elements, and rather store them inside variables:
document.addEventListener('DOMContentLoaded', () => {
let leftBox = document.getElementById('Left');
let rightBox = document.getElementById('Right');
let bothBox = document.getElementById('Both');
[...document.querySelectorAll('input[type="checkbox"]')].forEach((checkbox) => {
checkbox.addEventListener('change', () => {
leftBox.disabled = false;
let isLeft = leftBox.checked;
rightBox.disabled = false;
let isRight = rightBox.checked;
bothBox.disabled = false;
let isBoth = bothBox.checked;
if (isLeft && isRight) {
bothBox.checked = false;
bothBox.disabled = true;
}
if (isBoth) {
leftBox.checked = false;
rightBox.checked = false;
leftBox.disabled = true;
rightBox.disabled = true;
}
});
});
});
Left:
<input type="checkbox" id="Left" />
Right:
<input type="checkbox" id="Right" />
Both:
<input type="checkbox" id="Both" />

I'm not sure if this should be a comment or not, but your code only checks to see if it's checked or not once, on page load. If you want it to work properly, you may want to have an event attached or add a loop?

Related

input validation with two regex

Hi all I have following code: my code
I have 2 inputs and 2 regex for each of them
<input type="text" id="FormField_6_input" placeholder="company name" />
<input type="text" id="FormField_13_input" placeholder="zip code" />
const companyRGEX = /^[a-zA-Z0-9_.+,-]*(?:[a-zA-Z][a-zA-Z0-9_,.+-]*){2,}$/;
const found = event.target.value.match(companyRGEX);
const zipRGEX = /^[a-zA-Z0-9]{5,9}$/;
const foundZip = event.target.value.match(zipRGEX);
I need to check
if company name is valid but zip is not valid then disable button and show error message for zip
if zip code is valid but compony name is not valid then disable button and show error message for company name
if both of them is not valid then then disable button and show both error messages
I write my code only for company name with one regex and it was work very well, for example:
function validat(event) {
const companyRGEX = /^[a-zA-Z0-9_.+,-]*(?:[a-zA-Z][a-zA-Z0-9_,.+-]*){2,}$/;
const found = event.target.value.match(companyRGEX);
const errorMSG = document.getElementById("errorMSG");
if (button && (found || !event.target.value)) {
button.disabled = false;
errorMSG.style.display = "none";
} else {
button.disabled = true;
errorMSG.style.display = "block";
}
}
But when I try to write multi check something going wrong, please help me to resolve this problem.
here is multicheck code:
function validate(event) {
const companyRGEX = /^[a-zA-Z0-9_.+,-]*(?:[a-zA-Z][a-zA-Z0-9_,.+-]*){2,}$/;
const found = event.target.value.match(companyRGEX);
const zipRGEX = /^[a-zA-Z0-9]{5,9}$/;
const foundZip = event.target.value.match(zipRGEX);
if (
button &&
(found || !event.target.value) &&
(foundZip || !event.target.value)
) {
if (button && (found || !event.target.value)) {
button.disabled = true;
zip_errorMSG.style.display = "none";
errorMSG.style.display = "block";
} else if (button && (foundZip || !event.target.value)) {
button.disabled = true;
errorMSG.style.display = "none";
zip_errorMSG.style.display = "block";
} else {
button.disabled = false;
errorMSG.style.display = "none";
zip_errorMSG.style.display = "none";
}
} else {
button.disabled = true;
zip_errorMSG.style.display = "block";
errorMSG.style.display = "block";
}
}
P.S. please don't change html, only change js.
Thank you.
const checkvalue = (value, regex) => !!value.match(regex);
function validateCompanyName(event, source) {
const companyRGEX = /^[a-zA-Z0-9_.+,-]*(?:[a-zA-Z][a-zA-Z0-9_,.+-]*){2,}$/;
const zipRGEX = /^[a-zA-Z0-9]{5,9}$/;
const companyIsCorrect = checkvalue(
companyNameField.value,
companyRGEX
);
const zipIsCorrect = checkvalue(zipPostalCode.value, zipRGEX);
if (button && zipIsCorrect && companyIsCorrect) {
button.disabled = false;
zip_errorMSG.style.display = "none";
errorMSG.style.display = "none";
} else if (button && !zipIsCorrect && companyIsCorrect) {
button.disabled = true;
zip_errorMSG.style.display = "block";
errorMSG.style.display = "none";
} else if (button && zipIsCorrect && !companyIsCorrect) {
button.disabled = true;
zip_errorMSG.style.display = "none";
errorMSG.style.display = "block";
} else {
button.disabled = true;
zip_errorMSG.style.display = "block";
errorMSG.style.display = "block";
}

don't submit form if name field is empty

I am trying to stop the form from submitting if the name input is empty.
My code works to disable to submit button but once I click again and put a name it remains disable. How can i fix this?
<input type="text" id="name" name="user_name">
<button type="submit">Register</button>
const register = document.querySelector('button[type="submit"]');
function errorNameInput () {
let nameUser = document.getElementById('name').value;
if (nameUser == '') {
register.disabled = true;
console.log('please, fill in name');
} else {
console.log('submit');
}
document.getElementById('name').value = '';
}
register.addEventListener("click",
function(){
errorNameInput();
return false;
});
You need to add the case where the user has typed something and re-enable the button.
function errorNameInput () {
let nameUser = document.getElementById('name').value;
if (nameUser == '') {
register.disabled = true;
console.log('please, fill in name');
} else {
register.disabled = false;
console.log('submit');
}
document.getElementById('name').value = '';
}
register.addEventListener("click",
function(){
errorNameInput();
return false;
});
<input type="text" id="name" name="user_name">
<button type="submit">Register</button>
const register = document.querySelector('button[type="submit"]');
function errorNameInput () {
let nameUser = document.getElementById('name').value;
if (nameUser == '') {
register.disabled = true;
console.log('please, fill in name');
} else {
register.disabled = false;
console.log('submit');
}
document.getElementById('name').value = '';
}
register.addEventListener("click",
function(){
errorNameInput();
return false;
});

Chrome Extension Settings page [duplicate]

This question already has answers here:
Completely lost on how to save extension popup window content
(2 answers)
Closed 6 years ago.
I have this piece of code(thanks to Shah Abax Khan), and I wanted to make it a Chrome extension. I wrote a settings/options page, but it doesn't actually save the settings. Help?
Javascript:
var pretty_fied = false;
var isOn = localStorage.isOn;
var isCapFirst = localStorage.isCapFirst;
var firstLetterPerWord = localStorage.firstLetterPerWord;
function yay() {
if ($("#on").value == "on") {
isOn = true;
localStorage["isOn"] = true;
}
else {
isOn = false;
localStorage["isOn"] = false;
}
if ($("#first").value == "on") {
isCapFirst = true;
localStorage["isCapFirst"] = true;
}
else {
isCapFirst = false;
localStorage["isCapFirst"] = false;
}
if ($("#per").value == "on") {
firstLetterPerWord = true;
localStorage["firstLetterPerWord"] = true;
}
else {
firstLetterPerWord = false;
localStorage["firstLetterPerWord"] = false;
}
};
$('input, textarea').keyup(function () {
alert(isOn);
if (isOn) {
prev = true;
var value = $(this).val();
var altText = '';
for (num = 0; num < value.length; num++) {
if (num % 2 == 0)
altText += value[num].toUpperCase();
else
altText += value[num].toLowerCase();
}
$(this).val(altText);
}
});
And here's the HTML:
<!DOCTYPE html>
<html>
<head>
<title>Y.A.Y | Options</title>
<script type="text/javascript" src="/js/caps.js"></script>
</head>
<body>
<h1>Settings</h1>
<form>
<label>Enabled: </label>
<select id="on">
<option value="on">Yes</option>
<option value="off">No</option>
</select>
</br>
<label>First Letter:</label>
<select id="first">
<option value="on">Capital</option>
<option value="off">Lowercase</option>
</select>
</br>
<label>Change First Letter of Each </label>
<select id="per">
<option value="on">Word</option>
<option value="off">Sentence</option>
</select>
<button id="done" onclick="yay()">Save</button>
</form>
</body>
</html>
yay() is supposed to save the settings, but it doesn't.
In Chrome Extension you shouldn't use a LocalStorage. It's for websites.
Use Chrome Storage instead like this:
JavaScript:
var pretty_fied = false;
var isOn;
var isCapFirst;
var firstLetterPerWord;
getData()
function getData() {
chrome.storage.sync.get( function ( data ) {
isOn = data.isOn;
isCapFirst = data.isCapFirst;
firstLetterPerWord = data.firstLetterPerWord;
} )
}
function yay() {
isOn = $("#on").value == "on";
isCapFirst = $("#first").value == "on";
firstLetterPerWord = $("#per").value == "on";
chrome.storage.sync.set( {
isOn: isOn,
isCapFirst: isCapFirst,
firstLetterPerWord: firstLetterPerWord
} )
}

How do unselect after the target has changed IE?

I am working with a dynamic element list of checkboxes and I am at a lose as to how I can go about deselecting the elements after I've processed the request: http://jsfiddle.net/Arandolph0/k7uLg/15/
document.attachEvent('onclick', function (e) {
var myBtn = document.getElementById('mybutton')
var target = e.srcElement;
if (target.name == "mycheckbox1" || target.name == "mycheckbox2") {
if(target.checked){
myBtn.disabled = false;
// list.addRecord(target);
} else if(!list.hasItems()) {
myBtn.disabled = true;
target.checked = false;
}
if(list.hasItems()) {
myBtn.disabled = false;
}
}
});
function someFunction() {
alert("Some function");
}
Here's the Html:
<input type="button" id='mybutton' value="Click" disabled onclick="someFunction()"/>
<input type="checkbox" name='mycheckbox1' />
<input type="checkbox" name='mycheckbox2' />
So, in summary after the button has 'do something' how would I then deselect the checked checkboxes?
You could get all of the checkbox elements by type and then set them to false.
function unselect() {
var elements = document.getElementsByTagName('input');
for(var i = 0; i < elements.length; i++)
{
if(elements[i].type.toLowerCase() == 'checkbox')
elements[i].checked = false;
}
}
It isn't very sexy but it gets the job done.
you just need to use
$("input:checkbox").removeAttr("checked");
this will uncheck all the checkboxes. I have also attached working copy of your code.
$(document).click(function (event) {
var myBtn = document.getElementById('mybutton');
var target = event.target;
if (target.name == "mycheckbox1" || target.name == "mycheckbox2") {
if(target.checked){
myBtn.disabled = false;
// list.addRecord(target);
} else if(!list.hasItems()) {
myBtn.disabled = true;
target.checked = false;
}
$("input:checkbox").removeAttr("checked");
if(list.hasItems()) {
myBtn.disabled = false;
}
}
});
I hope this will be able to solve your problem.

Checkbox and input field value

I have a check box which will change the value of a textfield to 1 when checked and change it back to zero when unchecked, how can I do this? I want it in javascript.
<input type="checkbox" name="foo" onclick="document.getElementById('idtextfield').value = +this.checked;" />
You can do like this:
var chk = document.getElementById('checkbox_id');
var txt = document.getElementById('textbox_id');
chk.onclick = function(){
if (this.checked === true){
txt.value = '1';
}
else{
txt.value = '0';
}
};
window.onload = function() {
var checkBox = document.getElementById('idofcheck');
if (checkBox == null) {
return;
}
checkBox.onclick = function() {
var textField = document.getElementByd('ifoftextfield');
if (textField == null) {
return;
}
if (this.checked) {
textField.value = '1';
} else {
textField.value = '0';
}
};
};
if(document.getElementById("checkbox1").checked)
{
document.getElementById('textbox1').value=1;
}
else
{
document.getElementById('textbox1').value='';
}

Categories