I have some problems here with javascript.
I want someone to choose an option and a checked box, and if both are checked then other checkboxes should not be able to click.
I had tried to give the function 2 parameters (one is for the option and one for the checkbox).
function bs(id /*,chbxvalue */ )
{
var selectElement = document.getElementById(id);
var selectValue = selectElement.options[selectElement.selectedIndex].value;
//var select2Element = document.getElementById(chbxvalue);
//var selectCHBXval = select2Element.options[select2Element.selectedIndex].value;
if((selectValue == "banana" ) /*&& (document.getElementById("apple").checked == true )*/ )
{
document.getElementById("juice").checked = true;
}
else if(selectValue == "Salad")
{}
}
The thing in the comments doesn't work.
<div id="flavor"><br />
<select id="bss" name="beh" onChange="bs('bss')">
<option value="banana" >banana</option>
<option value="pinapple" >pinapple</option>
</select>
</div>
<div id="divcontainer" class="cont" style="display:block;">
<input type="checkbox" name="app" id="apple" value="appl" />Apples <br />
<input type="checkbox" name="juices" id="juice" value="fj" />Fruitjuice <br />
</div>
I've changed the names here. Has anybody an idea? Sorry, I am not so good with javascript... .
Sounds like you'd like to use simply
document.getElementById("...").disabled=true;
Or if you'd like to disable more checkboxes at once, assign them a class, and use
elements = document.getElementsByClassName("my_class");
for(var i = 0; i < elements.length; ++i)
{elements[i].disabled = "true"; }
I'm not exactly sure if this is what you're after, but it seems like you want some kind of conditional logic. I made a fiddle to illustrate it: https://jsfiddle.net/75uLereo/
var radios = document.myform.type,
select = document.myform.flavor;
for(var i = 0; i < radios.length; i++){
radios[i].addEventListener('change', checkValues);
}
select.addEventListener('change', checkValues);
function checkValues(){
var select = document.myform.flavor,
selectedValue = select.options[select.selectedIndex].value,
radioValue = document.querySelector('input[name = "type"]:checked').value;
if(radioValue !== "undefined"){
switch(selectedValue){
case 'none':
case 'banana':
case 'strawberry':
alert("This is "+selectedValue+" and "+radioValue+". Do some conditional logic with the values!");
break;
default:
break;
}
}
}
This binds a function to change events on the radio buttons and the select and then uses a switch on the different values to do whatever you want it to do.
Updated:
I made another example, with checkboxes and the bool value from the checkboxes if they are selected
https://jsfiddle.net/75uLereo/2/
Related
I am building a project on attendance management. In one of the forms of my project, I have multiple checkboxes. I want that at least one checkbox must be checked for form submission. I tried with Javascript but the problem is, it flag an alert even if one or more checkbox is checked.
Here is my js code :
function validat(){
var a = document.getElementsByTagName("checkbox");
var bool=false;
for(var i=0;i<a.length;i++){
if(a[i].checked==true){
bool=true;
}
}
if(bool){
return true;
}
else{
alert("Sorry!Please select checkbox corresponding to students involved in duty leaves.");
return false;
}
Here's my checkbox code :
echo "<input type='checkbox' name=duty[]' value='$row[university_roll_no]'></td></tr>";
Since you need at least one checkbox to be checked you don't have to loop through all the checkboxes in your form. In the first found checkkbox you can stop.
function validat(){
var checkboxes = document.getElementsByTagName("checkbox");
var atLeastOneCheckBoxIsChecked = false;
for( var i = 0; i < checkboxes.length; i++ ){
if( checkboxes[i].checked == true ){
atLeastOneCheckBoxIsChecked = true;
break;
}
}
if(atLeastOneCheckBoxIsChecked){
return true;
}
else {
alert("Sorry!Please select checkbox corresponding to students involved in duty leaves.");
return false;
}
}
A more functional way to do the same thing, is to be use Array.prototype.some method:
function validat(){
var atLeastOneCheckBoxIsChecked = document.getElementsByTagName("checkbox")
.some(checkbox => checkbox.checked == true);
if(atLeastOneCheckBoxIsChecked){
return true;
}
else {
alert("Sorry!Please select checkbox corresponding to students involved in duty leaves.");
return false;
}
}
Here you have an example:
function check() {
var checkboxes = document.querySelectorAll('input[type="checkbox"]');
var checkedOne = Array.prototype.slice.call(checkboxes).some(x => x.checked);
if (!checkedOne) {
console.log('please check at least one box!');
}
console.log(checkedOne);
}
<fieldset>
<legend>Choose some monster features</legend>
<div>
<input type="checkbox" id="scales" name="feature" onClick=check()
value="scales" checked />
<label for="scales">Scales</label>
</div>
<div>
<input type="checkbox" id="horns" name="feature" onClick=check()
value="horns" />
<label for="horns">Horns</label>
</div>
<div>
<input type="checkbox" id="claws" name="feature" onClick=check()
value="claws" />
<label for="claws">Claws</label>
</div>
</fieldset>
You need to get input elements and check if type is "checkbox":
var a = document.getElementsByTagName("input");
for(var i = 0; i < a.length; i++) {
if(inputs[i].type == "checkbox") {
if (inputs[i].checked) {
bool=true;
}
}
}
Change your line
var a = document.getElementsByTagName("checkbox");
to
var a = document.querySelectorAll('input[type="checkbox"]');
I would have preferred you to use jQuery but with what you currently have, you need to do this:
var a = document.getElementsByTagName("input");
And then:
if(a[i].type == 'checkbox' && a[i].checked==true){
// Checked alert
}
I want the checked checkboxes to be unchecked when clicking another button:
Below is the HTML
<input type="checkbox" name="checkb" id="Agent" value="Agent"> type=Agent
<br />
<input type="checkbox" name="checkb" id="Customer" value="Customer"> type=Customer
<br />
<input type="checkbox" name="checkb" id="Phone" value="Phone"> type=Phone
<br />
<input type="checkbox" name="checkb" id="ID_Card" value="ID_Card"> type=ID_Card
<br />
<input type=datetime id="Start_Date" value="" placeholder="Start_Date" />
<input type=datetime id="End_Date" value="" placeholder="End_Date" />
<button id="date">
Interval
</button>
On clicking of the Interval button if any checkboxes are checked they should get unchecked.
Below is the event listener for the Interval button:
var check1 = document.getElementById("Agent");
var check2 = document.getElementById("Customer");
var check3 = document.getElementById("Phone");
var check4 = document.getElementById("ID_Card");
var newBtn = document.getElementById("date");
if (newBtn) {
newBtn.addEventListener("click", function() {
if (check1.checked) {
var ischecked1 = check1.checked;
check1.checked != ischecked1;
}
if (check2.checked) {
var ischecked2 = check2.checked;
check2.checked != ischecked2;
}
if (check3.checked) {
var ischecked3 = check3.checked;
check3.checked != ischecked3;
}
if (check4.checked) {
var ischecked4 = check4.checked;
check4.checked != ischecked4;
}
});
}
Below code runs without any errors, but the boxes do not get unchecked if they are checked.
Below is the fiddle
Your statements are just evaluating as booleans, not performing assignments:
check1.checked != ischecked1; // this returns a boolean, doesn't do any assignment
You want to do this to toggle the checked state:
check1.checked = !ischecked1;
Same thing for other checkboxes.
There's also no need to create the extra variables, you can just do the toggling and reading directly:
check1.checked = !check1.checked;
Since you're only toggling checkboxes when they are checked, you can just directly set them to false as well.
if (check1.checked) check1.checked = false;
Instead of having if statements, you can use array iteration to do the toggling:
[check1, check2, check3, check4].forEach(check => {
if (check.checked) {
check.checked = false;
}
});
// or query the checkboxes directly and do the same
[...document.querySelectorAll('input[type="checkbox"]')].forEach(check => {
if (check.checked) {
check.checked = false;
}
});
Your mistake is in this line:
check1.checked != ischecked1;
This actually means "compare if check1.checked is not equal to ischecked1".
Most simple solution would be to remove the if statement and just do this:
check1.checked = !check1.checked
This means "set check1.checked to the opposite of check1.checked".
Since all checkboxes have the same name you could also collect all checkboxes by requesting them by name and use a loop to walk through them. A small example:
// Collect all checkboxes with a CSS selector that matches all input
// elements with a name attribute that's equal to "checkb"
var checkboxes = document.querySelectorAll('input[name="checkb"]');
var newBtn = document.getElementById("date");
if (newBtn) {
newBtn.addEventListener("click", function() {
// this is a for loop, it will run for as long as i
// is smaller than the amount of found checkboxes (checkboxes.length)
for(var i = 0; i < checkboxes.length; i++) {
// Get the checkbox from the checkboxes collection
// collection[i] means get item from collection with index i
var checkbox = checkboxes[i];
// Revert the .checked property of the checkbox
checkbox.checked = !checkbox.checked;
}
});
}
By the looks of it you just want to uncheck everything on click of button
you can just do this
var newBtn = document.getElementById("date");
if (newBtn) {
newBtn.addEventListener("click", function() {
document.getElementById("Agent").checked =
document.getElementById("Customer").checked =
document.getElementById("Phone").checked =
document.getElementById("ID_Card").checked = false;
});
}
I have 3 checkboxes and I want them to do certain actions i.e display an alert box when they are checked and when one check box is checked, the others should be unchecked.
I've been able to get the second part to work where only one checkbox can be checked at a time but I can't seem to make the first part of displaying an alert box work.
js that ensures only one box is checked at any time:
function qtyBox(e) {
var c = document.getElementsByClassName("qty");
for (var i = 0; i < c.length; i++) {
c[i].checked = false;
}
e.checked = true;
}
html:
<input class="qty" type="checkbox" id="pails" onchange="qtyBox(this)"/>Pails
<input class="qty" type="checkbox" id="liters" onchange="qtyBox(this)"/>Liters
<input class="qty" type="checkbox" id="gallons" onchange="qtyBox(this)"/>Gallons
Now all that's left is when Pails is checked,I want an alert box to display pails. when liters is checked, an alert box to display liters and when gallons is checked, an alert box to display gallons.
You need to get reference to the input. Just add:
var currId = e.id;
if(currId === "pails") alert("Pails");
else if(currId === "liters") alert("Liters");
else if(currId === "gallons") alert("Gallons");
so it become:
function qtyBox(e) {
var c = document.getElementsByClassName("qty");
for (var i = 0; i < c.length; i++) {
c[i].checked = false;
}
e.checked = true;
var currId = e.id;
if(currId === "pails") alert("Pails");
else if(currId === "liters") alert("Liters");
else if(currId === "gallons") alert("Gallons");
}
Hope this help.
Use radio buttons with a common name (e.g. units) and a click listener to do the alert. Add a value attribute for the value, an ID seems redundant:
<input class="qty" name="units" type="radio" value="pails" onclick="alert(this.value)">Pails
<input class="qty" name="units" type="radio" value="litres" onclick="alert(this.value)">Litres
<input class="qty" name="units" type="radio" value="gallons" onclick="alert(this.value)">Gallons
Though I'd delegate the listener to an ancestor element.
You should remove the onclick from the html - and just use something like this. However, if you want to use jquery would easier, but here is vanilla javascript solution. ( in a js file or wrapped in script tags )
(function(){
var inputs = document.getElementsByClassName('qty');
for(i=0; i<inputs.length; i++){
var el = inputs[i];
el.addEventListener('click', function(){
for (var i = 0; i < inputs.length; i++) {
inputs[i].checked = false;
}
this.checked = true
alert(this.id);
});
}
})();
I have a form located on my html page with a bunch of checkboxes as options. One of the options is "check-all" and I want all the other check boxes to be checked, if unchecked, as soon as the "check-all" box is checked. My code looks something like this:
<form method = "post" class = "notification-options">
<input type = "checkbox" name = "notification-option" id = "all-post" onClick = "javascript:checkALL(this
);"> All Posts <br/>
<input type = "checkbox" name = "notification-option" id = "others-post"> Other's Posts <br/>
<input type = "checkbox" name = "notification-option" id = "client-post"> Cilent's Post <br/>
<input type = "checkbox" name = "notification-option" id = "assign-post"> Task Assigned </form>
java script:
<script type = "text/javascript">
var $check-all = document.getElementbyId("all-post");
function checkALL($check-all){
if ($check-all.checked == true){
document.getElementByName("notification-option").checked = true;
}
}
</script>
nothing happens when I run my code
Here are some guidelines.
type attribute is not needed and can be omitted.
JS variable names can't contain hyphens, a typo in
getElementById()
You're using a global variable name as an argument, in the same time
you're passing this from online handler. The passed argument shadows the
global within the function.
if (checkAll.checked) does the job
Typo in getElementsByName(), gEBN() returns an HTMLCollection,
which is an array-like object. You've to iterate through the
collection, and set checked to every element separately.
Fixed code:
<script>
var checkAll = document.getElementById("all-post");
function checkALL(){
var n, checkboxes;
if (checkAll.checked){
checkboxes = document.getElementsByName("notification-option");
for (n = 0; n < checkboxes.length; n++) {
checkboxes[n].checked = true;
}
}
}
</script>
You can also omit the javascript: pseudo-protocol and the argument from online handler.
You can do it like this using jQuery:
$("#all-post").change(function(){
$('input:checkbox').not(this).prop('checked', this.checked);
});
Here is a JSfiddle
if all post check box is checked it will set check=true of others-post and client-post check boxes
$("input[id$=all-post]").click(function (e) {
if ($("input[id$=all-post]").is(':checked')) {
$("input[id$=others-post]").prop('checked', true);
$("input[id$=client-post]").prop('checked', true);
}
});
Check to see if any of the checkboxes are not checked first.
If so, then loop through them and check any that aren't.
Else, loop through them and uncheck any that are checked
I have an example at http://jsbin.com/witotibe/1/edit?html,output
http://jsfiddle.net/AX3Uj/
<form method="post" id="notification-options">
<input type="checkbox" name="notification-option" id="all-post"> All Posts<br>
<input type="checkbox" name="notification-option" id="others-post"> Other's Posts<br>
<input type="checkbox" name="notification-option" id="client-post"> Cilent's Post<br>
<input type="checkbox" name="notification-option" id="assign-post"> Task Assigned
</form>
function checkAll(ev) {
checkboxes = document.getElementById('notification-options').querySelectorAll("input[type='checkbox']");
if (ev.target.checked === true) {
for (var i = 0; i < checkboxes.length; ++i) {
checkboxes[i].checked = true;
}
} else {
for (var i = 0; i < checkboxes.length; ++i) {
checkboxes[i].checked = false;
}
}
}
I have the following code. I need to see how many checkboxes have been checked in my form and if there are more than four display error and uncheck the last check box,everything is working but how can I uncheck the last check box, thanks
function SetHiddenFieldValue()
{
var checks = document.getElementById('toppings').getElementsByTagName('input');
var toppings = new Array();
var randomNumber = Math.floor((Math.random() * 9000) + 100);
var totalChecked = 0;
var itemPrice = 5.99;
for (i = 0; i < checks.length; i++)
{
if (checks[i].checked)
{
toppings[i] = checks[i].value;
totalChecked += 1;
}
}
if (totalChecked > 4) {
alert("You can only choose up to Max of 4 Toppings");
} else {
itemPrice = itemPrice + (totalChecked * 0.99);
document.getElementById('my-item-name').value = toppings.join("\t");
document.getElementById('my-item-id').value = randomNumber;
document.getElementById('my-item-price').value = itemPrice;
}
}
And my form is:
<form id="pizza" name="pizza" method="post" action="" class="jcart">
<input type="hidden" name="my-item-id" id="my-item-id" value="" />
<input type="hidden" name="my-item-name" id="my-item-name" value="" />
<input type="hidden" name="my-item-price" id="my-item-price" value="" />
<input type="hidden" name="my-item-qty" value="1" />
<input type="submit" name="my-add-button" value=" add " />
</form>
I think that I would handle this differently. I'd have a click handler on each checkbox that counts the number of checked boxes (including the current if it is being checked) to see if it is greater than 4. If it is, then I would stop the current event, pop the alert, and reset the state of the checkbox causing the alert. This way it would always popup when clicking the fourth checkbox.
To handle the case where javascript is disabled, you'd need to make sure that your server-side code validates that no more than 4 checkboxes have been checked.
JQuery example:
$(':checkbox').click( function() {
if ($(this).val() == 'on') { // need to count, since we are checking this box
if ($(':checkbox:checked').length > 4) {
alert( "You can only choose up to a maximum of 4 toppings." );
$(this).val('off');
}
}
});
Note if you had other types of checkboxes on the page you could use a class to distinguish them. In that case, the selector becomes (':checkbox.topping') and (':checkbox.topping:checked').
Keep track of the last checked checkbox and set its checked property to false:
// ...
var lastChecked; // Will be used in loop below
for (i = 0; i < checks.length; i++)
{
if (checks[i].checked)
{
toppings[i] = checks[i].value;
totalChecked += 1;
lastChecked = i; // Store the checkbox as last checked
}
}
if (totalChecked > 4) {
alert("You can only choose up to Max of 4 Toppings");
checks[lastChecked].checked = false; // Uncheck the last checked checkbox
} else {
// ...
If you want to uncheck all but the four first ones, do it like this:
// ...
for (i = 0; i < checks.length; i++)
{
if (checks[i].checked)
{
toppings[i] = checks[i].value;
totalChecked += 1;
if (totalChecked > 4) checks[i].checked = false; // Uncheck checkbox
}
}
Well you'll need to somehow pass into this method which particular checkbox was just checked, and then if the total checked count test fails, then just set that checkbox's .checked property to false.
What if the user checked more than five?
One way to do it is create a javascript function that returns false if more than four checkboxes are checked. In each checkbox, hook the new function like this:
<input type="checkbox" onclick="return myNewFunction(this);">
This will inhibit the user from checking any checkbox that is the fifth one.
Alternatively, you could prevent the user from making an invalid action in the first place, by disabling all the other boxes once four of them are checked, and displaying a message like "Choose up to four of these." This way, you don't let the user do something you know is invalid and then scold them.