How to check all checkboxes using JS? - javascript

I want to check all checkboxes using javascript. When I click on submit button all the checkboxes should be checked. However all the checkboxes are checked just for a few seconds.
What am I doing wrong?
html:
<form method="post" name="myform">
<input type="checkbox" name="h" value="1" id="g">Reading<br/>
<input type="checkbox" name="h" value="2" id="g">php<br/>
<input type="checkbox" name="h" value="3" id="g">playing<br/>
<input type="checkbox" name="h" value="4" id="g">Gaming<br/>
<input type="checkbox" name="h" value="5" id="g">Coding<br/>
<input type="submit" name="sub" value="submit" onclick="checkall(document.myform.h)" >
</form>
javascript code:
<script type="text/javascript">
function checkall(chk){
for(var i = 0; i < chk.length; i++) {
chk[i].checked = true;
}
}
</script>

the problem is you are using a submit button within a form, which on click will submit the form.
So one solution is to change the button form a submit button to a normal button which will not trigger the submit of the form.
function checkall(chk) {
var i;
for (i = 0; i < chk.length; i++) {
chk[i].checked = true;
//return true;
}
}
<form method="post" name="myform">
<input type="checkbox" name="h" value="1" id="g">Reading
<br/>
<input type="checkbox" name="h" value="2" id="g">php
<br/>
<input type="checkbox" name="h" value="3" id="g">playing
<br/>
<input type="checkbox" name="h" value="4" id="g">Gaming
<br/>
<input type="checkbox" name="h" value="5" id="g">Coding
<br/>
<!--<input type="radio" name="gen" value="male">Male<br/>-->
<!--<input type="radio" name="gen" value="female">Female<br/>-->
<input type="button" name="sub" value="submit" onclick="checkall(document.myform.h)">
</form>

You created a form.And form will be submit after click on submit button.You can use following approach to select all checkbox only.
step 1- Write following statement in html.
<input type="checkbox" name="h" value="1" class="g">Reading<br/>
<input type="checkbox" name="h" value="2" class="g">php<br/>
<input type="checkbox" name="h" value="3" class="g">playing<br/>
<input type="checkbox" name="h" value="4" class="g">Gaming<br/>
<input type="checkbox" name="h" value="5" class="g">Coding<br/>
<input type="button" name="sub" value="check all" id='custom_button'>
step 2- Write following statement in js file-
jQuery('#custom_button').click(function(){
jQuery('.g').each(function() { //loop through each checkbox
this.checked = true; //deselect all checkboxes with class "checkbox1"
});
});
Above statement will select all checkbox after click on button.
If you want to check example please use this link - http://jsfiddle.net/oxg3p1ny/1/

your code is working just stop from form submit will solve your problem use <form method="post" name="myform" onsubmit="return false"> and use ajax to get data.
Working Fiddle

Related

Set hidden value based on radio button selection

Cannot find an answer:
I have searched Stack Overflow, however, despite finding lots of similar posts — and more complicated situations — I still couldn't find an answer to the issue I am trying to solve.
Here's my issue:
I have four radio buttons, and one hidden field:
<!-- My HTML Document -->
<form action="/my-doc.html" method="post">
<!-- The 4 Radio Buttons-->
<input type="radio" name="game" value="1" checked> First
<input type="radio" name="game" value="2"> Second
<input type="radio" name="game" value="3"> Third
<input type="radio" name="game" value="4"> Fourth
<!-- The Hidden Field -->
<input type="hidden" name="criteria" value="1">
<!-- My Submit Button -->
<input type="submit" name="action" value="Go">
</form>
What I need to do is set the value of <input type="hidden" name="criteria" value="1"> so that it is 0
Like this: <input type="hidden" name="criteria" value="0">
...but only after the user selects either the first, or second, radio button. The value of the hidden field should remain as being equal to 1 if any other radio button is selected.
How does a person do this using JavaScript?
Requirements: "Looking for a VanillaJS answer."
you can try below option
In javascript
function setValue() {
var selectedRadio = '';
var games = document.getElementsByName('game')
for (var i = 0; i < games.length; i++) {
if (games[i].checked) {
selectedRadio = games[i].value;
}
}
document.getElementById("hdnSelectedRadValue").value = (selectedRadio == "1" || selectedRadio == "2") ? "0" : "1";
return false;
}
Changes to do in HTML side
<body style="background-color: #f2f2f2;">
<form action="some.htm" method="post">
<input type="radio" name="game" value="1" checked> First
<input type="radio" name="game" value="2"> Second
<input type="radio" name="game" value="3"> Third
<input type="radio" name="game" value="4"> Fourth
<input type="text" name="criteria" id="hdnSelectedRadValue">
<input type="submit" name="action" value="Go" onclick="setValue();">
</form>
</body>
var radios =
document.querySelectorAll('input[type=radio][name="game"]');
radios.forEach(radio => radio.addEventListener(
'change', () => {
document.getElementsByName("criteria")[0].value =
parseInt(radio.value, 10) > 2 ? '1' : '0';
}
));
<input type="radio" name="game" value="1" checked> First
<input type="radio" name="game" value="2"> Second
<input type="radio" name="game" value="3"> Third
<input type="radio" name="game" value="4"> Fourth
<input type="hidden" name="criteria" value="1">
<input type="submit" name="action" value="Go">
You can simply listen to "change" events on all of the radio buttons, then just set the value accordingly.
Here's the snippet code I have written and tested
(function(){
let hdfValue = document.getElementById("myhiddenfield")
let radioButtons = document.querySelectorAll('input[name="game"]');
let submitButton = document.querySelector('input[name="action"]')
radioButtons.forEach((input) => {
input.addEventListener('change', function(e){
let radioButtonValue = e.target.value
if(radioButtonValue == 1 || radioButtonValue == 2){
hdfValue.value = 0;
} else {
hdfValue.value = 1;
}
});
});
submitButton.addEventListener("click", function() {
console.log(hdfValue.value)
});
})()
<form>
<input type="radio" name="game" value="1" checked> First
<input type="radio" name="game" value="2"> Second
<input type="radio" name="game" value="3"> Third
<input type="radio" name="game" value="4"> Fourth
<input type="hidden" name="criteria" id="myhiddenfield" value="1">
<input type="button" name="action" value="Go">
</form>

