I've got a problem with my JS function. I'll explain that to you with my code and a Prt Sc.
Code = http://jsfiddle.net/dKeRf/
This is a Php function and JS function.
Screen = http://img824.imageshack.us/i/antoe.png/
If one of the 2 checkbox over the table is checked, all the checkbox in the two table must be disabled. For the moment It works for the first checkbox, but not for the second, and I ask you why ? :)
I use '10' in my 'For' jut for a test, I'll change that latter by the number of row of the table.
Thanks for your help and have a good day !
Add a class to all of the checkboxes:
<input class="the_checkbox" id='{unique_id}' name='module[]' type='checkbox' value='{unqiue_value}'>
<input class="the_checkbox" id='{unique_id}' name='module[]' type='checkbox' value='{unqiue_value}'>
<input class="the_checkbox" id='{unique_id}' name='module[]' type='checkbox' value='{unqiue_value}'>
<input class="the_checkbox" id='{unique_id}' name='module[]' type='checkbox' value='{unqiue_value}'>
Then use jquery to update all of the checkboxes at once:
<script>
$(document).ready(function(){
$(".selectAll").click(function() {
if($(".selectAll").attr("checked")) {
$(".the_checkbox:checkbox").attr("disabled", true);
} else {
$(".the_checkbox:checkbox").removeAttr("disabled");
}
});
});
</script>
UPDATE: Changes the answer to use the .class name for updating the checkboxes instead of the ID so that the ID can remain unique and conform to HTML standards.
IDs are not allowed to start with a number, they must start with a letter. So document.getElementById(1234) will fail (I think IE might not say anything and allow it, but FF doesn't work). You should be ok with just putting a letter in front of the number and change the getElementById to document.getElementById('cb'+id2);.
Also, just a side note, if you are passing in this to a function onClick, that parameter is a reference to the element that was clicked. So there is no need to get box.id and then do document.getElementById(checkId). technically document.getElementById(checkId) is === box so you could just say box.checked.
http://www.w3.org/TR/html4/types.html#h-6.2. This is the spec that talks about ID attribute naming requirements:
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
Edit:
Even better than using document.getElementById() to select each checkbox, would be to use document.getElementById() on a parent element that the checkboxes you want to disable share (such as the table they are in) and then use document.getElementsByTagName('input') to get a collection of all the checkboxes and loop/disable them with that. So the JS disable code would look like:
Some table:
<input type='checkbox' onClick='checkCBs(this,"someTable1");'>
<table id='someTable1'>
<tr>
<td>This is checkbox 1:</td>
<td><input type='checkbox' name='group1' value='checkbox1'></td>
</tr>
<tr>
<td>This is checkbox 2:</td>
<td><input type='checkbox' name='group1' value='checkbox2'></td>
</tr>
</table>
The code:
function checkCBs(box, parent){
var parent = document.getElementById(parent),
CBs = parent.getElementsByTagName('input'),
i;
//loop through all input elements
for(i=0;i<CBs.length;i++){
//make sure the input is a checkbox
if(CBs[i].type && CBs[i].type=='checkbox'){
//set disabled on this checkbox to opposite
//of whether box is checked.
CBs[i].disabled = !box.checked;
}
}
}
Related
This question already has answers here:
POST unchecked HTML checkboxes
(44 answers)
Closed 1 year ago.
i have this kind of table where I have to store if checkbox is ticked or not because I use them like boolean
name
isEmployed
isSoloParent
john
1
0
I have to make the form dynamic, therefore people can add many rows as they want to fill up many at a single time.
There's no problem doing it for text inputs which can be easily done with <input type="text" name="name[]"> and some standard PHP $name=$_POST['name']; however I can't seem to apply the same concept to checkboxes. it doesnt receive unchecked values (NULL in sql) nor get read by php ISSET.
In php a checkbox is present (and contains the value) in the $_REQUEST (or $_GET or $_POST) if it is checked. Otherwise it is not present. So to get whether your checkbox is checked or not you can use the following:
$is_checked = isset($_POST["checkbox_name"]);
To print the checkbox value use the checked html attribute. If it is given, the checkbox will be ticked.
print(
"<input ".
"type='checkbox' ".
"name='checkbox_name' ".
(isset($_POST["checkbox_name"]) ? "checked='checked' " : "").
" />"
);
To work with a dynamic number of elements I use arrays in the $_POST (or $_REQUEST). You can do this by adding [ and ] to the end of the name attributes of your inputs (e.g. like in https://www.php.net/manual/reserved.variables.post.php#87650). An alternative is to use suffixes or prefixes (e.g. checkbox_name_1) but in my opinion this is just a little bit more work to do.
To add new inputs your javascript may look like the following snippet. The name is always the same, just a [<index>] is appended to tell php to handle this as an array. The <index> is the numeric index to use. This is important, otherwise you cannot use isset($_POST[...][$index]) because dynamic indices will "fill up" your checkbox values.
$("#add").on("click", function(){
let i = $("#table tr").length;
$("#table").append(
"<tr>" +
"<td>Name <input type='text' name='name[" + i + "]' /></td>" +
"<td>Is solo parent <input type='checkbox' name='is_solo_parent[" + i + "]' /></td>" +
"<td>Is employeed <input type='checkbox' name='is_employeed[" + i + "]' /></td>" +
"</tr>"
);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="add">Add</button>
<table id="table">
</table>
In php then you can iterate over the requested variables and check if they exist:
foreach($_POST["name"] as $i => $name){
// the "name" exists, if no name is given, no entry in the database is wanted
$is_solo_parent = isset($_POST["is_solo_parent"][$i]); // true or false
$employeed = isset($_POST["employeed"][$i]); // true or false
$database->insert($name, $is_solo_parent, $employeed);
}
$database->insert() is of course a function that fills the data into your database. Make sure to escape user input to prevent script injection and best use prepared statements to prevent sql injection.
i'm trying to find a way to erase the text screen from my calculator when you press the +/- button so it acts more like a real calculator.
i'm pretty new to php (a week or two) so i'm still learning but i cant figure this out.
the php file returns html code where in i have a <input type='text' named result value='$value'>
(calculator screen).
and a series of submit buttons with a name and value of 1,2,3,+,...
when i press a button a char gets added to the string in result.
when i press on the '=' button it reads the string with eval();
and calculates it.
iv'e tried with a function but i cant figure it out some ideas or tips would be very much welcome.
$value = '';
if(isset($_GET['result']))
$value.=$_GET['result'];
if(isset($_GET['1']))
$value .='1';
if(isset($_GET['2']))
$value .='2';
//and so on ...
if(isset($_GET['+']))
$value .='+';
if(isset($_GET['-']))
$value .='-';
if(isset($_GET['='])){
eval('$result = '.$value.';');
$value = $result;}
return "<form action='index.php' method='get'>
<br><input type='text' name='result' value='$value'><br>
<input type='submit' name='1' value='1'>
<input type='submit' name='2' value='2'>
//and so on ...
(the rest of the html code is loaded somewhere else)
This PHP code below will execute JavaScript code to clean the input field,
echo"<script>document.getElementsByName('result')[0].value = '';</script>
This should resolve your question but i have to tell you that PHP isn't suitable choice to make a web calculator, You need to use JavaScript to make a real calculator without refreshing the page.
Please copy this code below to an HTML file and try it so you can get an idea how it works.
First Number
<input type="text" id="firstNumber" value="6" /><br>
Second Number
<input type="text" id="secondNumber" value="5" /><br>
Result
<input type="text" id="result" /><br>
<button type="button" onclick="Calculate();">Calculate</button>
<script>
function Calculate(){
let firstNumber;
let secondNumber;
firstNumber = document.getElementById("firstNumber").value;
secondNumber = document.getElementById("secondNumber").value;
document.getElementById("result").value = Number(firstNumber) + Number(secondNumber);
// "Number" is to tell javascript its a number not a string/text,
// without "Number" it will concat both numbers
}
</script>
You should use brackets for your conditions, especially if you nest them:
if(isset($_GET['result'])) {
$value .= $_GET['result'];
}
And your indentation makes it look like Python, someone reading it would mistake it for a condition nested in another condition and believe that your if(isset($_GET['2'])) is true only if if(isset($_GET['1'])) is also true.
A switch is a better solution here (and even better for the operators since you probably only have four of them), but in any case, you should assign each term of your operation in a single variable.
Hi lets say I'm showing a numeric value in an element (not sure what element to use), what i want to achieve is once the numeric value is clicked (Thinking of onclick="this.form.submit();" or submit button) it will submit different designated value from the numeric value let us say. Apple then my sql query would retrieve apple and use it. NOTE: I have multiple numeric values and multiple designated values for each numeric value as an example it looks like this:
(numeric value) = (designated value)
15123 = apple
24151 = orange
39134 = peach
Here so far is what i have.
<input type='submit' name='searchthem' placeholder='<?php echo $numeric_value; ?>'
value='apple'>
** NOTE i have multiple numeric values with different designated value
And this is the SQL in the same page:
SELECT * from tbl_fruits where fruit_name='".$_POST['searchthem']."' ;
Would appreciate some help and ideas, If there is confusion please comment so i may further clarify.
Use select element and just submit the form so that it can process the values. if you wish to use AJAX, use some javascript and output the result in the browser.
If I understand your problem correctly you should add an array for the definition terms and do it like this:
<input type="hidden" name="searchterm" value="<?php echo $numeric_value; ?>" />
<input type='submit' name='send' value="<?php echo $names[$numeric_value]; ?>" />
Then in PHP switch through the values:
switch($_POST['searchterm']){
case(15123) $term = 'apple';break;
case(24151) $term = 'ornage';break;
case(39134) $term = 'peach';break;
}
This will secure your SQL query, too. [Beware: Never use unfiltered input (i.e. $_POST in your example) from the browser in SQL queries!]
This is more of a technique question rather than maybe code. I am having a php form with many fields (items to select). Naturally some of the items might be selected and some not. How do I know which ones are selected when i post the data from page 1 to page 2? I thought of testing each one if empty or not, but there are just too many fields and it doesn't feel at all efficient to use or code.
Thanks,
UPDATE EDIT:
I've tried the following and maybe it will get me somewhere before I carry on testing the repliers solutions...
<html>
<body>
<form name="test" id="name" action="testprocess.php" method="POST">
<input type="text" name="choices[shirt]">
<input type="text" name="choices[pants]">
<input type="text" name="choices[tie]">
<input type="text" name="choices[socks]">
<input type="submit" value="submit data" />
</form>
</body>
</html>
and then second page:
<?php
$names = $_POST['choices'];
echo "Names are: <br>";
print_r($names);
?>
This gives out the following:
Names are: Array ( [shirt] => sdjalskdjlk [pants] => lkjlkjlk [tie]
=> jlk [socks] => lkjlkjl )
Now what I am going to try to do is iterate over the array, and since the values in my case are numbers, I will just check which of the fields are > 0 given the default is 0. I hope this works...if not then I will let you know :)
I think what you're looking for is this:
<form action="submit.php" method="POST">
<input type="checkbox" name="checkboxes[]" value="this" /> This
<input type="checkbox" name="checkboxes[]" value="might" /> might
<input type="checkbox" name="checkboxes[]" value="work" /> work
<input type="submit" />
</form>
And then in submit.php, you simply write:
<?php
foreach($_POST['checkboxes'] as $value) {
echo "{$value} was checked!";
}
?>
The square brackets in the name of the checkbox elements tell PHP to put all elements with this name into the same array, in this case $_POST['checkboxes'], though you could call the checkboxes anything you like, of course.
You should post your code so we would better understand what you want to do.
But from what I understood you are making a form with check boxes. If you want to see if the check boxes are selected, you can go like this:
if(!$_POST['checkbox1'] && !$_POST['checkbox2'] && !$_POST['checkbox3'])
This looks if all the three check boxes are empty.
Just an idea:
Create a hidden input field within your form with no value. Whenever any of the forms fields is filled/selected, you add the name attribute of that field in this hidden field (Field names are saved with a comma separator).
On doing a POST, you can read this variable and only those fields present in this have been selected/filled in the form.
Hope this helps.
Try this.....
<?php
function checkvalue($val) {
if($val != "") return true;
else return false;
}
if(isset($_POST['submit'])) {
$values = array_filter(($_POST), "checkvalue");
$set_values = array_keys($values);
}
?>
In this manner you can get all the values that has been set in an array..
I'm not exactly sure to understand your intention. I assume that you have multiple form fields you'd like to part into different Web pages (e.g. a typical survey form).
If this is the case use sessions to store the different data of your forms until the "final submit button" (e.g. on the last page) has been pressed.
How do I know which ones are selected when i post the data from page 1 to page 2?
is a different question from how to avoid a large POST to PHP.
Assuming this is a table of data...
Just update everything regardless (if you've got the primary / unique keys set correctly)
Use Ajax to update individual rows as they are changed at the front end
Use Javascript to set a flag within each row when the data in that row is modified
Or store a representation of the existing data for each row as a hidden field for the row, on submission e.g.
print "<form....><table>\n";
foreach ($row as $id=>$r) {
print "<tr><td><input type='hidden' name='prev[$id]' value='"
. md5(serialize($r)) . "'>...
}
...at the receiving end...
foreach ($_POST['prev'] as $id=>$prev) {
$sent_back=array( /* the field values in the row */ );
if (md5(serialize($sent_back)) != $prev) {
// data has changed
update_record($id, $sent_back);
}
}
I've got this script for calculating square area, which works perfect:
<script language="javascript" type="text/javascript">
function startCalc(){
interval = setInterval("calc()",1);
}
function calc(){
one = document.autoSumForm.firstBox.value;
two = document.autoSumForm.secondBox.value;
document.autoSumForm.Area.value = (one * 1) * (two * 1);
}
function stopCalc(){
clearInterval(interval);
}
</script>
<form name="autoSumForm">
<input size="3" type=text name="firstBox" value="" onFocus="startCalc();" onBlur="stopCalc();">
<input size="3" type=text name="secondBox" value="" onFocus="startCalc();" onBlur="stopCalc();">
<input size="4" type=text name="Area" readonly="true">
</form>
But my problem is that I need the name of the third box to be Area[<?php echo $area['area_id']; ?>]
But I can't get the javascript to work, when I use brackets in the name.
Note that you should not add the brackets if you don't need them! It makes it unnecessary complex.
In your posted code there is no indication that you need those brackets. You normally add them if you have several input fields with the same name and you want PHP to create an array. For more information please refer to Variables From External Sources.
In case you need them, you have to use bracket notation to access the field:
document.autoSumForm['Area[<?php echo $area["area_id"]; ?>]'].value = (one * 1) * (two * 1);
Also I would suggest to not pass a value inside the brackets in the name of the field. This would simplify your code to:
<input size="4" type=text name="Area[]" readonly="true">
and:
document.autoSumForm['Area[]'].value = (one * 1) * (two * 1);
PHP will then create an array with continuous numerical keys starting at 0.
Add id to textarea
<input size="4" type=text name="Area" id="someid" readonly="true">
Put value by id
document.getElementById('someid').value = (one * 1) * (two * 1);
While Felix's answer will work in most (all?) browsers, it should be noted that HTML names and IDs are supposed to be valid identifiers, which cannot contain square brackets. The correct solution is to not use square brackets in your names and IDs.
EDIT: I stand corrected. In HTML 4, The 'id' attribute is type ID, but the 'name' attribute for form elements is type CDATA, so can contain practically anything. See http://www.w3.org/TR/html4/index/attributes.html
I was probably thinking of meta 'name', which is type NAME.
I would add an 'id' attribute to the third box (third input) and give the id a value without square brackets.
Use the 'id' attribute to select the DOM element in your javascript code. And let the 'name' attribute keeps its square brackets.