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";
Related
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
First of all sorry for my English and im not an expert of HTML, JS or PHP.
I appended some radio inputs to a div inside a form.
The append process looks OK, but when i submit the form, i cant get the post data from the appended inputs.
<form method="POST" action="post.php">
<div id="categradio">
<input type='radio' name='catradio' value='opt1' id='cat1'></input><label for='cat1'>OPT1</label>
<input type='radio' name='catradio' value='opt2' id='cat2'></input><label for='cat2'>OPT2</label>
<input type='radio' name='catradio' value='opt3' id='cat3'></input><label for='cat3'>OPT3</label>
</div>
<div id="subcategradio"></div>
<input type="submit" value="Send"></input>
</form>
<script>
function updateSubCats(currcat) {
var data = [{"0":"Analisi","Categoria":"Analisi","1":null,"Sottocategoria":null},{"0":"Creazione","Categoria":"Creazione","1":"Pagina Web","Sottocategoria":"Pagina Web"},{"0":"Creazione","Categoria":"Creazione","1":"Tabella","Sottocategoria":"Tabella"},{"0":"Creazione","Categoria":"Creazione","1":"Applicazione","Sottocategoria":"Applicazione"},{"0":"Creazione","Categoria":"Creazione","1":"Query","Sottocategoria":"Query"},{"0":"Creazione","Categoria":"Creazione","1":"Database","Sottocategoria":"Database"},{"0":"Monitoraggio","Categoria":"Monitoraggio","1":null,"Sottocategoria":null},{"0":"Importazione","Categoria":"Importazione","1":null,"Sottocategoria":null},{"0":"Calcolo","Categoria":"Calcolo","1":null,"Sottocategoria":null}];
$('#subcategradio').empty();
for (var i in data) {
var cat = data[i][0];
var subcat = data[i][1];
if (cat == currcat && subcat != "" && subcat != null) {
$('#subcategradio').append("<input type='radio' name='subcatradio' value='"+subcat+"' id='subcat"+i+"'></input><label for='subcat"+i+"' class='nosel'>" + subcat + "</label>");
}
}
}
$('#categradio').change(function(){
var cat = $('#categradio input[type=radio]:checked').val();
updateSubCats(cat);
});
</script>
and the php file (post.php) to receive the post data:
<?php
$category = $_POST['catradio'];
$subcategory = $_POST['subcatradio'];
echo $category."<br>".$subcategory;
?>
i solved the problem adding an invisible input.
<input name="subcategory" class="invisible" value="" id="empty"/>
when the appended radios selection change, the value of the invisible input change, and when i submit the form i get the value of the invisible input.
thanks to everyone
I've got multiple forms like this on one page:
<form method="post" action="#">
<input type="hidden" name="product_id" value="'.$item['articlenumber'].'" />
<input type="text" name="update_quantity" value="'.$pg->quantity.'" />
<input type="hidden" name="packing" value="'.$item['packing'].'" />
<input type="hidden" name="unit" value="'.$item['unit'].'" />
<input type="submit" name="addtocart" value="Update" />
</form>
And I've got one submit button at the bottom:
<input name='placeorder' type='submit' value='Place order' />
How can I check all forms when I press the submit button? I need to validate that the input that was given is the correct quantity.
UPDATE
I now got all the values from the forms in JavaScript and the validation is correct. Now I want to store the variables into PHP SESSIONS. I saw the answer from Ben and that would work if the values where in PHP, they are now in JavaScript. I need them on other pages so I thought Sessions would be the best thing here (if not, other suggestions are welcome).
I saw this answer and there they say it is not possible on one page. I understand that because PHP is server side and Javascript client side. Is this the only possible way to send Javascript variables to PHP?
Alright, first you should remove the type='submit' on the input. So change it to :
<input name='placeorder' value='Place order' />
Then you just need to add a javascript function to validate.
$(document).ready(function() {
$("input [name='placeorder']").click(function() {
var formOK = true;
$("form input").each(function(index, element) {
var value = $(element).val();
if (value != "OK") {
formOK = false;
}
});
if (formOK) {
submitForms();
} else {
alert("Form Input Inccorect");
}
});
});
function submitForms() {
$("#form1").add("#form2").submit();
}
With regards to your question about storing form data in a session variable Try something along these lines:
session_start();
if (isset($_POST['placeorder'])) {
$_session['ProductID'] = $_POST['product_id'];
$_session['UpdateQuantity'] = $_POST['update_quantity'];
$_session['Packing'] = $_POST['packing'];
$_session['Unit'] = $_POST['unit'];
}
Hope that helps
Both answers helped me a little bit but I needed to combine them so I ended up with a solution like the following. I got the values from the inputs by their unique name like this:
var sizeS25 = parseInt($("input[name='size-s25']").val(), 10) || 0;
var sizeM25 = parseInt($("input[name='size-m25']").val(), 10) || 0;
Then I send the variables to a PHP file:
window.location.href = "phpsessions.php?sizeS25=" + sizeS25 + "&sizeM25=" + sizeM25;
In the PHP file I set the variables as sessions:
$_SESSION['sizeS25'] = $_GET['sizeS25'];
$_SESSION['sizeM25'] = $_GET['sizeM25'];
I'm on the learning mode.
<?php
if (!empty($_POST['fifty']) || !empty($_POST['sixty'])) {
$fifty = (isset($_POST['fifty'])) ? (int)$_POST['fifty'] : 0;
$sixty = (isset($_POST['sixty'])) ? (int)$_POST['sixty'] : 0;
echo $fifty + $sixty;
} else {
echo "No selection selected";
}
?>
<form method="post">
<input type="radio" name="fifty" value="50"/>
<input type="radio" name="sixty" value="60"/>
<input type="submit" name="submit" value="Submit"/>
</form>
This only works when I select both radio buttons. How do I make this work when I just select 1 radio button instead of 2?
And is the way I coded the PHP the good way to write it? I get an idea that I do double work with checking :P
And how do I do it with three radio options? Can you give me a example with a third radio option called seventy with value 70?
My idea is to make it + count the values if 1 and 3 are slected it must to 50+70
if 2 and 3 are selected it must do 60 + 70, etc, etc.
Use ||for OR, && for AND
if(!empty($_POST['fifty']) || !empty($_POST['sixty'])){
$fifty = (isset($_POST['fifty']))? (int)$_POST['fifty'] : 0;
$sixty = (isset($_POST['sixty']))? (int)$_POST['sixty'] : 0;
echo $fifty + $sixty;
} else {
echo "No selection selected";
}
A few things to change.
The <input /> tags.
<input type="radio" name="fifty" value="50" />
<input type="radio" name="sixty" value="60" />
The logic you used (which you have corrected).
if (!empty($_POST['fifty']) || !empty($_POST['sixty']))
Remove unnecessary code:
$submit = $_POST['submit'];
i have 1 php page containing 2 forms and 1 submit button.i want to submit both forms with this single button.My code works perfectly but there is 1 problem that in each form only 1 field submitted successfully. Below is my html and javascript code, plz tell me where i have error
2 html forms
<form name="form">
<input type="text" name="a" value="a">
<input type="text" name="b" value="b">
</form>
<form name="form">
<input type="text" name="c" value="c">
<input type="text" name="d" value="d">
</form>
<input type="submit" name="Submit" id="button" value="Submit" onClick="submitAllDocumentForms()">
Javascript code
<script language="javascript" type="text/javascript">
/* Collect all forms in document to one and post it */
function submitAllDocumentForms() {
var arrDocForms = document.getElementsByTagName('form');
var formCollector = document.createElement("form");
with(formCollector)
{
method = "post";
action = "test.php";
name = "formCollector";
id = "formCollector";
}
for(var ix=0;ix<arrDocForms.length;ix++) {
appendFormVals2Form(arrDocForms[ix], formCollector);
}
document.body.appendChild(formCollector);
formCollector.submit();
}
/* Function: add all elements from ``frmCollectFrom´´ and append them to ``frmCollector´´ before returning ``frmCollector´´*/
function appendFormVals2Form(frmCollectFrom, frmCollector) {
var frm = frmCollectFrom.elements;
for(var ix = 0 ; ix < frm.length ; ix++)
frmCollector.appendChild(frm[ix]);
return frmCollector;
}
</script>
My php code to echo submitted values
<?php
echo $_POST['a'];
echo $_POST['b'];
echo $_POST['c'];
echo $_POST['d'];
?>
The problem is that appendChild() takes the element away from the form, modifying the elements array as well as its length. To avoid this, you can e.g. store the number of elements in a variable and process the array of elements starting from the last element:
var frm = frmCollectFrom.elements;
var nElems = frm.length;
for(var ix = nElems - 1; ix >= 0 ; ix--)
frmCollector.appendChild(frm[ix]);