Prevent multiple checkboxes with same name from getting reset after form submit

I have multiple classes/groups of checkboxes and each class/group contain multiple checkboxes in it with same name. When form submitted, all checkboxes get reset. I have tried many solutions available on this site but these are not working for group of checkboxes. For example:-
<form method="post" action="" name="SearchForm" >
<input type="checkbox" name="color[]" value="Black">
<input type="checkbox" name="color[]" value="White">
<input type="checkbox" name="color[]" value="Green">
<input type="checkbox" name="language[]" value="Punjabi">
<input type="checkbox" name="language[]" value="Sindhi">
<input type="checkbox" name="language[]" value="Saraiki">
</form>
How can I prevent checkboxes from getting reset after form submitted?
When the form sent, the page reloads, so all changes in the document will be lost. But you can easily do it with PHP:
<form method="post" action="" name="SearchForm">
<input type="checkbox" name="color[]" value="Black" <?php echo $_POST['color'][0]?'checked="checked"':'';?>>
<input type="checkbox" name="color[]" value="White" <?php echo $_POST['color'][1]?'checked="checked"':'';?>>
<input type="checkbox" name="color[]" value="Green" <?php echo $_POST['color'][2]?'checked="checked"':'';?>>
<input type="checkbox" name="language[]" value="Punjabi" <?php echo $_POST['language'][0]?'checked="checked"':'';?>>
<input type="checkbox" name="language[]" value="Sindhi" <?php echo $_POST['language'][1]?'checked="checked"':'';?>>
<input type="checkbox" name="language[]" value="Saraiki" <?php echo $_POST['language'][2]?'checked="checked"':'';?>>
</form>
Something like this should work.
I hope that this will help you!
To keep the checkboxes from clearing, you can use the preventDefault method. But then you'll be responsible for handling the form data yourself.
Here's what that might look like:
<form method="post" action="" name="myForm" >
<input class="color" type="checkbox" name="color[]" value="Black"> // Class matches name
<input class="color" type="checkbox" name="color[]" value="White">
<input class="color" type="checkbox" name="color[]" value="Green">
<input class="language" type="checkbox" name="language[]" value="Punjabi">
<input class="language" type="checkbox" name="language[]" value="Sindhi">
<input class="language" type="checkbox" name="language[]" value="Saraiki">
<!-- The onclick attribute calls our processForm function -->
<input type="submit" onclick="processForm(event)" value="Submit" />
</form>
<script>
function processForm(event) {
event.preventDefault(); // Keeps the form from being submitted/cleared
let checkedColorBoxes = document.querySelectorAll(".color:checked"); // Find checked boxes
let checkedLanguageBoxes = document.querySelectorAll(".language:checked");
// Store the values from the checked boxes
let selectedColors = [], selectedLanguages = [];
for(let i = 0; i < checkedColorBoxes.length; i++){
selectedColors.push(checkedColorBoxes[i].value);
}
for(let i = 0; i < checkedLanguageBoxes.length; i++){
selectedLanguages.push(checkedLanguageBoxes[i].value);
}
// Now we have the values that would have been submitted, and can do what we like with them
// If nothing better comes to mind, one (very kludgy) option is to populate another (hidden)
// form with them and secretly submit that.
console.log(`colors: ${selectedColors}`);
console.log(`languages: ${selectedLanguages}`);
}
</script>
Another approach would be to listen for when the checkboxes change and keep track of their states (checked or unchecked). Then, in processForm(), you could skip the preventDefault() call and just re-check the appropriate boxes programmatically.

Checking if a particular checkbox in a checkbox list is checked

