javascript check a box with value - javascript

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']");

Related

Receiving error after removing Option from Select using 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>

How should I improve my javascript form validation?

I grabbed the form from some random site because I'm only interested writing the javascript at the moment.
I am trying to check that a user has selected or entered text for all fields. I've made it a long if if-else but that can't be the best/most elegant/easiest solution.
Leaving aside the radio button validation for now, what's the better way to check that the text fields, drop down, and checkboxes all have a value/input?
I'm teaching myself javascript so I'm open to being told the proper way and I'll research it and do it on my own, or updating my fiddle would be fine too. (Be gentle with me. I'm sure this code is janky.)
Any thoughts on this would be appreciated.
Fiddle: https://jsfiddle.net/kiddigit/g0rur21a/
document.getElementById("newForm").addEventListener("submit", enterForm);
function enterForm(event) {
event.preventDefault();
var dropdown = document.getElementById('dropDown');
if (document.getElementById('fname').value === ''){
document.getElementById('fname').focus();
alert('Enter text.');
} else if (document.getElementById('eMail').value === ''){
document.getElementById('eMail').focus();
alert('Enter text.');
} else if (document.getElementById('textArea').value === '') {
document.getElementById('textArea').focus();
alert('Enter text.');
} else if (!dropDown.value) {
document.getElementById('dropDown').focus();
alert('Choose an option.');
} else if ( ( newForm.checkbox[0].checked == false ) && ( newForm.checkbox[1].checked == false ) )
{ alert ( "Please choose a checkbox" );
return false;
}
var radios = document.getElementsByName("radio");
var formValid = false;
var i = 0;
while (!formValid && i < radios.length) {
if (radios[i].checked) formValid = true;
i++;
}
if (!formValid) alert("Please check a radio button.");
return formValid;
return false;
};
If you use HTML5, and assuming you're NOT using jQuery for anything (just native JavaScript), a good convention would be to assign a class to all input elements in the form that you want to validate (or if they all need to be validated, you can get all child elements of the form), and use getElementsByClassName(). With HTML5 data-* attributes, you can assign something like data-invalid-error-message to set the error message for the element itself.
http://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp
From there, you can perform a loop across all elements, check if they're empty, and then grab the data-invalid-error-message attribute and display it to the user without doing nested if statements.
https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes
document.getElementById("newForm").addEventListener("submit", function (event) {
event.preventDefault();
if (!document.getElementById('fname').value) {
return alert('Enter text.');
}
if (document.getElementById('eMail').value === '') {
document.getElementById('eMail').focus();
return alert('Enter text.');
}
if (document.getElementById('textArea').value === '') {
document.getElementById('textArea').focus();
return alert('Enter text.');
}
var dropdown = document.getElementById('dropDown');
if (!dropdown || !dropDown.value) {
document.getElementById('dropDown').focus();
return alert('Choose an option.');
}
if (( newForm.checkbox[0].checked == false ) && ( newForm.checkbox[1].checked == false )) {
return alert("Please choose a checkbox");
}
var radios = document.getElementsByName("radio");
var formValid = false;
var i = 0;
while (!formValid && i < radios.length) {
if (radios[i].checked) {
formValid = true;
}
i++;
}
if (!formValid) {
return alert("Please check a radio button.");
}
// Form is valid here
});
Here is some improvements. Updated Fiddle
I would like to validate form with required property, but it does not support validation of group of options and radio groups
If you're OK not supporting IE8, you can use querySelectorAll to dynamically get all the nodes of different types within your form and validate them accordingly. This will work for a form with any number of inputs:
function validateForm(formNode) {
var formValid = true;
var textFlds = formNode.querySelectorAll('input[type="text"],input[type="email"],input[type="password"],textarea');
var dropdowns = formNode.querySelectorAll('select');
var checks = formNode.querySelectorAll('input[type="checkbox"]');
var anyChecked = false;
var radios = formNode.querySelectorAll('input[type="radio"]');
var anyRadios = false;
for (var i = 0, l = textFlds.length; i < l; i++) {
if (!textFlds[i].value) {
textFlds[i].focus();
alert('Please enter text into the ' + textFlds[i].name + ' field.');
formValid = false
break;
}
};
for (var i = 0, l = dropdowns.length; i < l; i++) {
if (formValid && !dropdowns[i].value) {
dropdowns[i].focus();
alert('Please choose an option from the ' + dropdowns[i].name + ' selector.');
formValid = false
break;
}
};
for (var i = 0, l = checks.length; i < l; i++) {
if (checks[i].checked) {
anyChecked = true;
break;
}
};
if (formValid && !anyChecked) {
alert('Please choose at least one of the checkboxes.');
formValid = false;
}
for (var i = 0, l = radios.length; i < l; i++) {
if (radios[i].checked) {
anyRadios = true;
break;
}
};
if (formValid && !anyRadios) {
alert('Please check a radio button.');
formValid = false;
}
return formValid;
}
document.getElementById('newForm').addEventListener('submit', function (evt) {
evt.preventDefault();
validateForm(this);
});
This could be prettied up a bit, but you get the idea. (fiddle here)

