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.
Related
I am currently building a dynamic form, using a bit of HTML, PHP and jQuery. This form contains a drop down select field (with the tag name) and two input boxes named tag_text_color and tag_background_color.
When you select a tag in the select field, a bit of jQuery will fill the boxes tag_text_color and tag_background_color with the current database value.
Before that, I have a form which allow the user to add a tag in the database. My problem occurs when I right before adding a tag in the database.
Here is the code for adding a tag :
<form id="form_addtag" method="post" name="form_addtag" action="add_tag.php">
<legend>Add a tag</legend>
<input type="text" name="tag_name" id="tag_name" class="text" size="30" placeholder="Tag Name" />
<input type="text" name="tag_text_color" id="tag_text_color" class="text" size="6" placeholder="#ffffff"/>
<input type="text" name="tag_bg_color" id="tag_bg_color" class="text" size="6" placeholder="#000000" />
<button type="submit" id="button_save_tag">Add</button>
</form>
and the jQuery corresponding function :
$( document ).ready(function() {
$("#form_addtag").submit(function(e) {
e.preventDefault();
var url = "add_tag.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#form_addtag").serialize(), // serializes the form's elements.
});
$('#form_addtag')[0].reset();
$("#form_edittag").load("demo.php #form_edittag")
});
Adding a tag works fine, and it reloads perfectly the form to edit a tag. However if in this block I am selecting the new tag, it is not loaded yet by jQuery
HTML to edit a tag :
<form id="form_edittag" method="post" name="form_edittag" action="edit_tag.php">
<legend>Edit a tag</legend>
<select id="select_edittag">
<?php
$tags = get_tags();
$numberOfTags = sizeof($tags);
var_dump($numberOfTags);
var_dump($tags);
foreach ($tags as $line)
{
echo("<option value='".$line["name"]."''>".$line["name"]."</option>");
}
//print("<option value='". $tags[ $j ]["name"]."'>".$tags[ $j ]["name"]."</option>");
?>
</select>
<input type="text" name="tag_text_color_edit" id="tag_text_color_edit" class="text" size="6" />
<input type="text" name="tag_bg_color_edit" id="tag_bg_color_edit" class="text" size="6" />
<button type="submit" id="button_edit_tag">Edit</button>
<button type="submit" id="button_delete_tag">Delete</button>
</form>
Corresponding jQuery :
$( document ).ready(function() {
$( document ).on( "change", "select#select_edittag", function()
{
var name = $("#select_edittag").val();
var tags = <?php echo json_encode(get_tags()); ?>;
$("#tag_text_color_edit").val(tags[name]["text_color"]);
$("#tag_bg_color_edit").val(tags[name]["background_color"]);
});
});
The function get_tags() will return an array with all the tags in the database.
I was thinking that each time I select a new item in my select "select_edittag" it would run the script, and update the tags variable with the lastest content from the function get_tags(). It does not sadly.
Any idea ? If you want a live demo I can host something like that
No.
PHP is running once, when loading the page. You must repopulate 'tags' via ajax. Check: getJSON
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 an appendchild-function that adds form elements. In IE, everything works fine; the process.php is able to $_POST it. But in firefox, it doesnt send the data.
Here is my code.
<script type="text/javascript">
var i=0;
function addElement()
{
var ni = document.getElementById('org_div1');
var numi = document.getElementById('theValue');
var num = (document.getElementById('theValue').value -1)+ 2;
numi.value = num;
var newDiv = document.createElement('div');
var divIdName = num; newDiv.setAttribute('id',divIdName);
newDiv.innerHTML = '<input type="text" name="work" /><input type="file"
class="fileupload" size="80" name="file' + (num) +'" onclick="addElement()"/> <a
class="removelink" onclick=\'removeElement('+divIdName+')\'>Remove This File</
a>';
// add the newly created element and it's content into the DOM
ni.appendChild(newDiv);
}
function removeElement(divNum)
{
var d = document.getElementById('org_div1');
var olddiv = document.getElementById(divNum);
d.removeChild(olddiv);
}
</script>
<td>
<div class="file_input_wrapper">
<input type="hidden" value="1" id="theValue" />
<div id='org_div1'>
<input type="file" class="fileupload" name="file1" size="80" onclick="addElement()" />
</div>
</td>
Solved the problem...
Basically, I had this..
<div>
<form>
</div>
</form>
And changed to this..
<form>
<div>
</div>
</form>
Seems firefox doesnt like invalid html.
You can use PHP's field name array functionality to get around having to keep track of your field names. Simply name the field like this:
<input type="file" name="files[]" ... />
^^--- array notation
and PHP will handle each file box as a separate member in the $_FILES array after the form's submitted. This frees you up from all the extra overhead of keeping track of how many boxes there are and hidden form fields to store the value.
You may want to reconsider having the file element's onclick be the thing that adds a new file input. What happens if someone clicks on the "browse" button to add a file? They'll get a new file input box, even though they may only have wanted one. If they choose the wrong file or change their minds later and click browse again to change the file selection, they'll get yet another input box.
Consider having a dedicated "add another box" button instead.
Just want to ask where your form tag is located? Before or after table tag? I had similar problem and my form tag was inside table. When I put form tag outside of table everything worked fine.
Site doesn't work anymore.
Here is working example. I used your code. Only two thing I changed is
<input type="text" name="work[]" /> instead of <input type="text" name="work" />
and you was missing one </div> closing div tag
here is code (tested on IE7, IE8, FF and google chrome)
<?php
if (!empty($_POST['btnProsledi'])){
print_r($_POST);
echo "<br />";
print_r($_FILES);
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Untitled</title>
<script type="text/javascript">
var i=0;
function addElement()
{
var ni = document.getElementById('org_div1');
var numi = document.getElementById('theValue');
var num = (document.getElementById('theValue').value -1)+ 2;
numi.value = num;
var newDiv = document.createElement('div');
var divIdName = num; newDiv.setAttribute('id',divIdName);
newDiv.innerHTML = '<input type="text" name="work[]" /><input type="file" class="fileupload" size="80" name="file' + (num) + '" onclick="addElement()"/> <a class="removelink" onclick=\'removeElement(' + divIdName + ')\'>Remove This File</a>';
// add the newly created element and it's content into the DOM
ni.appendChild(newDiv);
}
function removeElement(divNum)
{
var d = document.getElementById('org_div1');
var olddiv = document.getElementById(divNum);
d.removeChild(olddiv);
}
</script>
</head>
<body>
<form method="post" action="" enctype="multipart/form-data">
<table>
<tr>
<td>
<input name="proba" type="text" id="proba" value="" />
</td>
</tr>
<tr>
<td>
<div class="file_input_wrapper">
<input type="hidden" value="1" id="theValue" />
<div id='org_div1'>
<input type="file" class="fileupload" name="file1" size="80" onclick="addElement()" />
</div>
</div>
</td>
</tr>
<tr>
<td>
<input name="btnProsledi" type="submit" id="btnProsledi" value="Submit" />
</td>
</tr>
</table>
</form>
</body>
</html>
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>