I have a form of different types of input fields. It looks something like this:
<form action="function.php" method="POST" ...>
<select name="table" ...>
<option> ... </option>
<option> ... </option
</select>
<select name="column" ...>
<option> ... </option>
<option> ... </option
</select>
<input type="text" name="searchword">
<input type="button" name="operator" value="=" id="operator" onclick="change(this.id)">
<input type="submit" ...>
</form>
With my dynamic button, I can switch the operators (=, <, >) with my "change()" function which I need to create my queries. In my function.php file, I'm trying to get all the values of my input fields ...
$table = $_POST["table"];
$column = $_POST["column"];
$operator = $_POST["operator"];
... but unfortunately, it only works for the table and for the column input. I can't store the value of my operator button. I tried to find a solution for my problem but most people wrote that I have to change my button's input type to "submit" to pass the value. However, I do not want the action to be executed directly when this button is pressed, but only when the real "submit" button is pressed.
Edit:
Here is my "change()" function:
function change(operatorId) {
let element = document.getElementById(operatorId);
if (element.value == "=") {
element.value = ">";
} else if (element.value == ">") {
element.value = "<";
} else if (element.value == "<") {
element.value = "=";
}
}
And this is the error message I get when the function.php file opens: "Undefined array key "operator" in ..."
Edit: Solution
Thanks to Professor Abronsius' answer, I was able to resolve my problem. As he suggested, I inserted another hidden input field with the name "operator" and changed my button to "operator-selector". In this way, I just had to add some lines to my function to change the hidden field's value. This is how it looks like now:
<input type="hidden" name="operator" id="operator" value="">
<input type="button" name="select-operator" value="=" id="select-operator" onclick="change(this.id)">
function change(selectorOperatorId) {
let selector = document.getElementById(selectorOperatorId);
if (selector.value == "=") {
selector.value = ">";
document.getElementById("operator").value = selector.value;
} else if (selector.value == ">") {
selector.value = "<";
document.getElementById("operator").value = selector.value;
} else if (selector.value == "<") {
selector.value = "=";
document.getElementById("operator").value = selector.value;
}
}
What you could possibly do would be to keep the button as a regular button but change it's name and then add a hidden input named operator - the value can be assigned by the change function and will appear in the POST array.
Incidentally I had already written the alternative change function below before I saw the edited question. It does have the advantage of being easily extensible if other operators were required/possible.
If the button were changed to a submit the change function would need to have the event passed in as an argument and then call event.preventDefault(); to stop the form from actually being submitted.
const change=function(e){
e.preventDefault();//if the button was a `submit` button this would stop the form being submitted.
const operators=['=','>','<'];
const input=this.parentNode.operator;
let i=Number( this.dataset.i );
let j=i < operators.length-1 ? i+1 : 0;
this.dataset.i=j;
input.value=this.value=operators[j]
}
document.querySelector('input[type="button"][name="op-selector"]').addEventListener('click',change);
<form method='POST'>
<select name='table'>
<option>coffee
<option>dining
</select>
<select name='column'>
<option>doric
<option>corinthian
</select>
<input type='text' name='searchword' />
<input type='hidden' name='operator' />
<!--
the button appears the same but now sets the value of the real `operator`
field.
-->
<input type='button' name='op-selector' data-i=0 value='=' />
<input type='submit' />
</form>
Change input type from button to submit and then you can access button value with $_POST["operator"];
<input type="submit" name="operator" value="=" id="operator" onclick="change(this.id)">
If you're using a style framework and don't want your button type to get affected add another hidden field with text type and change its value programmatically.
value
Defines the value associated with the button’s name when it’s submitted with the form data. This value is passed to the server in params when the form is submitted using this button.
As documented here: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button
Related
I'm trying to create a comparison page/form using a combination of PHP, HTML and jQuery. The ideal effect I like to create as below
<form>
left | right
[text1.l] | [text1.r]
[text2.l] | [text2.r]
submit
</form>
Where [] denotes an input text box. For a particular use case, the user select would select either the left or right textbox for each row and post the form. Essentially I am only interested in the value of the text box selected when I process the form.
I was thinking of perhaps using a radio button as I only allow selection of one box per row, but I am unsure how set this up to retrieve the text box value.
Any helps would be appreciated, cheers.
JSFIDDLE http://jsfiddle.net/Bq8AF/
Form
<form method="post" action="process.php" class="form">
<fieldset id="left">Left
<input type="text" name="foo-left-1" size="50" />
<input type="text" name="foo-left-2" size="50" />
</fieldset>
<fieldset id="right">Right
<input type="text" name="foo-right-1" size="50" />
<input type="text" name="foo-right-2" size="50" />
</fieldset>
<input type="submit" value="Submit">
</form>
JS + jQuery
$("input[type=text], textarea").focus(function(){
// Check for the change from default value
if(this.value == this.defaultValue){
this.select();
}
// get the name of the field, e.g. foo-left-1
//alert(this.name);
var fieldNameSplitted = this.name.split("-");
// recombine + switch "left" to "right" and vice versa
var fieldNameOtherSide = '';
// the ident remains the same (e.g. foo-)
var fieldNameOtherSide = fieldNameSplitted[0] + "-";
// left/right switch (e.g. foo-left, gets foo-right and vv)
if(fieldNameSplitted[1] == 'left') { fieldNameOtherSide += 'right-'; }
if(fieldNameSplitted[1] == 'right') { fieldNameOtherSide += 'left-'; }
// row number (e.g. foo-right-2)
fieldNameOtherSide += fieldNameSplitted[2];
// now we have the name of the field on the other side of the row, right?
//alert(fieldNameOtherSide);
// use that as jQuery selector and disable the element
// because the user has selected the other one
// and when the form is send disabled fields will not be send
// http://www.w3.org/TR/html401/interact/forms.html#disabled
$('input[name=' + fieldNameOtherSide + ']').prop("disabled", true);
});
The user selects the textbox by click.
When "submit" is clicked, a browser will only send the not-disabled fields.
The $_POST array will only contain the values from all not-disabled fields.
When a user enters this:
you would get $_POST['foo-right-1'] = 'car' and $_POST['foo-left-2'] = 'dog'.
I have a list of names and some buttons with product names. When one of the buttons is clicked the information of the list is sent to a PHP script, but I can't hit the submit button to send its value. How is it done?
I boiled my code down to the following:
The sending page:
<html>
<form action="buy.php" method="post">
<select name="name">
<option>John</option>
<option>Henry</option>
<select>
<input id='submit' type='submit' name='Tea' value='Tea'>
<input id='submit' type='submit' name='Coffee' value='Coffee'>
</form>
</html>
The receiving page: buy.php
<?php
$name = $_POST['name'];
$purchase = $_POST['submit'];
//here some SQL database magic happens
?>
Everything except sending the submit button value works flawlessly.
The button names are not submit, so the php $_POST['submit'] value is not set. As in isset($_POST['submit']) evaluates to false.
<html>
<form action="" method="post">
<input type="hidden" name="action" value="submit" />
<select name="name">
<option>John</option>
<option>Henry</option>
<select>
<!--
make sure all html elements that have an ID are unique and name the buttons submit
-->
<input id="tea-submit" type="submit" name="submit" value="Tea">
<input id="coffee-submit" type="submit" name="submit" value="Coffee">
</form>
</html>
<?php
if (isset($_POST['action'])) {
echo '<br />The ' . $_POST['submit'] . ' submit button was pressed<br />';
}
?>
Use this instead:
<input id='tea-submit' type='submit' name = 'submit' value = 'Tea'>
<input id='coffee-submit' type='submit' name = 'submit' value = 'Coffee'>
The initial post mentioned buttons. You can also replace the input tags with buttons.
<button type="submit" name="product" value="Tea">Tea</button>
<button type="submit" name="product" value="Coffee">Coffee</button>
The name and value attributes are required to submit the value when the form is submitted (the id attribute is not necessary in this case). The attribute type=submit specifies that clicking on this button causes the form to be submitted.
When the server is handling the submitted form, $_POST['product'] will contain the value "Tea" or "Coffee" depending on which button was clicked.
If you want you can also require the user to confirm before submitting the form (useful when you are implementing a delete button for example).
<button type="submit" name="product" value="Tea" onclick="return confirm('Are you sure you want tea?');">Tea</button>
<button type="submit" name="product" value="Coffee" onclick="return confirm('Are you sure you want coffee?');">Coffee</button>
To start, using the same ID twice is not a good idea. ID's should be unique, if you need to style elements you should use a class to apply CSS instead.
At last, you defined the name of your submit button as Tea and Coffee, but in your PHP you are using submit as index. your index should have been $_POST['Tea'] for example. that would require you to check for it being set as it only sends one , you can do that with isset().
Buy anyway , user4035 just beat me to it , his code will "fix" this for you.
Like the others said, you probably missunderstood the idea of a unique id. All I have to add is, that I do not like the idea of using "value" as the identifying property here, as it may change over time (i.e. if you want to provide multiple languages).
<input id='submit_tea' type='submit' name = 'submit_tea' value = 'Tea' />
<input id='submit_coffee' type='submit' name = 'submit_coffee' value = 'Coffee' />
and in your php script
if( array_key_exists( 'submit_tea', $_POST ) )
{
// handle tea
}
if( array_key_exists( 'submit_coffee', $_POST ) )
{
// handle coffee
}
Additionally, you can add something like if( 'POST' == $_SERVER[ 'REQUEST_METHOD' ] ) if you want to check if data was acctually posted.
You can maintain your html as it is but use this php code
<?php
$name = $_POST['name'];
$purchase1 = $_POST['Tea'];
$purchase2 =$_POST['Coffee'];
?>
You could use something like this to give your button a value:
<?php
if (isset($_POST['submit'])) {
$aSubmitVal = array_keys($_POST['submit'])[0];
echo 'The button value is: ' . $aSubmitVal;
}
?>
<form action="/" method="post">
<input id="someId" type="submit" name="submit[SomeValue]" value="Button name">
</form>
This will give you the string "SomeValue" as a result
https://i.imgur.com/28gr7Uy.gif
I am done with my script using form submit. What I am doing is a series of questions per page with a Next Button. Now I would like to add a feature to go back to previous question.
How do I code this in one
<FORM name ="Submit1" method ="post" action = <? echo "question.php?num=". $n ; ?> >
<Input type = "Submit" VALUE = "Next" name ="Submit1" /></FORM>
I would like to add the button Previous to the same form without messing the alignment.
I tried making another and just posted the action to the previous page.
But the button is under the Next or above the questions.
<FORM name ="Submit1" method ="post" action="/question.php?num=<? echo $n; ?>" id="formID">
<Input type = "Submit" VALUE = "Next" name ="Submit1" />
<Input type = "Submit" VALUE = "Prev" onclick="document.formID.action = '/question.php?num=<? echo ($n-1); ?>'" name ="Submit2" />
</FORM>
Try with that Javascript
onclick="document.formID.action = '/question.php?num=<? echo ($n-1); ?>'"
This must change the Form action before your form is submitet, to the prev page $n-1 or perhaps it must be $n-2 .. You have to set it correctly
I'm trying to figure out how to make the logic in the following form work. Basically if either of the first two radio buttons is checked, make the hidden input named categories have a value of vegetables. Else, make the hidden input named categories have a value of fruits.
I'm not sure if this should be done with PHP or JavaScript, but if it is done with PHP I think the form would have to be submitted to itself to be pre-processed and then the collected, pre-processed information would be sent to external_form_processor.php. If this is how you do it, what would be the PHP code that I need to use to make it work?
<?php
if($_POST["food"]=="carrots" || $_POST["food"]=="peas") {
$category = "vegetables";
} else {
$category = "fruits";
}
?>
<form name="food_form" method="post" action="external_form_processor.php" >
<fieldset>
<input type="radio" id="carrots" name="food" value="carrots" />
<input type="radio" id="peas" name="food" value="peas" />
<input type="radio" id="orange" name="food" value="orange" />
<input type="radio" id="apple" name="food" value="apple" />
<input type="radio" id="cherry" name="food" value="cherry" />
</fieldset>
<input type="hidden" name="categories" value="<?php $category ?>" />
</form>
If using jQuery would be easier, how could I call the variable as the value of the hidden input if I use the following in the head of the page?
$(function(){
$('input[name=food]').click(function(){
var selected_id = $('input[name=food]:checked').attr('id');
if (selected_id == 'carrots' || selected_id == 'peas') {
var category = "vegetables";
} else {
var category = "fruits";
}
});
});
Any help with this would be greatly appreciated. Thanks!
I think jQuery would work perfect for you, you just need to pass the category value to the input field:
$(function(){
$('input[name=food]').click(function(){
var selected_id = $('input[name=food]:checked').attr('id');
if (selected_id == 'carrots' || selected_id == 'peas') {
var category = "vegetables";
} else {
var category = "fruits";
}
$('input[name=categories]').val(category);
});
});
I would set the category in PHP when the form is submitted.
//validate inputs... always
$food = "";
if(isset($_GET['food'])){
$food = preg_replace("/[^a-zA-Z]+/", "", $_GET['food']);
}
$category = ($food=="peas"||$food=="carrots")?"vegetables":"fruits";
I have an HTML form - with PHP, I am sending the data of the form into a MySQL database. Some of the answers to the questions on the form have checkboxes. Obviously, the user does not have to tick all checkboxes for one question. I also want to make the other questions (including radio groups) optional.
However, if I submit the form with empty boxes, radio-groups etc, I received a long list of 'Undefined index' error messages for each of them.
How can I get around this? Thanks.
I've used this technique from time to time:
<input type="hidden" name="the_checkbox" value="0" />
<input type="checkbox" name="the_checkbox" value="1" />
note: This gets interpreted differently in different server-side languages, so test and adjust if necessary. Thanks to SimonSimCity for the tip.
Unchecked radio or checkbox elements are not submitted as they are not considered as successful. So you have to check if they are sent using the isset or empty function.
if (isset($_POST['checkbox'])) {
// checkbox has been checked
}
An unchecked checkbox doesn't get sent in the POST data.
You should just check if it's empty:
if (empty($_POST['myCheckbox']))
....
else
....
In PHP empty() and isset() don't generate notices.
Here is a simple workaround using javascript:
before the form containing checkboxes is submitted, set the "off" ones to 0 and check them to make sure they submit. this works for checkbox arrays for example.
///// example //////
given a form with id="formId"
<form id="formId" onSubmit="return formSubmit('formId');" method="POST" action="yourAction.php">
<!-- your checkboxes here . for example: -->
<input type="checkbox" name="cb[]" value="1" >R
<input type="checkbox" name="cb[]" value="1" >G
<input type="checkbox" name="cb[]" value="1" >B
</form>
<?php
if($_POST['cb'][$i] == 0) {
// empty
} elseif ($_POST['cb'][$i] == 1) {
// checked
} else {
// ????
}
?>
<script>
function formSubmit(formId){
var theForm = document.getElementById(formId); // get the form
var cb = theForm.getElementsByTagName('input'); // get the inputs
for(var i=0;i<cb.length;i++){
if(cb[i].type=='checkbox' && !cb[i].checked) // if this is an unchecked checkbox
{
cb[i].value = 0; // set the value to "off"
cb[i].checked = true; // make sure it submits
}
}
return true;
}
</script>
To add to fmsf's code, when adding checkboxes I make them an array by having [] in the name
<FORM METHOD=POST ACTION="statistics.jsp?q=1&g=1">
<input type="radio" name="gerais_radio" value="primeiras">Primeiras Consultas por medico<br/>
<input type="radio" name="gerais_radio" value="salas">Consultas por Sala <br/>
<input type="radio" name="gerais_radio" value="assistencia">Pacientes por assistencia<br/>
<input type="checkbox" name="option[]" value="Option1">Option1<br/>
<input type="checkbox" name="option[]" value="Option2">Option2<br/>
<input type="checkbox" name="option[]" value="Option3">Option3<br/>
<input type="submit" value="Ver">
Use this
$myvalue = (isset($_POST['checkbox']) ? $_POST['checkbox'] : 0;
Or substituting whatever your no value is for the 0
We are trouble on detecting which one checked or not.
If you are populating form in a for loop, please use value property as a data holder:
<?php for($i=1;$i<6;$i++):?>
<input type="checkbox" name="active[]" value="<?php echo $i ?>"
<?endfor;?>
If submit form you'll get order numbers of checkboxes that checked (in this case I checked 3rd and 4th checkboxes):
array(1) {
["active"]=>
array(2) {
[0]=>
string(1) "3"
[1]=>
string(1) "4"
}
}
When you are processing form data in loop, let's say in post.php, use following code to detect if related row is selected:
if(in_array($_POST['active'] ,$i))
$answer_result = true;
else
$answer_result = false;
Final code for testing:
<?php if (isset($_POST) && !empty($_POST)):
echo '<pre>';
var_dump($_POST);
echo '</pre>';
endif;
?>
<form action="test.php" method="post">
<?php for($i=1;$i<6;$i++):?>
<input type="checkbox" name="active[]" value="<?php echo $i; ?>" />
<?php endfor;?>
<button type="submit">Submit</button>
</form>
Although many answers were submitted, I had to improvise for my own solution because I used the customized check-boxes. In other words, none of the answers worked for me.
What I wanted to get is an array of check-boxes, with on and off values. The trick was to submit for each check-box on/off value a separator. Lets say that the separator is ";" so the string you get is
;, on, ;, ;, ;
Then, once you get your post, simply split the data into array using the "," as a character for splitting, and then if the array element contains "on", the check-box is on, otherwise, it is off.
For each check-box, change the ID, everything else is the same... and syntax that repeats is:
<div>
<input type="hidden" name="onoffswitch" class="onoffswitch-checkbox" value=";" />
...some other custom code here...
<input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch1" checked>
</div>
EDIT: instead of the ";", you can use some KEY string value, and that way you will know that you did not mess up the order, once the POST is obtained on the server-side... that way you can easily create a Map, Hash, or whatever. PS: keep them both within the same div tag.