Check / Uncheck All but one checkbox.?

Currently I'm using this to check / uncheck all checkboxes in my form.
<script type="text/javascript">
checked=false;
function checkedAll (frm1) {
var aa= document.getElementById('frm1');
if (checked == false)
{
checked = true
}
else
{
checked = false
}
for (var i =0; i < aa.elements.length -2; i++)
{
aa.elements[i].checked = checked;
}
}
</script>
This works well, But I have one check box within this form I don't want to be affected.
It has an id of id='ignore' is there anyway the above code can be used to work as is, but ignore this one checkbox ?
Thanks
for (var i =0; i < aa.elements.length -2; i++)
{
if(aa.elements[i].id !== 'ignore'){
aa.elements[i].checked = checked;
}
}
Get rid of the if loop also...
The full code -
<script type="text/javascript">
var checked = false;
function checkedAll (frm1) {
var chkBoxs = document.getElementById('frm1').getElementsByTagName('input');
checked = !checked;
for (var i =0; i < chkBoxs.length -2; i++) {
if (chkBoxs[i].id == 'ignore') {
continue;
}
chkBxs[i].checked = checked;
}
}
</script>
for (var i =0; i < aa.elements.length -2; i++)
{
if (aa.elements[i].getAttribute('id') != 'ignore')
aa.elements[i].checked = checked;
}
for (var i =0; i < aa.elements.length -2; i++)
{
if (aa.elements[i].getAttribute('id') == 'ignore')
continue;
aa.elements[i].checked = checked;
}
<script type="text/javascript">
checked=false;
function checkedAll (frm1) {
var aa= document.getElementById('frm1');
if (checked == false)
{
checked = true
}
else
{
checked = false
}
for (var i =0; i < aa.elements.length -2; i++)
{
if (aa.elements[i].getAttribute('id') == 'ignore')
aa.elements[i].checked = false;
else
aa.elements[i].checked = checked;
}
}
</script>

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")
});
})

How do I create a "check all" link for a web form?

I've got a form with a bunch of checkboxes on it, and I'd like to provide a "check all" link/button.
I'm using the code below, but when it runs, it picks up some radio buttons on the page, and checks/unchecks those too. How do I fix this?
var check = 0;
function doNow()
{
void(d=document);
void(el=d.getElementsByTagName('INPUT'));
for(i=0;i<el.length;i++)
{
if(check == 0)
void(el[i].checked=1)
else
void(el[i].checked=0)
}
if(check == 0)
check = 1;
else
check = 0;
}
You're going to want to check the element's type to ensure you don't accidentally go checking the wrong kind of inputs.
Basic example:
function checkAll( toggle ) {
var inputs = document.getElementsByTagName( 'input' );
for( var i = 0; i < inputs.length; i++ ) {
if( inputs[i].type == 'checkbox' ) {
inputs[i].checked = toggle;
}
}
}
You may want to add other checks, such as only acting on check boxes in a certain logical "group", for example.
You can check the type of the input:
if(el[i].type == 'checkbox') {
el[i].checked = true;
}
You can store the current state as a property of the function as well as check the type
function checkAll() {
var all = document.getElementsByTagName('input');
for( var i = 0, l = all.length; i < l; i++ ) {
if( all[i].type == 'checkbox' ) {
all[i].checked = checkAll.checked;
}
}
checkAll.checked = !checkAll.checked;
}
checkAll.checked = true;

Categories

Resources