Javascript doesn't work when textbox name contains square brackets - php

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.

Related

using a variable name inside another variable name

I'm sorry for my English.
I have a dynamic php form connected to mysql DB. In stock array I save the mysql query results. I can access the name of the product[0] and its available quantity [4]. I use the name of the product[0] to set input name and available quantity to fix max parameter value, as it below:
<input type="number" name="<?php echo $stock[$i][0]?>" min="0" max="<?php echo $stock[$i][4]; ?>" value="0" style="width:4em>
I don't kwow how many inputs will be created (and which, because it is dynamic), so I save the name of the input created in another array $_SESSION["INPUTS"] as show:
array_push($_SESSION["inputs"],$stock[$i][0]);
In the next page, I want to $REQUEST the value from the inputs. Now I have the problem, I need to call $REQUEST for the created inputs which names are saved inside $_SESSION["inputs"], I need something as:` $REQUEST["$_SESSION["inputs"]]. I try it different ways without exit.
Any idea? Any alternative?
thanks
I think the best approach is by naming the input name attribute like an array: eg: "name=stock[the product name]". This approach allows you to discard the usage of the $_SESSION["inputs"].
<input type="number" name="stock[<?php echo $stock[$i][0];?>]" min="0" max="<?php echo $stock[$i][4]; ?>" value="0" style="width:4em">
Then to read the values:
$stocks = $_REQUEST['stock'];
foreach($stocks as $productName => $quantity) {
//...
}
This works because the inputs are converted to a php array after being submitted.
You can even get the number of inputs by calling count:
echo count($_REQUEST['stock']);

How can I put a POST inside another POST in PHP

I am trying to take the contents of a form and i want to display them using PHP. The way the form is structured is the following:
There is a list of checkboxes, which when they are clicked, a JavaScript function will create another <input> tag. The JS then sets the name of the new input to <input name="value of checkbox">.
What I need to do is get my PHP to take the value of the <input> I created.
Here is my HTML of the checkboxes.
<input name="product[]" value="value of Check 1" id="id-check-1" type="checkbox" onclick="id-check-1"/><input name="product[]" value="value of Check 2" id="id-check-2" type="checkbox" onclick="id-check-2"/><input name="product[]" value="value of Check 3" id="id-check-3" type="checkbox" onclick="id-check-3"/>
Here is my HTML of the inputs created by the JS.
<input name="value of Check 1" type="text"/><input name="value of Check 2" type="text"/><input name="value of Check 3" type="text"/>
PHP:
$aProduct = $_POST['product];
$product1 = $aProduct[0];
$product2 = $aProduct[1];
$product3 = $aProduct[2];
$input1 = $_POST[$product1];
$input2 = $_POST[$product3];
$input3 = $_POST[$product3];
I tried using this PHP to obtain the value inputted to the crated inputs. This shouldwork, since the name of the inputs = the value of the checkboxes, so in short, this is what I've done:$_POST[$_POST['product']]
Unfortunately, it doesnt work and the variables $input1, $input2 & $input3 dont return any value. So I'd like to know: A) Can i put a _POST within a _POST? and B) What can I do to make my code work?
First of alll the $_POST Variable is one Super Global in PHP i dont think it makes any sense to use $_POST[$_POST...
http://php.net/manual/en/language.variables.superglobals.php
Also i dont think you have to create extra inputs just use $_POST['product'] (array of values which are selected)
try var_dump($_POST['product']) to see whats stored in it
If I understand correctly otherwise guide me in the right direction.
First: You have given the name product[]. Then it should be $_POST['product[]'] which I don't know if that is possible.
Second: If you are writing the value of the checkbox to an input field than why not just check the checkboxes by name. For example:
<input name="check1" value="checkbox 1 value" type="text"/>
<input name="check2" value="checkbox 2 value" type="text"/>
<input name="check3" value="checkbox 3 value" type="text"/>
then in php do:
$check1 = isset($_POST['check1']) ? $_POST['check1'] : "";
This way if the checkbutton is checked you get the value of check1 and otherwise it's empty.
Potentially, you are having issues because you can't have whitespace in the name attribute.
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 (".").
https://www.w3.org/TR/html401/types.html#type-name

Return value from element while showing another

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!]

Disable multiple checkboxes with javascript

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;
}
}
}

Javascript mysql interface?

I am going back though a web-based document numbering system from few weeks ago. To sum it up, the user types in the project,class,base, and dash number (PPP-CCC-BBBB-DDD) then it is added to a mysql database. Now most doc numbers go in order according to revisions. IE: A document 1465-630-0001-000 becomes, after revision, 1465-630-0002-000.
The boss wants the system to automatically fill the input text box for the base number if it detects that the user is entering a revised doc. So if a user types in 1465 into the project field and 630 into the class field the system should autofill the base field with the next available number. In the previous example this would be 0002.
It needs to be able to search the database for the first two fields so that it can find the next available one. Is there anyway to do this using javascript or something? SO was really helpful with my last javascript question pertaining to this system.
heres an bit of my code if it helps:
` ?>
<div id='preview'></div>
<form id='item' action="submit.php?item=1" method="post">
Enter Title:<input type="text" name="title" size="20"><BR>
Choose Project Code:
<SELECT NAME="project">
<OPTION VALUE="">Project...
<?
$query = "SELECT * FROM project ORDER BY project asc";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result))
{
$num = ($row['project']);
$name = ($row['description']);
?>
<OPTION VALUE="<?=$num?>" ><? echo"{$num}" . " | " . "{$name}";?>
<?
}
?>
</SELECT><BR>
Choose Class Code:
<SELECT NAME="class">
<OPTION VALUE="">Class...
<?
$query = "SELECT * FROM class ORDER BY class asc";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result))
{
$num = ($row['class']);
$name = ($row['description']);
?>
<OPTION VALUE="<?=$num?>" ><? echo"{$num}" . " | " . "{$name}";?>
<?
}
?>
</SELECT><BR>
Assigned Base Number:<input type="text" name="base" size="20"><BR>
Enter Dash Number:<input type="text" name="dash" size="20"><BR>
Enter Comments:<input type="text" name="comment" size="40"><BR>
<input type="hidden" name="item" value="1"/> `
Just a simple html/php input form with the project and class code list generated from a database pertaining to each.
Thanks for any help-Thomas
Update:
So, you're going to need to make an AJAX call (see example in my comment below) to some PHP script that will retrieve the base value you want and then returns that to the AJAX request. Once the request gets a response, you can use that data to fill in the value the way I originally said...
On a side note, since the example I gave you is a jQuery AJAX function, you should probably check out how to use jQuery to select elements on the page, instead of using straight JS.
E.g. for getting by ID and replacing value:
$("#base").attr('value', valueFromAjaxCall);
How to change value with JS:
If you use PHP to get the base value you want to fill into the field, then you can fill the value in with:
var baseField = document.getElementsByName("base")[0];
baseField.value = <?=$baseValue?>;
The getElementsByName() call returns an array, which is why you have to index into the field you want. I would suggest giving your <input> an id so that you can use document.getElementById() instead. You would do something like:
<input type="text" id="base" size="20">
and the JS to get the input element would be:
var baseField = document.getElementById("base");
...therefore, no need to index, in case you named any fields with the same name.
**Not sure about the PHP syntax.
An ajax call on focus of the 3rd field firing back to the server the values of the first two fields?
first, you'll probably want to use jQuery since it has great support is easy to use and will feel familiar to someone used to PHP.
so include your jQuery javascript code that you can get from :
http://jquery.com/
then, assume a form that looks like:
{form}
<input type=text id='major' name='major' value=''>
{Or a select, your choice}
<input type=text id='minor' name='minor'>
{or a select again}
<input type=text id='sequence' name='sequence' onFocus='getNextSequence()'>
...
{/form}
in your head, have your javascript:
function getNextSequence(){
var major=$('#major').val();
var minor=$('#minor').val();
if(!major){
alert('Select a major version#');
$('#major').focus();
return(false);
}
if(!minor){
alert('Select a minor version#');
$('#minor').focus();
return(false);
}
$.getJSON('http://url.to.getnextNumber.php',
{major:major,minor:minor},
function(data){
if(!data.error){
$('sequence').val(data.nextSequence);
}else{
alert(data.error);
}
}
});
}
the jQuery getJSON call will make a call back to your URL with two $_POST variables, major and minor. do your query, save the result as $result=array('nextSequence'=>$x,'error'=>'false');
and convert it to JSON with echo json_encode($result);
don't include ANY headers or any other content in the output of that file, and jQuery will pull the correct value and insert it where it's supposed to bed

Categories