html and javascript same name for multiple inputs - how to? - php

I have never done anything like this, and I would like to know how to do it. I need to put 4 inputs into a sub array if it is field out
I know that when i $_POST the form to the server it sends the names of the inputs but how do I get the input to be allowed to have the same name
for example
the sub array i need it to be in is offers
here is what i dont know. How do i get the following inputs
<input name="offers[]['minspend']" value="15.00"/>
<input name="offers[]['minspend']" value="5.00"/>
<input name="offers[]['minspend']" value="19.00"/>
<input name="offers[]['minspend']" value="8.00"/>
<input name="offers[]['minspend']" value="30.00"/>
<input name="offers[]['minspend']" value="7.00"/>
<input name="offers[]['minspend']" value="100.00"/>
<input name="offers[]['minspend']" value="10.00"/>
is this correct or wrong?
thanks

It depends a bit on the back end technology that processes your request (java, php, whatnot), but from an html standpoint multiple elements with the same name will just send their value with the same parameter name. You don't need any special [] syntax.
GET /mypage.html?offer=15.00&offer=5.0&offer=19.0 (etc, could be post too)
Most languages that provide built in support for html requests represent this request as a map, with a key named "offer" and a value that is an array or list containing the values submitted.
For example http://docs.oracle.com/javaee/6/api/javax/servlet/ServletRequest.html#getParameterMap()

This form
<input name="offers['minspend'][]" value="15.00"/>
<input name="offers['minspend'][]" value="5.00"/>
<input name="offers['minspend'][]" value="19.00"/>
<input name="offers['minspend'][]" value="8.00"/>
<input name="offers['minspend'][]" value="30.00"/>
<input name="offers['minspend'][]" value="7.00"/>
<input name="offers['minspend'][]" value="100.00"/>
<input name="offers['minspend'][]" value="10.00"/>
on doing var_dump($_POST) [assuming form method=post] give:
array(1) {
["offers"] = > array(1) {
["\'minspend\'"] = > array(8) {
[0] = > string(5)"15.00"
[1] = > string(4)"5.00"
[2] = > string(5)"19.00"
[3] = > string(4)"8.00"
[4] = > string(5)"30.00"
[5] = > string(4)"7.00"
[6] = > string(6)"100.00"
[7] = > string(5)"10.00"
}
}
}
So, that is how you do it.
you can remove 's around minspend. they aren't needed.
You were almost there. offers[]['minspend'] means that you get:
array(){
array(){
'minspend' => "15.00"
}
array(){
'minspend' => "5.00"
}
.. and so on
}
So what is happening is, when you do something like arr[] = 1, 1 is inserted into array arr.

Well first let me tell you what i understood from the question. You want multiple input fields to have same name and then you want to select them all to perform some action. If this is the case i'd like to present a different approach - why don't you assign same class (cssclass) to all the controls you want to have same name. That way you'll be able to select them all together using document.getElementsByClassName("yourclassName"). which will return you an array of all the elements having class attribute as yourclassName.
Or if you wanna stick to name then you can use document.getElementsByName("elementName"); which returns you an array of elements having name as elementName.
Hope its helpful.

Related

Associative array from form inputs

