How to check< 2 and > 4 checkbox in javascript - javascript

I am trying to check the user input for greater than 2 and less than 4 checkbox selected.
I have to do this check before the form gets submitted.
Although I am using AlloyUI for client side validation. You can help me with vanilla javascript.
Please help me with my code...
<% for(loop here which generates more than one checkbox) { %>
<form name=".." method=".." action=".." onSubmit="return checkBox();">
<input type="checkbox" id=".." name=".."/>
</form>
%>
My javascript
function checkBox(){
alert("start");
var total = 0;
var max = form.checkcompare.length;
alert(max);
for(var idx = 0; idx < max; idx++)
{
if(eval("document.compareform.checkcompare[" + idx + "].checked") == true)
{
alert("checking");
total += 1;
}
}
if (total==2 || total==4)
{
/* document.compareform.submit(); */
alert("success");
}
else
{
alert('Select minimum of 2 or maximum of 4 Estimates');
}
//alert("You selected " + total + " boxes.");
}
Its not working..can someone help..Thanks

Something tells me you have little idea what you're doing.
First off, you're creating one form for EVERY checkbox. Open the form tag, then put in your loop to add the checkboxes, then close the form.
Now for your script...
form is undefined, so you can get its elements. form.checkcompare is undefined, so you can't get its length. You probably want to pass this in the onSubmit event (onSubmit="return checkBox(this);"), and function checkBox(form). Then use form.querySelectorAll('input[type=checkbox]');.
Next, why in the world are you using evil eval just to get an array index?
As if that weren't enough you say you want "between 2 and 4" but your code considers "3" invalid.
Finally, you're not returning anything.
Fixed (and improved) code:
function checkBox(form){
var total = 0;
var boxes = form.querySelectorAll('input[type=checkbox]:checked').length;
if (boxes < 2 || boxes > 4)
return true;
else {
alert('Select minimum of 2 or maximum of 4 Estimates');
return false;
}
}

function getNumberOfCheckedCheckboxes ( form ) {
var returnValue = 0;
var inputElements = form.getElementsByTagName("input");
for (var i = 0; i < inputElements.length; i ++) {
if (inputElements.type == "checkbox") {
if (inputElments.checked) {
returnValue ++;
}
}
}
return returnValue;
}

Related

How do I combine 2 onclick functions in javascript?

Hi there I am trying to combine 2 javascript onClick function so that they only fire once both have been clicked, this is what I have currently attempted.
Javascript
click.onclick = function() {
for (let i = 0; i < 1; i++) {
console.log("Clicks counted " + I);
}
}
click2.onclick = function() {
for (let i = 0; i < 1; i++) {
console.log("Clicks counted " + I);
}
}
if (click.onclick && click2.onclick === true) {
console.log("You have clicked on both onClicks");
}
HTML
<section>
<button id="button-click">Nice</button>
<button id="button-click-2">Even nicer</button>
</section>
Super simple I know, but I just wanted to figure out how to do this as it's for an API call so requires both buttons to be clicked and then send a statement.
You could use a function which checks a value. This value is made up by using bitwise or with 1 or 2, for more buttons double the value for each one.
In the checking function, check the value which is 2n - 1, for two check against 3.
let clickButtons = 0;
function check() {
if (clickButtons === 3) console.log("You have clicked on both onClicks");
}
document.getElementById("button-click").addEventListener('click', function() {
clickButtons |= 1;
check();
});
document.getElementById("button-click-2").addEventListener('click', function() {
clickButtons |= 2;
check();
});
<section>
<button id="button-click">Nice</button>
<button id="button-click-2">Even nicer</button>
</section>

The sum cannot show although i click on the button

What I want is, after the user enters the number of subjects, the system will show the number of input box according to the number of subjects entered, then when the user clicks on the button, it should show the sum. I tried many ways, but I failed to show the sum, anyone knows what is the mistake I made?
Below is my code:
function select() {
var x = parseInt(document.getElementById('1').value);
if (document.getElementById('1').value == "") {
alert("Please fill up number of subject");
} else if (isNaN(x) == true) {
alert("Please fill up number of subject with number");
} else {
var subject = parseInt(document.getElementById('1').value);
var sum = 0;
for (var num = 1; num <= subject; num++) {
document.write("Enter the mark for subject " + num + " : ");
var value = parseFloat(document.write("<input/><br>"));
sum += value;
}
var calc = document.write("<button>Next</button><br>");
calc.onclick = function() {
next()
};
function next() {
document.write("Total marks: " + sum + "%");
}
}
}
<html>
<body>
Enter the number of subject: <input type="text" onkeypress="return/[0-9]/i.test(event.key)" id="1" value=""><br>
<button onclick="select()">Check</button><br>
</body>
</html>
That's how I have rewritten a big part of your code. I have place inline comments to explain what I do.
function select() {
var x = parseInt(document.getElementById('1').value, 10);
// Getting the div that wraps the initial form.
var formWrapper = document.querySelector('.formWrapper');
// Getting the div, that is going to display the new fields and the results.
var results = document.querySelector('.results');
// I have switch your statement from x == '' to '' === x as it
// consists a good practice
if ( '' === x ) {
alert("Please fill up number of subject");
// I have remove the isNaN(x) == true, because the isNan will
// be either true or false.
} else if ( isNaN(x) ) {
alert("Please fill up number of subject with number");
} else {
// Using parseInt(x, 10) to set the base.
var subject = parseInt(x, 10);
// In this array, I store the auto-generated fields.
var fieldsList = [];
// Removing the first div from the DOM
formWrapper.parentElement.removeChild(formWrapper);
for ( var num = 1; num <= subject; num++ ) {
// I am creating a new field
var newField = document.createElement('input');
// I push the field into the array I made for the fields.
fieldsList.push(newField);
// I append the field in the HTML
results.appendChild(newField);
// I create a <br> tag
var br = document.createElement('br');
// And I append the tag in the DOM
results.appendChild(br);
}
// I create the button that is going to handle the Next functionality
var nextButton = document.createElement('button');
// I set the button text
nextButton.innerText = 'Next';
// I add an Event Listener for the click event.
nextButton.addEventListener(
'click',
function() {
// I reset the sum to 0
var sum = 0;
// I itterate the fields auto-generated and saved in the array
fieldsList.forEach(
function(field) {
// I get the value
sum += parseInt(field.value, 10);
}
);
// I create the field that is going to display the output
let resultText = document.createElement('div');
// I set the text based on the sum
resultText.innerText = "Total marks: " + sum + "%";
// I append the text message to the DOM
results.appendChild(resultText);
}
);
// I append the button to the DOM
results.appendChild(nextButton);
}
}
<html>
<body>
<div class="formWrapper">
Enter the number of subject: <input type="text" onkeypress="return/[0-9]/i.test(event.key)" id="1" value=""><br>
<button onclick="select()">Check</button><br>
</div>
<div class="results"></div>
</body>
</html>

How to give alert on multiple textarea if already texarea id using jsp

This is textarea which display multiple text box with taking input using jsp.
I want to give alert to each area if phase is not selected then descripton will not be blank and descripion should not be exceed after 50 char.
<textarea id=<%out.print("desc__" + time);%> name=<%out.print("desc_" + time);%> rows="4" cols="50" style="margin-left: 85px"></textarea>
This is my Javascript Code.
function Validation()
{
for(var i = 9; i < 23; i++)
{
var selectvalue = document.getElementById("phase__"+i).value;
var desc = document.getElementById("desc__"+i).value;
if(selectValue == 'Select' && desc!='')
{
alert("Please select phase");
}
else if(selectValue!='Select' && desc>10)
{
alert("Please select desc with max length 100 n min 10");
}
alert(a);
}
// form will not get submitted..
return true;
}

Page refreshes after javascript function

After I excecute my JS function over onClick button method. My site refreshes and everything that was writen with innerHTML is erased. I think i'm missing something. I will just put the whole JS function here. I probably don't understand something and that's what is causing it.
function stisk() {
var stevilo = prompt("Vnesi iskano stevilo");
var seznam = document.getElementById("vnos").value;
var pattern = new RegExp("^[0-9](,\s*[0-9])+$");
var vsota = 0;
var seznam = seznam.split(',');
var dolzina = seznam.length;
var pravilnost = pattern.test(seznam);
if (pravilnost == true) {
for (i = 0; i < dolzina; i++) {
vsota = vsota + parseInt(seznam[i]);
}
for (i = 0; i < dolzina - 1; i++) {
var star = document.getElementById("stevila").innerHTML;
if (isNaN(seznam[i]) == false) {
var starejsi = document.getElementById("stevila").innerHTML = star + parseInt(seznam[i]) + "+";
} else {
document.getElementById("stevila").innerHTML = "Vnos ni pravilen";
}
}
document.getElementById("stevila").innerHTML = starejsi + seznam[dolzina - 1] + "=" + vsota;
var c = 0;
for (i = 0; i < seznam.length; i++) {
if (stevilo == seznam[i]) {
c++;
}
}
if (c == 0) {
alert("stevila ni na seznamu");
} else {
alert("Stevilo je na seznamu");
}
} else {
document.getElementById("stevila").innerHTML = "Napacen vnos stevil";
}
}
HTML:
Here is the browser view:
After i press "V redu" (OK) Everything goes back to the start, expacting me to write a number inside. I want the 2+3+4=9 to stay there if that is possible? Thanks
Change:
<button onclick="stisk()">OK</button>
to:
<input type="button" onclick="stisk()">OK</input>
Like #Teemu said, < button > will submit a form element.
Another solution
<button onclick="stisk(event)">OK</button>
and in javascript
function stisk(e){
e.preventDefault();
...
This can be useful in other cases, like default behavior of <a href element is to redirect page, so you can prevent default behavior with event.preventDefault()
even better solution - let your button submit form, but prevent default on form submit
<form onsubmit="stisk(e)">
...
<button type="submit">
and in javascript
function stisk(e){
e.preventDefault();
...
and it will work when submitting form with Enter in input field.

HTML + javascript mouse over, mouseout, onclick not working in firefox

My question is to get onMouseover,onMouseout,onMousedown,onClick on a table row. For which i am calling javascript userdefined functions.
onMouseover --- Background color should change.
onMouseout --- Reset to original color
onClick --- First column checkbox/radio button should be set and background color should change
onMousedown --- background color should change.
My code in html is:-
<tr onMouseOver="hover(this)" onMouseOut="hover_out(this)" onMouseDown="get_first_state(this)" onClick="checkit(this)" >
and the methods in javascripts are:-
var first_state = false;
var oldcol = '#ffffff';
var oldcol_cellarray = new Array();
function hover(element) {
if (! element) element = this;
while (element.tagName != 'TR') {
element = element.parentNode;
}
if (element.style.fontWeight != 'bold') {
for (var i = 0; i<element.cells.length; i++) {
if (element.cells[i].className != "no_hover") {
oldcol_cellarray[i] = element.cells[i].style.backgroundColor;
element.cells[i].style.backgroundColor='#e6f6f6';
}
}
}
}
// -----------------------------------------------------------------------------------------------
function hover_out(element) {
if (! element) element = this;
while (element.tagName != 'TR') {
element = element.parentNode;
}
if (element.style.fontWeight != 'bold') {
for (var i = 0; i<element.cells.length; i++) {
if (element.cells[i].className != "no_hover") {
if (typeof oldcol_cellarray != undefined) {
element.cells[i].style.backgroundColor=oldcol_cellarray[i];
} else {
element.cells[i].style.backgroundColor='#ffffff';
}
//var oldcol_cellarray = new Array();
}
}
}
}
// -----------------------------------------------------------------------------------------------
function get_first_state(element) {
while (element.tagName != 'TR') {
element = element.parentNode;
}
first_state = element.cells[0].firstChild.checked;
}
// -----------------------------------------------------------------------------------------------
function checkit (element) {
while (element.tagName != 'TR') {
element = element.parentNode;
}
if (element.cells[0].firstChild.type == 'radio') {
var typ = 0;
} else if (element.cells[0].firstChild.type == 'checkbox') {
typ = 1;
}
if (element.cells[0].firstChild.checked == true && typ == 1) {
if (element.cells[0].firstChild.checked == first_state) {
element.cells[0].firstChild.checked = false;
}
set_rowstyle(element, element.cells[0].firstChild.checked);
} else {
if (typ == 0 || element.cells[0].firstChild.checked == first_state) {
element.cells[0].firstChild.checked = true;
}
set_rowstyle(element, element.cells[0].firstChild.checked);
}
if (typ == 0) {
var table = element.parentNode;
if (table.tagName != "TABLE") {
table = table.parentNode;
}
if (table.tagName == "TABLE") {
table=table.tBodies[0].rows;
//var table = document.getElementById("js_tb").tBodies[0].rows;
for (var i = 1; i< table.length; i++) {
if (table[i].cells[0].firstChild.checked == true && table[i] != element) {
table[i].cells[0].firstChild.checked = false;
}
if (table[i].cells[0].firstChild.checked == false) {
set_rowstyle(table[i], false);
}
}
}
}
}
function set_rowstyle(r, on) {
if (on == true) {
for (var i =0; i < r.cells.length; i++) {
r.style.fontWeight = 'bold';
r.cells[i].style.backgroundColor = '#f2f2c2';
}
} else {
for ( i =0; i < r.cells.length; i++) {
r.style.fontWeight = 'normal';
r.cells[i].style.backgroundColor = '#ffffff';
}
}
}
It is working as expected in IE.
But coming to firefox i am surprised on seeing the output after so much of coding.
In Firefox:--
onMouseOver is working as expected. color change of that particular row.
onClick -- Setting the background color permenantly..eventhough i do onmouseover on different rows. the clicked previous row color is not reset to white. -- not as expected
onclick on 2 rows..the background of both the rows is set..Only the latest row color should be set. other rows that are selected before should be set back..not as expected i.e if i click on all the rows..background color of everything is changed...
Eventhough i click on the row. First column i.e radio button or checkbox is not set..
Please help me to solve this issue in firefox. Do let me know where my code needs to be changed...
Thanks in advance!!
Sorry for making everything inline, but this should work in all browsers:
<tr onmouseover="this.className += ' hover'" onmouseout="this.className = this.className.replace(/(^|\s)hover(\s|$)/,' ');" onclick="if(this.getElementsByTagName('input')[0].checked){this.className = this.className.replace(/(^|\s)click(\s|$)/,' ');this.getElementsByTagName('input')[0].checked = false;}else{this.className += ' click';this.getElementsByTagName('input')[0].checked = true;}">
Here is a complete page you can test out:
<html>
<head>
<style type="text/css">
tr.click{
background:yellow;
}
tr.hover{
background:green;
}
</style>
</head>
<body>
<table border="1">
<tr onmouseover="this.className += ' hover'" onmouseout="this.className = this.className.replace(/(^|\s)hover(\s|$)/,' ');" onclick="if(this.getElementsByTagName('input')[0].checked){this.className = this.className.replace(/(^|\s)click(\s|$)/,' ');this.getElementsByTagName('input')[0].checked = false;}else{this.className += ' click';this.getElementsByTagName('input')[0].checked = true;}">
<td>
<input type="checkbox" readonly="readonly"/> click me
</td>
</tr>
<tr onmouseover="this.className += ' hover'" onmouseout="this.className = this.className.replace(/(^|\s)hover(\s|$)/,' ');" onclick="if(this.getElementsByTagName('input')[0].checked){this.className = this.className.replace(/(^|\s)click(\s|$)/,' ');this.getElementsByTagName('input')[0].checked = false;}else{this.className += ' click';this.getElementsByTagName('input')[0].checked = true;}">
<td>
<input type="checkbox" readonly="readonly"/> click me
</td>
</tr>
<tr onmouseover="this.className += ' hover'" onmouseout="this.className = this.className.replace(/(^|\s)hover(\s|$)/,' ');" onclick="if(this.getElementsByTagName('input')[0].checked){this.className = this.className.replace(/(^|\s)click(\s|$)/,' ');this.getElementsByTagName('input')[0].checked = false;}else{this.className += ' click';this.getElementsByTagName('input')[0].checked = true;}">
<td>
<input type="checkbox" readonly="readonly"/> click me
</td>
</tr>
</table>
</body>
</html>
I would strongly advise moving everything to an external JS file and using some sort of initialization function to assign the event listeners, instead of writing them all inline like me.
I hope this helps in some way.
There may be a particular reason you haven't, but have you considered using a library such as JQuery to tackle this? What you're trying to achieve here could be done very easily and simply with JQuery's CSS-like selectors and .parent/.parents.
As MartyIX says, I would start by using console.log and/or breakpoints in Firebug / Chrome to check exactly which code blocks are being executed. Using the javascript debugging tools can be a little daunting at first until you get how each of the options (step into, step over) work, but they do allow you to check that the code is working as you think it is very easily.
One thing I notice in checkit() - be careful with where you declare variables. I'm not an expert with javascripts variable scoping, but to me it looks like the typ variable only exists within the if block. I would declare "var typ" before the if block and use a third value or second variable to check whether any checkbox or radio is found (what happens if no checkbox and no radio is found?)

Categories

Resources