I have a list of checkboxes:
<input name="choice" type="checkbox" id="choice1" value="A" />
<input name="choice" type="checkbox" id="choice2" value="B" />
<input name="choice" type="checkbox" id="choice3" value="C" />
<input name="choice" type="checkbox" id="choice4" value="D" />
Name is the same for all but id is different.
I need to check if a particular checkbox (for example the one with id=choice3 is checked.
Tried
if (this.choice.id === "choice3" && this.choice[2].checked) {
alert("checked!");
}
but it does not work - the alert is never reached
P.S. I need to use javascript not jquery
Thats how you do it without jQuery:
Suppose your form is like this:
<form id="myForm" action="test.php">
<input name="choice" type="checkbox" id="choice1" value="A"/>
<input name="choice" type="checkbox" id="choice2" value="B"/>
<input name="choice" type="checkbox" id="choice3" value="C"/>
<input name="choice" type="checkbox" id="choice4" value="D"/>
<input type="button" onclick="validate();" value="Submit form">
</form>
You can do the validation on submit this way:
function validate() {
if (document.getElementById('choice3').checked) {
alert("checked");
} else {
alert("You didn't check it! ");
}
}

Append multiple variables(params) to url for ajax call

I am trying to append values from a checked checkbox to a url that later would be used for an ajax call. As mentioned I would only like to have the values appended to the url if checkbox is checked. If a user checks and then unchecks, this would indicate not to add the value to the url. Below I have some basic foundation code. How can I append multiple items to the url ?
<form>
<input type="checkbox" value="1" id="item1" />
<input type="checkbox" value="2" id="item2" />
<input type="checkbox" value="3" id="item3" />
<input type="submit" id="submitForm" value="Submit Form" />
<form>
<script>
$('#submitForm').click(function() {
$('checkbox').click(function() {
$.getJSON('www.mysite.com/mypage.php?id='+item1+item2+item3)
});
});
</script>
First give your checkboxes a specific name like;
<form name="checkbox_form" id="checkbox_form">
<input type="checkbox" value="1" id="item1" name="val1" />
<input type="checkbox" value="2" id="item2" name="val2" />
<input type="checkbox" value="3" id="item3" name="val3" />
<input type="submit" id="submitForm" value="Submit Form" />
<form>
And your js will be;
$('#submitForm').click(function() {
var url = "'www.mysite.com/mypage.php";
if ($("#checkbox_form").serialize().length > 0) {
url += "?" + $("#checkbox_form").serialize();
}
alert("Your ajax url will be: " + url);
$.getJSON(url)
});
Here is a working fiddle: http://jsfiddle.net/cubuzoa/UKV3r/2/
You can use JQuery method serialize() as follows:
var query = $('form').serialize()
and after:
$.getJSON('www.mysite.com/mypage.php?'+query );
Only necessary to provide the input field attribute "name":
<form>
<input type="checkbox" value="1" id="item1" name="item1"/>
<input type="checkbox" value="2" id="item2" name="item2"/>
<input type="checkbox" value="3" id="item3" name="item3"/>
<input type="submit" id="submitForm" value="Submit Form" />
<form>
and you get:
www.mysite.com/mypage.php?item1=1&item2=2&item3=3
if all checkboxes are selected.

change field value when select radio buttons

I want to change the value of hidden input field when radio buttons selected :
<input type="radio" name="r1" value="10" />10
<br/>
<input type="radio" name="r1" value="45" />45
<br/>
<input type="hidden" name="sum" value="" />
for example when user click on one the buttons the value of hidden field change to that value.
Use the onClick property:
<input type="radio" name="r1" value="10" onClick="document.getElementById('hidfield').value=this.value"/>10
<br/>
<input type="radio" name="r1" value="45" onClick="document.getElementById('hidfield').value=this.value"/>
45
<br/>
<input type="hidden" name="sum" value="" id="hidfield" />
You can try for example
<input type="radio" id="radio1r1" name="r1" value="10" />10
<br/>
<input type="radio" id="radio2r1" name="r1" value="45" />45
<br/>
<input type="hidden" name="sum" value="" />
jQuery("input[id^='radio']").click(function() {
jQuery("input[name='sum']").val(jQuery(this).val());
}
So then when user click on each radio we handle it by various id with same start.
Using jQuery it would be:
$(":radio").click(function () {
var inputValue = $this.val();
$(":hidden[name='sum']").val() = inputValue;
$(":hidden[name='sum']").name() = "lalala";
});
I've not double checked that code so it might need a little tweaking.
hook into the onclick event for the radio button "r1". Normally I'd suggest the onchange event but in IE it isn't fired until the user "blurs" the radio button.
If you are using a framework like jQuery, hook in the events in a nice unobtrusive manner... but if you want a quick n dirty solution, just add the events inline.
<input type="radio" name="r1" value="10" onclick="doIt(this);"/>10
<br/>
<input type="radio" name="r1" value="45" onclick="doIt(this);"/>45
<br/>
<input type="hidden" name="sum" value="" />
<script>
function doIt(obj){
//alert('my value is now: ' + obj.value);
obj.form.elements['sum'].value = obj.value;//set hidden field to radio value
}
</script>

Categories

Resources