I'm building a calculator for a mmo guild. At this moment I'm looking for a way to make data more easy to access for calcules.
Basically, I have a form with 5 text fields (just for test, there will be a lot more), and a select list (for choose the proper equation).
Example code:
<input type="text" id="strength" name="strength" value="0">
<input type="text" id="dexterity" name="dexterity" value="0">
<select name="equation" id="equation">
<option name="damage" id="damage">Damage</option>
<option name="defense" id="defense">Defense</option>
</select>
So this form will be procesed through a php file.
<form action="file.php" method="post">
//inputs here
<input type="submit" value="calculate">
</form>
At this moment I'm receiving all data in php file with vars:
$strength = (int)$_POST['strength'];
$dexterity = (int)$_POST['dexterity'];
For start is ok, but when my script is complete there will be more than 20 fields... so I wanna store all data in an array, something like this:
$strength = array(
'fuerza' => 125,
'dexterity ' => 125,
//and more fields...
);
And use this data in various different functions for equations:
function equation1()
{
$damage = $stats['dexterity'] + $stats['strength'];
}
I have read several posts and tutorials about use name value from inputs for create an array somethin like this: name="name[]". But doesn't work for me how I want. This calculator will receive just 1 value for each "stat", and I need have all these values in an array so I can access them from different fuctions in my script.
Please ask me if my question is not clear, and sorry if my english is bad.
EDIT AFTER SOLVE
I let here my code after solve:
.html example:
<input type="text" id="strength" name="stats[strength]" value="0">
<input type="text" id="dexterity" name="stats[dexterity]" value="0">
<select name="operation" id="operation">
<option name="damage" id="damage">Damage</option>
<option name="defense" id="defense">Defense</option>
</select>
.php example:
function critOp($stat)
{
$result = $stat * 0.00725;
return $result;
}
switch($_POST['operation']){
case 'damage' :
$critical = critOp($_POST["stats"]["dexterity"]);
break;
//more case...
You can use brackets in the name field to direct PHP to stick them in an array. If you use [] it will form a numerical array, but you can specify an associative key in the brackets like [dexterity]
<input type="text" id="dexterity" name="strength[dexterity]" value="125">
<input type="text" id="fuerza" name="strength[fuerza]" value="125">
This will result in
$_POST['strength'] = array(
'dexterity' => 125,
'fuerza ' => 125,
);
Bonus points
You can continue to enforce integer values by using array_map:
$_POST['strength'] = array_map('intval', $_POST['strength']);
This will make sure all values are integers.

Can Grails handle POST variables as an array?

If you post the following HTML into a PHP script:
<input type="hidden" name="var[0]" value="A" />
<input type="hidden" name="var[2]" value="C" />
<input type="hidden" name="var[1]" value="B" />
You would end up with a variable called $_POST['var'] (that is essentially a HashMap) whose keys/values look like this:
[0] => "A"
[1] => "B"
[2] => "C"
In PHP, I'm then able to do basic array logic on this, for instance I can see that count($_POST['var']) == 3, and I can iterate over it with a foreach statement.
Is there any way to accomplish this, or something similar, in Grails? I noticed that if I pass in the same sort of HTML to Grails, the result is much less intuitive than it is in PHP. What I want to do is to simply be able to access params.var[0], params.var[1], and so on, and likewise be able to examine things like params.var.length.
But this is not the case. What happens is that params.var is undefined, but instead I then have to access request.getParameter('var[0]'), which is obviously pretty useless.
I realize that I could change my HTML to something like this:
<input type="hidden" name="var" value="A" />
<input type="hidden" name="var" value="B" />
<input type="hidden" name="var" value="C" />
But this is far from ideal, because then I have to guarantee that the HTML inputs are in precisely the right order every time. In PHP, it doesn't really matter what order they appear in since I can specify that directly in the name attribute, and the language is smart enough to take care of it.
Am I missing something? Is there any way to accomplish this in Grails?
Actually it does by default, when binding data. See http://grails.org/doc/latest/guide/theWebLayer.html#dataBinding Binding To Collections And Maps.
The data binder can populate and update Collections and Maps. The following code shows a simple example of populating a List of objects in a domain class:
class Band {
String name
static hasMany = [albums: Album]
List albums
}
class Album { String title Integer numberOfTracks }
def bindingMap = [name: 'Genesis',
'albums[0]': [title: 'Foxtrot', numberOfTracks: 6],
'albums[1]': [title: 'Nursery Cryme', numberOfTracks: 7]]
def band = new Band(bindingMap)
assert band.name == 'Genesis'
assert band.albums.size() == 2
assert band.albums[0].title == 'Foxtrot'
assert band.albums[0].numberOfTracks == 6
// ...
Also if you want to deal with this on your own, you can of course write it yourself. E.g.:
params.collect{it=~/${name}\[(\d+)\]/}.findAll().collectEntries{[it.group(1).toInteger(), params[it.group(0)]]}

associative array with web form

good day all ,, I am new learner and trying to make an associative array for jobs which user inputs the id, title and description but it is not correct ,,can u guide me through this ?
I also want to search for jobs by its title or description and return the job id ,
Thanks alot
<html>
<body>
This form is for storing array of jobs with ID and description for each
<form method = "post" >
input job iD <input id="jobid">
input jobname <input id="jobname">
Write a description <input id="jobdesc">
<input type="submit" value="click to store input" >
</form>
</body>
</html>
<?php
$jobs_array = array();
$jobs_array[] = array ($_POST['jobid'] ,$_POST['jobname'], $_POST['jobdesc']);
?>
You do not need to separate the values like
$_POST['jobid'] ,$_POST['jobname'], $_POST['jobdesc']
and enclose them in an array. Because, they are originally formed that way. When a user submits a post with multiple values, all those values are stored in the super global array $_POST so, instead of separating and then, attaching them inside an array, just depend on this one only, because it has all you need inside.
$all_arrays = $_POST;
Tweaked your markup a bit to
<html>
<body>
<p>This form is for storing array of jobs with ID and description for each </p>
<form action = "<?php echo $_SERVER['PHP_SELF']; ?>" method = "post" >
<p><label for = "jobid">input job iD</label> <input type = "text" name = "jobid" id="jobid"></p>
<p><label for = "jobname">input jobname</label><input type = "text" name = "jobname" id="jobname"></p>
<p><label for = "jobdesc">Write a description</label><input type = "text" name = "jobdesc" id="jobdesc">
<input type="submit" value="click to store input" >
</form>
</body>
</html>
<?php
$jobs_array = array ($_POST['jobid'] ,$_POST['jobname'], $_POST['jobdesc']);
?>
you can access jobid with $jobs_array[0] now, and so on.
An associative array is one where you have a value in an array which can be accessed by a key - that acts as the index.
In your code, as shown below, you are assigning a value to the array without a key thus it isn't associative. Furthermore, you are adding an array to the array making it multidimensional which is inappropriate in this situation.
$jobs_array[] = array ($_POST['jobid'] ,$_POST['jobname'], $_POST['jobdesc']);
The code should look like this:
$jobs_array = array("job_id" => $_POST['jobid'], "job_name" => $_POST['jobname'], "job_description" => $_POST['jobdesc']);
Also, the reason why the $_POST variables are not set is because you're using id rather than name. id refers to the stylesheet whereas name refers to how the data in the field can be accessed.
For the second part of your question, you need to be using a database to store the jobs, and from there, you can run queries whereby you are able to search through the rows by its id, and return an array of results.

Modifying $_POST variable before submitting

I'm making a quiz generator, and I have an HTML form with radio buttons for multiple choice answers. Right now, when I submit my form, the contents of the $_POST variable looks like this when I submit it:
Array ( [a1] => Bob [a2] => Bobby )
(Bob and Bobby are the radio button choices I picked)
I'm generating this form using a PHP function, which returns an array of answers in addition to echoing the HTML form. Is there a way to modify the $_POST variable to have an 'answer' field (for checking my answers), like this:
Array( [a1] => Bob [a2] => Bobby [answers] => Array( [0] => Bob [1] => Bilbo ))
The above was one way I thought of to check answer array with $_POST array.
Edit: More info on what I have so far:
I have a PHP function getTest() that echoes the HTML form, and returns an array with the correct answers.
getTest() generates each question randomly, and as such the correct answers are random.
The main problem is that I have two separate PHP files, questions.php and verify.php.
questions.php echoes the form using getTest(), and has the array of answers.
verify.php only has the contents of $_POST, BUT NOT the array of correct answers.
Is there a better way to check the results of the form submission in general? Thanks!
The best way to do a quiz is to have an answers array and a user input array. Loop through one and compare to the other using the same increment.
You can take all of your post variables and create an array print_r($_POST); Then, loop through this.
$inputArray = //the post data into an array
$answerArray = array('a','b','a');
$numCorrect = 0;
for($a = 0; $a < count($inputArray); $a++)
{
if($inputArray[$a] == $answerArray[$a])
{
$numCorrect++;
}
}
If you want to transmit the answers when submitting the form, you could use inputs of hidden type (like ) which are invisible on the page. However it only takes the user checking the source HTML of the page to see these answers, so it might not be good for your use. Hope this helps
I think what you need to do is a have a look at sessions.
That way on questions.php you can save the answers to a session variable,
Then on verify.php you can read the answers from the session variable and compare them to answered supplied by the $_POST variable
If you really wanted to, you could probably just use a hidden field in your form for submitting an answer array. However, anyone can change your source and modify what the correct answer is.
The best way is to just have an array in your processing script with the same keys (a1, a2), but with the correct answers.
Your processing script would look like this:
$answers = array('a1'=>'Robert', 'a2'=>'Hobo');
foreach($_POST as $key => $value)
{
if (!array_key_exists($key, $answers))
{
continue;
}
if (trim($value) == $answers[$key])
{
// correct
}
else
{
// incorrect
}
}
If you want $_POST to contain an array you can simply use the bracket array notation on the name field of your form.
For example:
<fieldset class="Question1">
<input type="radio" name="answers[]" value="Question1Answer1">Question1Answer1<br>
<input type="radio" name="answers[]" value="Question1Answer2">Question1Answer2<br>
<input type="radio" name="answers[]" value="Question1Answer3">Question1Answer3<br>
</fieldset>
<fieldset class="Question2">
<input type="radio" name="answers[]" value="Question2Answer1">Question2Answer1<br>
<input type="radio" name="answers[]" value="Question2Answer2">Question2Answer2<br>
<input type="radio" name="answers[]" value="Question2Answer3">Question2Answer3<br>
</fieldset>
<fieldset class="Question3">
<input type="radio" name="answers[]" value="Question3Answer1">Question1Answer1<br>
<input type="radio" name="answers[]" value="Question3Answer2">Question1Answer2<br>
<input type="radio" name="answers[]" value="Question3Answer3">Question1Answer3<br>
</fieldset>
(Note that the fieldset tag is optional, I just included it to group things together)
The output in post will be an array $_POST['answers'] that will have one element for each question. So if you selected answer 1 for question 1, answer 2 for question 2, and answer 2 for question 3 you'd have:
$_POST['answers'] = [ 'Question1Answer1', 'Question2Answer2', 'Question3Answer2' ]
Not sure, but looks like you are asking for solution Y, whereas your problem is X (XY Problem)
The XY problem is when you need to do X, and you think you can use Y
to do X, so you ask about how to do Y, when what you really should do
is state what your X problem is. There may be a Z solution that is
even better than Y, but nobody can suggest it if X is never mentioned.
Usually it is not recommended to modify $_POST array, and also not to transmit Answers with the questions to client-side. Instead, the approach should be that because questions.php dont need answers, but verify.php does, so only verify.php shoul have access to answers.
For example, answer-lists are never transported to examination halls along with the question papers on the occasion of exams.
I have taken the liberty to modify your code structure. If you still want to go with your own code, please post it, and then you can get the answers you want.
Try to use this:
question.php:
<form action="verify.php" method="POST">
<fieldset class="Question1"> Complete this: ___<b>bar</b>
<input type="radio" name="answers[]" value="foo">Foo<br>
<input type="radio" name="answers[]" value="too">Too<br>
<input type="radio" name="answers[]" value="cho">Cho<br>
</fieldset>
<fieldset class="Question2"> Complete this: ___<b>overflow</b>
<input type="radio" name="answers[]" value="stack">Stack<br>
<input type="radio" name="answers[]" value="stock">Stock<br>
<input type="radio" name="answers[]" value="stick">Stick<br>
</fieldset>
</form>
answers.php:
//correct answers
$answers = array("foo", "stock");
verify.php:
include("answers.php");
$user_answers = $_POST["answers"];
$user_answers_count = count($user_answers);
$error = "";
for($i=0;$i<$user_answers_count;$i++)
if($user_answers[$i] !== $answers[$i]) //verify
$error[] = "Answer for Question ".($i+1)." is wrong!";
if(empty($error))
//Notify that user has passed the Quiz
else
//Notify that user has NOT passed the Quiz
//print the $error array
Couple of Notes:
I have used answers.php as a different file, but if there is no special requirement, consider merging answers.php & verify.php (put answers.php code on top of verify.php) Even better, you could also merge all these three files into one.
I have assumed that $_POST is sanitized.
Sequence of Questions & answers array is same. i.e. answers[foo] is correct answer for $_POST["answers"][foo]

PHP avoiding a long POST

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

Categories