I have a form with a get method that is used for searching items (vehicles) from the database. The form has multiple checkbox sets. Like user can filter the search results by selecting multiple makes from the makes checkbox list. Similarly user can also apply filter on car models from models chebox list and so on. There are about 10 such filters on the form.
Here is the code snippet of the my form:
<form action='./search' method='get'>
<input type='checkbox' name='make[]' value='BMW'/>
<input type='checkbox' name='make[]' value='Mercedes'/>
<input type='checkbox' name='make[]' value='Honda'/>
<input type='checkbox' name='make[]' value='Toyota'/>
<input type='checkbox' name='make[]' value='Porsche'/>
......//Remaining Form
</form>
Similarly for car models I have similar markup...There are such 10 filters all implemented using checkbox list.
Now coming towards the problem, when I submit the form I get URL like this:
http://localhost/auto/search?make=BMW&make=Mercedes&make=Honda
This is forming a type of query string which I don't like i.e it is repeating 'make' attribute for all the checked values and will do so for remaining 9 filters as well. This will result in very long ugly looking URL.
What I want is that my URL should look something like this:
http://localhost/auto/search?make=BMW,Mercedes,Honda
This is much better but I don't know how would I achieve that. What I have tried is to get all the values of checked boxes and then write them into hidden field value so that I get my desired format in the query string. And unset all the checboxes selected by the user and submit the form with hidden field containing all the selections. But the problem is when the form is submitted I get two 'make' fields in the URL like:
http://localhost/auto/search?make=&car_makes=BMW,Mercedes,Honda
where car_makes is the hidden input field in which I wrote all the selections in value attribute.
Any solution to this? So that make attribute does not get submitted, but it does, since it is the part of the form.
Thanks.
Try these:
<html>
<head>
<script type="text/javascript">
function buildup(){
var makes=document.getElementsByName('make[]');
var m=document.getElementById('make');
m.value='';
ms='';
for (var i = makes.length - 1; i >= 0; i--) {
if(i>0)ms=ms+',';
ms=ms+makes[i].value;
}
m.value=ms;
document.getElementById('form').submit();
}
</script>
</head>
<body>
<input type='checkbox' name='make[]' value='BMW'/>
<input type='checkbox' name='make[]' value='Mercedes'/>
<input type='checkbox' name='make[]' value='Honda'/>
<input type='checkbox' name='make[]' value='Toyota'/>
<input type='checkbox' name='make[]' value='Porsche'/>
<form action='./search' id='form' method='get'>
<input type='hidden' name='make' id='make'>
<input type='button' value='submit' onclick='buildup()'>
</form>
</body>
If you don't want the make inputs to get submitted, you should disable them before the form gets submitted (or remove the name attribute...).
It would probably be easiest to add a class to all inputs you don't want to submit and then do something like this right before the form submit:
html:
...
<input type='checkbox' name='make[]' value='BMW' class='dont-send-class' />
...
js:
$('.dont-send-class').prop("disabled", true);
// now you can submit the form
Related
I have some PHP code that generates and edits forms of users. The number of forms depend on number of users registered. As a developer, I don't know what's the number of users that can register per day.
The code is like this:
for($i=0;$i<$n;$i++)
{
echo "<form method='post'>
<input type='text' name='fname'>
<input type='text' name='lname'>
<input type='submit' name='submit' value='save'></form>";
}
This code can repeat with 4 or 5 or ++ users. When i do:
if(isset($_POST['submit']))
{
//code
}
for recovering the value of the two inputs.
How does the PHP know the source of the event? It can make a mistake because all button has the same name? Please help me!
You can give the button different names then:
for($i=0;$i<$n;$i++)
{
echo "<form method='post'>
<input type='text' name='fname'>
<input type='text' name='lname'>
<input type='submit' name='submit".$i."' value='save'></form>";
}
And then loop through the names to see if (and which) button is pressed:
for($i=0;$i<$n;$i++)
{
if(isset($_POST['submit'.$i]))
{
//code
}
}
If in addition you want to distinguish post values of the inputfields you could index their names alike.
When a process changed required me to change a radio button field, to a checkbox to allow multiple selections, I made the following change to my html:
<input type='checkbox' name='ptype[]' value='1'> Jail/not sentenced</br>
<input type='checkbox' name='ptype[]' value='2'> Jail/Sentenced</br>
<input type='checkbox' name='ptype[]' value='3'> State/DOC</br>
<input type='checkbox' name='ptype[]' value='4'> ICE/US Marshall</br>
<input type='checkbox' name='ptype[]' value='5'> 7x/wardens Agree</br>
When making ptype an array to handle multiple selections, I am finding my $_POST variable missing a key. If I try to revert ptype to a radio button and handle only one value, I don't get any error/warning.
I've checked Firebug, and when ptype[] is set, one of my $_POST variables is not relayed. I know the max post variable is not an issue, as I only have 52 post variables on my form.
I don't know if it's relevant, but this field is never coming through:
<input type='radio' name='wc' value='1'> Yes
<input type='radio' name='wc' value='0'> No
Notice: Undefined index: wc in C:\inetpub\wwwroot\internal_tools\include\consults\consult_utilities.php on line 53
Any help would be greatly appreciated.
EDIT: As requested, my form.
EDIT 2: Firebug POST variables
EDIT 3: Added line 53:
$data['workers_comp'] = $_POST['wc'];
Probably you didn't select an option for the wc radiobutton and therefore the variable is not submitted.
You should change your PHP code to:
$wc = isset($_POST["wc"]) ? $_POST["ws"] : "0";
Or, as I already suggested in comment, you have a problem in the javascript method validateFrm which you call upon submitting the form.
I am trying to get values of rows which are checked using checkbox. So when I submit the form I want values of selected rows but I am not able to figure it out how to get it. Can anybody help me or guide me?
<?php
if(isset($_POST['invite'])){
// what should I write here to get value of hidden fields name and email which was selected
}
?>
<!doctype>
<html><head>
<script type="text/javascript" src="jquery-1.4.2.js"></script>
// performing select all /deselect all checkbox operation
<SCRIPT language="javascript">
$(function(){
// add multiple select / deselect functionality
$("#selectall").click(function () {
$('.case').attr('checked', this.checked);
});
// if all checkbox are selected, check the selectall checkbox
// and viceversa
$(".case").click(function(){
if($(".case").length == $(".case:checked").length) {
$("#selectall").attr("checked", "checked");
} else {
$("#selectall").removeAttr("checked");
}
});
});
</SCRIPT>
</head><body>
<div class = 'middle' style = 'width : 700px;background-color:beige'>
// creating grid view
<form type="post" name ="contacts">
<span><input type="checkbox" id="selectall"/></span>
<div class = 'middle row'>NAME</div>
<div class = 'middle row'>E-MAIL</div>
<div class='line'></div>
<div class='line'></div>
<?php foreach($email as $e){
echo "<div>
<span><input type='checkbox' class='case' name='case'/></span>
<div class='row'>".$e['name']."
<input name='cname[]' type='hidden' value =".$e['name']."></div>
<div class='row'>".$e['email']."
<input name='cemail[]' type='hidden' value =".$e['email']."></div>
</div><div class='line'></div>";
}
echo"<input type='submit' name='invite' value='invite'>
</form></div></body></html>";
}?>
After submitting the form, the value of a checked checkbox appears in the $_POST array like any other form fields. In your case, you have multiple checkboxes named case. None of those has a specific value assigned, so $_POST['case'] will equal on if any checkbox is checked, so this won't help you at all.
Change the name of the checkbox to case[] and assign a unique value to each, and $_POST['case'] will contain an array of the values of all checked checkboxes after submit. For instance, you could repeat the values of the hidden fields in the value attribute of your checkbox.
I wrote a small php script that should help you to understand, how checkboxes work with php. Just run it, play with the checkboxes and have a look at the $_POST array afterwards.
<!doctype html>
<html>
<body>
<form method="post">
<input type="checkbox" name="test[]" value="0"/>
<input type="checkbox" name="test[]" value="1"/>
<input type="checkbox" name="test[]" value="2"/>
<input type="checkbox" name="test[]" value="3"/>
<input type="checkbox" name="test[]" value="4"/>
<input type="submit"/>
</form>
<pre><?php var_dump($_POST); ?></pre>
</body>
</html>
If you want to keep your hidden fields and don't want to repeat their values in the checkbox element, you can also use the array key of their arrays as checkbox value:
<?php
$i = 0;
foreach($email as $e) {
echo "<div>
<span><input type='checkbox' class='case' name='case[]' value='".$i."'/></span>
<div class='row'>".$e['name']."
<input name='cname['".$i."']' type='hidden' value =".$e['name']."></div>
<div class='row'>".$e['email']."
<input name='cemail['".$i."']' type='hidden' value =".$e['email']."></div>
</div><div class='line'></div>";
$i++;
}
Now, if $_POST['case']contains the values 2, 4 and 8 for instance, the emails you are looking for, are in $_POST['cemail'][2], $_POST['cemail'][4] and $_POST['cemail'][8]. Same applies for $_POST['cname'], of course.
First of all, there's a mistake in an argument of form tag:
<form type="post"
This should read
<form method="post"
Then, since you store name and e-mail in the inputs named cname[] and cemail[], they will be passed respectively in $_POST['cname'] and $_POST['cemail'] variables. Note that you named them in a way they will be passed as arrays, so actually, $_POST['cname'] is an array - it contains a key-value pair of 0 and the value attribute of the input control. So actually, your name and e-mail will be in $_POST['cname'][0] and $_POST['cemail'][0] variables.
Please analyse and also read Dealing with Forms section of PHP manual.
I have the following form:
<form name='progObj_form' method='POST' enctype='multipart/form-data' action='processpage.php'>
<select name='manageObj[]' id='objectives' multiple="multiple">
<option value=0>there are no objectives for this program</option>
</select><br />
<a href='#nogo' onclick="delItem(objectives,0,'objEditBtn')" class='shiftOpt'>delete selected</a><br />
<input name='newObjective' type='text' id='newObjective'/>
<input name='addNew' type='button' onclick="AddItem(newObjective.value,6,'objectives','objEditBtn');" value='add objective'/>
<input name="passProgID" type="hidden" value="1" /><br />
<input name="objectiveEdit" id="objEditBtn" type="submit" value="save changes" disabled=disabled/>
</form>
that allows data (objectives in this case) to be added and deleted from a list box. That all works well but for some reason the updated listbox values aren't being passed to the process page.
I'm catching the data like so (simplified):
if (isset($_POST['objectiveEdit'])){
$progID=$_POST['passProgID'];
for ($v=1;$v<count($_POST['manageObj']);$v++){
$value=$_POST['manageObj'][$v];
$sqlObj="INSERT INTO progObjective (progID,objective,objectiveOrder) VALUES ($progID,$value,$v)";
$result = mssql_query($sqlObj,$linkProbation) or die('Query failed: '.$sqlObj);
}//end for ($a=0;$a<count($_POST['manageObj']);$a++)
$objMsg=print_r($_POST['manageObj']).$sqlObj;
}//end if (isset($_POST['objectiveEdit'])
For $objMsg, I get a response of 1 and the array doesn't print because ostensibly, it's empty which means that it also doesn't enter the for loop.
I can include the javascript as well but started with just this for simplicity since I'm probably just overlooking something obvious?!
Option elements are never sent to the server. Only the value of the selected option will be sent.
In your case, something like manageObj=x will be sent to the server, where x is the value of the option element that is selected by the user. It is possible that you misunderstand the [] when it's used in a name attribute.
You should try to find a different method if you want to send the objectives created by the user to the server. You could store the data in hidden inputs for example.
So I finally figured it out! There's no array because there are no selections made! I updated the submit button to call a SELECT ALL function and now it's all good.
<input name="objectiveEdit" id="objEditBtn" type="submit" value="save changes" onclick="selectAll('objectives',true)" />
name='manageObj[]' - shouldn't that be name='manageObj' ?
I have this form which allows the input of any product quantity from 1-10:
<form method='post' action='cart.php'>
<input type='number' name='quantitychange' size='2' min='1' max='10' value=".$_SESSION["itemsSelected"][$i][1].">
<input type='hidden' name='ProductID' value=".$_SESSION["itemsSelected"][$i][0].">
<input type='submit' value='Update'>
</form>
And another form (button) to display a selection of payment modes:
<form action='cart.php' method='post'>
<input type='hidden' name='next'>
<input type='submit' value='Select Payment Mode'>
</form>
What I want to happen is that when a user did not input anything (1st form), ex. null or 0, I want to display an alert box that says 'Product quantity can't be null or 0'.
Here's my code for that:
if (isset($_POST['next'])) {
if ($_POST['quantitychange']==null || $_POST['quantitychange']==0) {
?>
<script type='text/javascript'>
alert('Product quantity can't be null or 0.');
</script>
<?php
}
else {
echo "
//Payment modes here
";
}
}
The error is that even when a user inputs a quantity bet. 1 to 10, it still displays the alert message. Any help? Thank you.
By the way, the input type "number" only works in Google Chrome browser.
Use a small javascript (or jQuery) function to validate the form before posting it. Have this function throw up the alert if your condition isn't met and then return false. If the condition is met, return true, and it gets submitted.
Edited to add since this might get googled, I'll help a bit with code snippet I have used. The below example is jQuery and was used in production for a web application I made for my employees. document.form.doit.submit(); should be the pure javascript way of submitting the form.
<script type="text/javascript">
function subForm() {
// document.form.doit.submit();
if( test condition passes ) {
$('#save_order').submit();
}
}
</script>
<form id="save_order" action="oms_db.php" method="POST">
<input id="doit" type="button"
value="i am a button" onClick="subForm();">
</form>
I think you have some error in your forms. Instead of the below:
<input type='number' name='quantitychange' size='2' min='1' max='10' value=".$_SESSION["itemsSelected"][$i][1].">
<input type='hidden' name='ProductID' value=".$_SESSION["itemsSelected"][$i][0].">
you should be using something like this:
<input type='number' name='quantitychange' size='2' min='1' max='10' value="<?php echo $_SESSION["itemsSelected"][$i][1]; ?>">
<input type='hidden' name='ProductID' value="<?php echo $_SESSION["itemsSelected"][$i][0]; ?>">
The value parameters in the hidden input fields needs to be echoed from PHP. What you have now is like the value is simple strings ".$_SESSION["itemsSelected"][$i][0].".
I suggest you use
if(empty($_POST['quantitychange'])) { echo 'yourerror'; }
As it is far cleaner then your script. (http://php.net/manual/en/function.empty.php)
Update:
Also, you can't use two seperate forms like you do, your browser only posts whats between
<form>
</form>
Using only one will fix your problem.