Im trying to limit the amount of checkboxes that can be checked, in this case only 3 can be checked. When using plain HTML this works fine. The code can be seen below.
HTML example
<td ><input type=checkbox name=ckb value=2 onclick='chkcontrol()';></td><td>Perl</td>
Javascript Function
<script type="text/javascript">
function chkcontrol(j) {
var total=0;
for(var i=0; i < document.form1.ckb.length; i++){
if(document.form1.ckb[i].checked){
total =total +1;}
if(total > 3){
alert("Please Select only three")
document.form1.ckb[j].checked = false;
return false;
}
}
}
</script>
The problem appears when replacing the fixed HTML values with values from a MYSQL database. All the information appears correctly, and can be posted to another page via a submit button. However, it seems like the 'value' assigned to each record from the database is not making its way too the javascript function.
<td><input name="checkbox[]" type="checkbox" value="<?php echo $rows['TCA_QID'];?>" onclick="chkcontrol();"></td>
I have tried changed the name in the javascript function to match the 'checkbox' name.Any advice would be greatly appreciated
Thanks
In the second version, your input element's name is "checkbox[]", but in your JavaScript function you're looking for an element with a name of ckb. The JavaScript function cannot find your field if you're telling it to look for the wrong name.
You say you've tried changing this. What happened when you tried that? Make sure you're naming the element "ckb", not "ckb[]".
Have you looked at what the checkboxes' values are in the generated HTML for the page? Do they match what you expect?
<script type="text/javascript">
<!--
//initial checkCount of zero
var checkCount=0
//maximum number of allowed checked boxes
var maxChecks=3
function setChecks(obj){
//increment/decrement checkCount
if(obj.checked){
checkCount=checkCount+1
}else{
checkCount=checkCount-1
}
//if they checked a 4th box, uncheck the box, then decrement checkcount and pop alert
if (checkCount>maxChecks){
obj.checked=false
checkCount=checkCount-1
alert('you may only choose up to '+maxChecks+' options')
}
}
//-->
</script>
</head>
<body>
<form>
Option1 <input type="checkbox" id="check1" onclick="setChecks(this)"><br />
Option2 <input type="checkbox" id="check2" onclick="setChecks(this)"><br />
Option3 <input type="checkbox" id="check3" onclick="setChecks(this)"><br />
Option4 <input type="checkbox" id="check4" onclick="setChecks(this)"><br />
Option5 <input type="checkbox" id="check5" onclick="setChecks(this)"><br />
Option6 <input type="checkbox" id="check6" onclick="setChecks(this)"><br />
</form>
</body>
Related
So i have this line of code that will repeat different times in a form.
<input type="checkbox" name="checkbox[]" /> !checked
<input type="checkbox" name="checkbox[]" /> !unchecked
<input type="checkbox" name="checkbox[]" /> !checked
<input type="checkbox" name="checkbox[]" /> !unchecked
The !checked show that the checkbox was checked and the !unchecked shows that the checkbox was not checked.
How can i create a php array to get values of checked and unchecked checkboxes in order like this :
array( 0 => checked, 1 => unchecked, 2 => checked, 3 => unchecked );
Momentarily i can get just the checked value with $_POST["checkbox"] but i cannot get the unchecked value.
First of all you need to put a value to your checkboxes:
<input type="checkbox" name="checkbox[]" value="checkboxNchecked" /> !checked
You can't really distinguish your checkboxes otherwise.
Then: Your checkboxes will either return a value if they are checked or will be ignored when they are unchecked. You will not get a NULL, FALSE or other value. It will simply not be transfered via POST/GET to your php script as if it wasn't in yout HTML code. This covers the topic: Does <input type="checkbox" /> only post data if it's checked?
If you know how many checkboxes are around and what they are called - no problemo señor - but if you don't, you'll need to find a way around. If you tell us what the nature of your checkboxes are, we can help you find a tailored solution.
you can use jquery and ajax. In your submit event get all values from the form and submit it by ajax. you can get unchecked value in jquery like this:
$("input:checkbox:not(:checked)")
or
if ($('#idOfYourCheckBox:checked').length > 0) {
//its checked
}
else {
//not checked
}
This will print only checked fields, because unchecked ones are not sent to server.
You will have to do some javascript and hidden field tricks.
Take a look here
Post the checkboxes that are unchecked
<input type="checkbox" name="checkbox[n1]" /> !checked
<input type="checkbox" name="checkbox[n2]" /> !unchecked
<input type="checkbox" name="checkbox[n3]" /> !checked
<input type="checkbox" name="checkbox[n4]" /> !sdsk
foreach($_POST['checkbox'] as $key => $value){
$checkbox[$key] = 'checked';
}
print_r($checkbox); // your new array
Solved:
Declaration of form...
<form id="form1" name="form1" method="post" action="xx.php" onSubmit="set_hidden_value()">
<input name="arrayofchecks" type="hidden" value="toset" />
...
OnSubmit:
function set_hidden_value()
{
var checkstring = "";
for (var i=0; i < $('#checkbox').length; i++)
{
if ($('#checkbox')[i].checked)
{
checkstring = checkstring + "1";
}
else
{
checkstring = checkstring + "0";
}
}
$('#arrayofchecks').val(checkstring);
And the result is a string with values checked and unchecked (1 and 0)...
In my case, i use ajax for intercept submit and do set_hidden_value here...
If you are using a server side language like PHP, there is an easier method than using hidden fields to supply default or writing javascript (both may fail if the user's device/browser doesn't support that method).
<input type="checkbox" value="choice1" name="checkbox[]" />
<input type="checkbox" value="choice2" name="checkbox[]" />
<input type="checkbox" value="choice3" name="checkbox[]" />
This method doesn't return unchecked items, but it specifically identifies which items were checked. Otherwise, if the checkboxes all have the same value, all you get is one, two or 3 values repeated with no idea which item was checked. However, assuming choice2 was checked with the above method, it's pretty easy then to figure out that item 1 and 3 therefore were not checked.
Please check below code.
$("button").click(function () {
var i=0;
var cbox=[];
$("input[name='cbox']").each(function () {
if($(this).is(':checked')) {
cbox[i++] = $(this).val();
}else{
cbox[i++] = "unchecked";
}
});
console.log(cbox);
i = 0;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" value="checked" name="cbox">
<input type="checkbox" value="checked" name="cbox">
<input type="checkbox" value="checked" name="cbox">
<input type="checkbox" value="checked" name="cbox">
<button>Click</button>
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Combine $_GET variables before Submit
I am not really sure if this is possible but here is the problem I cant figure out.
I need a way to have two boxes with a price min and max and a button that send the user to a link like this. where A is min price and B is max price.
End result Link.
domain/index.php?a=price_range_A_B
I can not use a from but i can use Input fields. Any ideas?
You will need to do this with javascript. In the "Submit" button/link/whatever click action, fetch the values of the fields and construct the url. Then either send the browser there, or do an ajax request, depending on your needs.
eg.
<script>
function doSubmit() {
var fieldA = document.getElementById('fieldA'),
fieldB = document.getElementById('fieldB'),
valA = fieldA.value,
valB = fieldB.value,
url = "/index.php?a=price_range_" + valA + "_" + valB;
window.location = url;
}
</script>
<input id="fieldA" />
<input id="fieldB" />
<input type="button" onclick="doSubmit();" />
use this function onclick of button
function value_change(){
var a=document.getElementById('box1').value();
var b=document.getElementById('box2').value();
document.getElementById('linkdiv').innerHTML()="domain/index.php?a=price_range_"+A+"_"+B;
}
where box1 and box2 are ids of max and min price respectively and linkdiv is id od di that shows the link
<input id="one" type="text" />
<input id="two" type="text" />
<input id="go" type="button" value="button"/>
$("#go").click(function(){
window.location = "http://google.com/a=price_range_" + $("#one").val() + '_' + $("#two").val();
});
http://jsfiddle.net/kTUu5/
Try this code,
HTML
<div>
Max: <input type="textbox" id="max" name="max" value="" />
<br />
Min: <input type="textbox" id="min" name="min" value="" />
<br />
<input type="button" name="btn" value="Submit" onclick="sendData()"/>
</div>
Javascript
function sendData(){
var max = document.getElementById('max').value;
var min = document.getElementById('min').value;
if(!max || !min){
alert('Enter max and min value');
return false;
}
window.location = "http://domain/index.php?a=price_range_"+min+"_"+max;
}
Demo: http://jsfiddle.net/muthkum/FhY5a/
Yes. You can do it if you can use any client side scripting Like javascript or 'Jquery'. You have to bind a click event fubnction on that Submit button. So once you click on that button it will call a function which take the value of those inputbox and prepared a url and send you to that location.
Example:
<input type="text" name="minPrice" id="min" value="" />
<input type="text" name="maxPrice" id="max" value="" />
<button type="button" name="Submit" onClick="doSubmit()">Submit</button>
Now Your doSubmit() function.
function doSubmit(){
var minPrice=document.getElementById('min').value;
var maxPrice=document.getElementById('max').value;
var location='domain/index.php?a=price_range_'+minPrice+'_'+maxprice+'';
window.location=location;
}
Now on the index page you can easily explode $_REQUEST['a'] variable like this way
$var=$_REQUEST['a'];
$explodedVar=explode('_',$var);
//print_r($explodedVar);
$minPrice=$explodedVar[2];
$maxPrice=$explodedvar[3];
I'm trying to learn jQuery and have a question which may be pretty simple to someone familiar with it already.
Application:
Using PHP with jQuery and Bootstrap Toggle Buttons (http://www.larentis.eu/bootstrap_toggle_buttons/) to create a dynamic link address depending on which toggle buttons the user has turned "on".
Right now i'm using form to POST the toggle button states which once the page reloads it then pulls those POST variables and attaches them to the link.
What I would like to do is to have jQuery automatically change the link on the page when the user toggles the button instead of having to use form post.
What I would like to be able to do is in layman's terms explanation each time the toggle button is toggled:
$link = "http://www.mydomain.com/students.php?view="
if jQuery toggle-button-1 = on then add "name"
if jQuery toggle-button-2 = on then add "id"
if jQuery toggle-button-3 = on then add "address"
// If toggle-button-1 and toggle-button-2 were on and toggle-button-3 was off
// then $views would equal
$views = "name,id"
// On the webpage it would then display
http://www.mydomain.com/students.php?view=name,id
// If the person toggled toggle-button-1 to off, the link would display:
http://www.mydomain.com/students.php?view=id
I hope i've explained this so you can understand it...it's really simple what i'm trying to do and I know how to do this in PHP but i feel like i've been searching around online for something that should be simple and I just can't seem to wrap my head around it.
If anybody could please help me out or point me in the right direction I would greatly appreciate it!
Thanks!!
Here is my example on jsFiddle
HMTL
<input type="checkbox" name="name" value="name" id="name" /> name<br />
<input type="checkbox" name="id" value="id" id="id" /> id<br />
<input type="checkbox" name="address" value="address" id="address" /> address<br />
Link: <input type="text" name="url" value="" id="url" />
JavaScript
$(function() {
var link = "http://jsfiddle.net/mouse0270/chnyy/"
$('input[type=checkbox]').change(function () {
var viewItems = "";
$('input[type=checkbox]:checked').each(function () {
viewItems += ','+$(this).val();
});
$('#url').val(link+'?view='+viewItems.substring(1));
});
});
http://jsfiddle.net/CvsbD/
HTML
<input type="checkbox" class="items" id="one" data-view="name" />
<input type="checkbox" class="items" id="two" data-view="id" />
<input type="checkbox" class="items" id="three" data-view="address" />
<input type="text" id="output" />
JS
$("body").on('change', '.items', function(){
// filter down to items that are checked
var items = $('.items').filter(function(){
return this.checked;
});
// map data values to an array
items = items.map(function (){
return $(this).data('view');
}).get();
// join the array with a comma separator
$("#output").val(items.join(','));
});
Do note that binding a delegate to the document body is not generally the best way to go. You'll want to use a more direct ancestor of your checkboxes, or you can bind the change event to the checkboxes themselves.
This can be further simplified (forgot about :checked) like so:
$("body").on('change', '.items', function(){
// filter down to items that are checked, and get their data-view value.
var items = $('.items:checked').map(function(){
return $(this).data('view');
}).get();
// join the array with a comma separator
$("#output").val(items.join(','));
});
I have number of check boxes that gets generated dynamically. So i do not know how many check boxes gets generated each time. I need to have some JavaScript ways to count the total numbers of check boxes in a form.
<input type="checkbox" value="username1" name="check[0]" id="1" /><br/>
<input type="checkbox" value="userusername2" name="check[1]" id="1" /><br/>
<input type="checkbox" value="userusername3" name="check[2]" id="1" /><br/>
I can not change the name of the check boxes as i need to send the values to serverside PHP script as an array.
Since all other answers are jquery based, I'll offer a pure javascript solution. Assuming the following form:
<form id="myform">
<input type="checkbox" value="username1" name="check[0]" /><br/>
<input type="checkbox" value="userusername2" name="check[1]" /><br/>
<input type="checkbox" value="userusername3" name="check[2]" /><br/>
</form>
You could compute the number of checkbox elements with the following logic:
<script type="text/javascript">
var myform = document.getElementById('myform');
var inputTags = myform.getElementsByTagName('input');
var checkboxCount = 0;
for (var i=0, length = inputTags.length; i<length; i++) {
if (inputTags[i].type == 'checkbox') {
checkboxCount++;
}
}
alert(checkboxCount);
</script>
BTW: As others have noted, the id attribute in any HTML tag should be unique within the document. I've omitted your id="1" attributes in my sample HTML above.
Update:
If you simply want to count all checkbox elements on the entire page without using a containing form element, this should work:
<script type="text/javascript">
var inputTags = document.getElementsByTagName('input');
var checkboxCount = 0;
for (var i=0, length = inputTags.length; i<length; i++) {
if (inputTags[i].type == 'checkbox') {
checkboxCount++;
}
}
alert(checkboxCount);
</script>
In Plain JavaScript:
var myForm = document.forms[nameOrIndex];
var inputs = myForm.getElementsByTagName('input');
var checkboxes = [];
for(var i=0;i<inputs.length;i++){
if(inputs[i].getAttribute('type').toLowerCase() == 'checkbox'){
checkboxes.push(inputs[i]);
}
}
alert(checkboxes.length);
I would go with:
alert(document.querySelectorAll("input[type=checkbox]").length);
If you wanted a particular form you would need to select the form and use that as a base for your call to querySelectorAll instead of document or change the selector to include the form.
<form id="aForm">
<input type="checkbox" value="userusername2" name="check[1]" id="1" /><br/>
<input type="checkbox" value="userusername3" name="check[2]" id="1" /><br/>
</form>
<form id="bForm">
<input type="checkbox" value="username1" name="check[0]" id="1" /><br/>
<input type="checkbox" value="userusername2" name="check[1]" id="1" /><br/>
<input type="checkbox" value="userusername3" name="check[2]" id="1" /><br/>
</form>
Then use:
alert(document.querySelectorAll("#aForm > input[type=checkbox]").length); //shows 2
alert(document.querySelectorAll("#bForm > input[type=checkbox]").length); //shows 3
Note: The Selectors API is only available in newer browsers starting with: Internet Explorer 8, Firefox 3.5, Safari 3.1, Chrome 1, and Opera 10.
alert( $("form input[type='checkbox']").length );
Will give you all the checkboxes in a form, using jQuery.
As you tagged your question with php and you seem to use some sort of numbering already for the form fields, you can also just echo that php counter to a javascript variable:
<?php
//
?>
<script language="javascript" type="text/javascript">
var checkbox_counter = <?php echo $your_counter_in_php; ?>
</script>
<?php
//
?>
By the way, in html you can only have one id on a page and it can´t start with a number.
you could use jquery
var len = $('input:checkbox').length;
alert(len);
WORKING DEMO
if you have jQuery you could do something like
alert ($(':checkbox').length ());
If not then you'll have to document.getElementsByTagName ('input'), iterate over the collection you get back and increment a counter every time you encounter one with its type attribute set to checkbox.
I have a checkbox group in my html form.The check box group contains array.
My question is how validate the checkbox array using jquery and get the array value in php
The code given below
<input type="checkbox" name="go[]" value="1" /><label>Married</label><br>
<input type="checkbox" name="go[]" value="2" /><label>Widowed</label><br>
<input type="checkbox" name="go[]" value="3" /><label>Single</label><br>
<input type="checkbox" name="go[]" value="4"/><label>Minor</label>
Thanks in advance.
I think you're trying to use the jQuery Validation plugin to make sure that at least one checkbox from your group is checked.
The Validation plugin doesn't like input names with brackets in them. Try this in your form's validate method:
rules: {
'go[]': { //since it has brackets, the name must be in quotes to work
required: true,
minlength: 1
}
If you mean how to validate check boxes because they contain [], here is one solution using ids instead:
<script type="text/javascript">
function validate()
{
var proceed = true;
for(var i = 1; i <= 4; i++)
{
if (!$("#" + i).is(':checked'))
{
proceed = false;
break;
}
}
if (proceed == true)
{
return true;
}
else
{
alert('All Fields Are Required !!');
return false;
}
}
</script>
And the html form might look like this:
<form action="frm" method="post" onsubmit="return validate();">
<input type="checkbox" id="1" name="go[]" value="1" /><label>Married</label><br>
<input type="checkbox" id="2" name="go[]" value="2" /><label>Widowed</label><br>
<input type="checkbox" id="3" name="go[]" value="3" /><label>Single</label><br>
<input type="checkbox" id="4" name="go[]" value="4"/><label>Minor</label>
<br />
<input type="submit">
</form>
For PHP:
// get checkboxes array
$chk_array = $_POST['go'];
Now you can manipulate $chk_array array in any way you want:
Note:
$chk_array[0] // contains your 1st checkbox value
$chk_array[1] // contains your 2nd checkbox value
$chk_array[2] // contains your 3rd checkbox value
$chk_array[3] // contains your 4th checkbox value
In php, arrays start from 0 index.
Thanks