This is the content on my view page and i want to replace the value from "0" when the monthfunc() is called...the monthfunc() is given below the view content
<tr>
<td>
<input type="submit" name="monthplus" id="monthplus" onClick="return monthfunc('monthplus');" value=">>>>>>">
<input type="hidden" name="monthnum" id="monthnum" value="1">
<input type="text" name="monthname" id="monthname" value="0" value="<? echo $month;?>" >
<input type="submit" name="monthminus" id="monthminus" onClick="return monthfunc('monthminus');" value="<<<<<<">
</td>
</tr>
My script is
function monthfunc(mnth)
{
if(mnth == 'monthplus')
{
var yn = document.getElementById('monthnum').value;
ynpo = parseInt(yn)+1;
if(ynpo==13)
{
ynpo=1;
}
}
else if(mnth == 'monthminus')
{
var yn = document.getElementById('monthnum').value;
ynpo = parseInt(yn)-1;
if(ynpo==0)
{
ynpo=12;
}
}
if(ynpo ==1)
{
document.getElementById('monthname').value = 'january';
document.getElementById('monthnum').value = ynpo;
return true;
}
else if(ynpo ==2)
{
document.getElementById('monthname').value = 'february';
document.getElementById('monthnum').value = ynpo;
return true;
}
else if(ynpo ==3)
{
document.getElementById('monthname').value = 'March';
document.getElementById('monthnum').value = ynpo;
return true;
}
return false;
}
How can i replace The value with the value like january february etc..
Actually i can change the values but cannot retain the values...
i want to retain the values ,,,How to do that
For the monthname input you have two 'values'. What happens when you remove the first one?
Also, you really need to improve the structure of your function. For example, using the following array would reduce your code significantly:
var month=new Array(12);
month[0]="January";
month[1]="February";
month[2]="March";
month[3]="April";
month[4]="May";
month[5]="June";
month[6]="July";
month[7]="August";
month[8]="September";
month[9]="October";
month[10]="November";
month[11]="December";
I'm not sure I exactly understand your question, but by way of an answer:
One of the input elements in your HTML snippet has two value attributes:
value="0"
and
value="<? echo $month;?>"
I would start by removing one of them.
Related
I've got some code working that takes the text from my input box and moves it across to a function. I'm now trying to change it so I add another form element, a radio button and I want to access the choice within my functions.php file.
This is my current code which works for the post name, but what if I want to also grab the colours boxes that was selected too?
main.php
<?php
if (isset($_POST['submit'])) {
$data = $_POST['name']; // the data from the form input.
}
?>
...
<form action="/" method="post">
<input type="text" name="name" placeholder="Acme Corp"/>
<input name="colour" type="radio" value="red">Red<br>
<input name="colour" type="radio" value="blue">Blue<br>
<input name="colour" type="radio" value="green">Green<br>
<input type="submit" name="submit" value="Submit">
</form>
<img src="pngfile.php?data=<?php print urlencode($data);?>"
alt="png php file">
I guess I confused because currently it is calling this:
pngfile.php
<?php
require_once 'functions.php';
$inputData = urldecode($_GET['data']);
process($inputData);
exit;
?>
Which calls functions.php
<?php
function process($inputdata)
{
...
EDIT: What I have tried:
main.php [Change]
$data = $_POST['name'] && $_POST['colour']
But I'm not really sure how to progress.
Never trust user input. Sanitize and validate your inputs before using them.
This can be arranged better, but the basics are still true.
PHP Manual: filter_input_array()
PHP Manual: filter_var_array()
Small Function Library
function sanitizeArray($filterRules)
{
return filter_input_array(INPUT_POST, $filterRules, true)
}
function validateArray($filteredData, $validationRules)
{
return filter_var_array($filteredData, $validationRules, true);
}
function checkFilterResults(array $testArray, array &$errors)
{
if (!in_array(false, $testArray, true) || !in_array(null, $testArray, true)) {
foreach($testArray as $key => $value)
{
$errors[$key] = '';
}
return true;
}
if ($testArray['name'] !== true) { //You can make a function and do various test.
$errors['name'] = 'That is not a valid name.';
}
if ($testArray['clour'] !== true) { //You can make a function and do many test.
$errors['colour'] = 'That is not a valid colour.';
}
return false;
}
function processUserInput(array &$filteredData, array $filterRulesArray, array $validationRulesArray, array &$cleanData, array &$errors)
{
$filteredInput = null;
$tempData = sanitizeArray($filterRulesArray);
if (!$checkFilterResults($tempData, $errors)){
throw new UnexpectedValueException("An input value was unable to be sanitized.");
//Consider forcing the page to redraw.
}
$filteredData = $tempData;
$validatedData = validateArray($filteredData, $validationRulesArray);
if (!$checkFilterResults($validatedData, $errors)){
return false;
}
$errors['form'] = '';
$cleanData = $validatedData;
return true;
}
function htmlEscapeArray(array &$filteredData)
{
foreach($filteredData as $key => &$value)
{
$value = htmlspecialchars($value, ENT_QUOTES | ENT_HTML5, 'UTF-8', false);
}
return;
}
Basic Main Line
try {
$filterRulesArray = []; //You define this.
$filteredData = []; //A temporary array.
$validationRulesArray = []; //You define this.
$validatedData = null; //Another temporary array.
$results = null; //Input processing results: true or false.
$cleanData = null; //Filtered and validated input array.
$errors = []; //Any errors that have accumulated.
if (isset($_POST, $_POST['submit'], $_POST['colour']) && !empty($_POST)) {
$results = processUserInput($filteredData, $filterRulesArray, $validationRulesArray, $cleanData, $errors);
} else {
$errors['form'] = "You must fill out the form."
}
if ($results === true) {
$name = $cleanData['name']; //You can do what you want.
$colour = $cleanData['colour']; //You can do what you want.
//header("Location: http://url.com/registration/thankYou/")
//exit;
}
//Prepare user input for re-display in browser
htmlEscapeArray($filteredData);
} catch (Exception $e) {
header("Location: http://url.com/samePage/"); //Force a page reload.
}
Let the form redraw if input processing fails.
Use the $errors array to display error messages.
Use the $filteredData array to make the form sticky.
<html>
<head>
<title>Your Webpage</title>
</head>
<body>
<h1>My Form</h1>
<form action="/" method="post">
<!-- Make spots for error messages -->
<input type="text" name="name" placeholder="Acme Corp" value="PUT PHP HERE"/>
<!-- No time to display sticky radios! :-) -->
<input name="colour" type="radio" checked="checked" value="red">Red<br>
<input name="colour" type="radio" value="blue">Blue<br>
<input name="colour" type="radio" value="green">Green<br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
Tip:
It may be better to submit numbers for radios, as opposed to longer string values like (red, green, blue). Numbers are easier to sanitize and validate. Naturally, then you must translate the input number into its corresponding string. You would do that after validation has finished, but before using the values. Good luck!
you can access this using array like this.
$data[] = $_POST['name'];
$data[] =$_POST['colour'];
Or combine both variable
$data = $_POST['name'].'&'.$_POST['colour'];
Use Array in php for this process as follows:
if (isset($_POST['submit'])) {
$array_val = array(
"name"=> $_POST['name'],
"color"=> $_POST['color']
);
}
In my form I am trying to get the radio checked value to be passed on to the next page (which is an FPDF page)
I have 4 options: Annual Leave, Sick Leave, Business Leave, & also others with a textfield.
However I have tried a lot of 'if' as well as 'switch cases'
I am getting either only the element with value '1'
or else 'Undefined index: rad in D:\xampp\htdocs\Application\generate_report.php on line 13'
some where I am wrong, can anyone help me please. My code below.
html form:
<form id="formmain" method="post" action="generate_report.php" onsubmit="return_validate()">
<script type="text/javascript">
function selectRadio(n){
document.forms["form4"]["r1"][n].checked=true
}
</script>
<table width="689">
<tr>
<td width="500d">
<input type="radio" name="rad" value="0" />
<label>Business Trip</label>
<input type="radio" name="rad" value="1"/><label>Annual Leave</label>
<input type="radio" name="rad" value="2"/><label>Sick Leave</label>
<input type="radio" name="rad" value="3"/><label>Others</label> <input type="text" name="others" size="25" onclick="selectRadio(3)" />
</td>
</tr>
</table>
//....
//below submit button is end of the html page:
<input type="submit" name="submit" value="send" />
</form>
Generate PDF form:
$radio = $_POST['rad']; // I am storing variable
if($radio = 0) {
$type = 'Business Leave';
}elseif ($radio = 1) {
$type = 'Annual Leave';
}elseif ($radio = 2) {
$type = 'Sick Leave';
} else { $type = $_POST['others']; }
//echo
$pdf->Cell(98,10, 'Reason | ' .$type , 1, 0, 'C', $fill);
if($radio = 0)
and
elseif ($radio = 1)
and all the other elseifs have to be == 1, with two '='!
A further explanation on the OP. If you do not use == then you are setting the value, not checking it. Furthermore, there are levels of checking. Using the double equals (==) is effectively stating "is equal to" whereas using triple equals (===) is like stating "is absolutely equal to". Generally the == operator will do everything you need but sometimes when working with data types or specific values you might need ===. This is mostly FYI as the OP has an actionable solution.
You should always check if inputs are checked or any value inserted. If there's no value, then it throws an undefined index error. Also, you should replace =s to == in your if clauses. So:
PHP:
$radio = $_POST['rad']; // I am storing variable
if (isset($radio)) { // checks if radio is set
if($radio == 0) {
$type = 'Business Leave';
}elseif ($radio == 1) {
$type = 'Annual Leave';
}elseif ($radio == 2) {
$type = 'Sick Leave';
} else {
if (isset($_POST['others'])) { // cheks if input text is set
$type = $_POST['others'];
}
else {
echo 'Error';
}
}
//echo
$pdf->Cell(98,10, 'Reason | ' .$type , 1, 0, 'C', $fill);
}
else {
echo 'Error';
}
Now it should work.
I’m attempting to pass multiple values through J Query and displaying in a div. The code below works fine for single values.
<script type="text/jscript">
function get1() {
$.post('viewexisting.php', {
Status: reportform.Status.value,
Date1: reportform.Date1.value,
Date2: reportform.Date2.value
},
function (output) {
$('#info').html(output).show();
});
}
</script>
<form name="reportform">
<?php
{
$box1 = array();
$result1 = "SELECT Status FROM CT:Status";
$rs1 = odbc_exec($conn1,$result1);
while($row = odbc_fetch_array($rs1)) {
$box1[] = $row;
}
}
$Status = '<select name="Status" multiple="multiple size="7">';
$Status .= '<option selected="selected">---< All Statuses >---</option>';
if (!empty($box1)) {
foreach ($box1 as $k => $v) {
$Status .= '<option value="'.$v['Status'].'">'.$v['Status'].'</option>';
}
}
$Status .= '</select>';
echo $Status;
?>
Date Range: <br>From <input name="Date1" id="Date1" type="text"><br>
To <input name="Date2" id="Date2" type="text">
<input type="button" value="Apply Date Range" onclick="get1();" style="width: 146px">
</form>
<div id="info"></div>
But when I try to put [] behind Status in the select name and in the script, the button stops working. select name="Status[]" does work if I'm using a form with a post method to another page though. I would like to make it work with the javascript. Any ideas? Thanks.
When you use [] as your post names, it becomes an array. You need to iterate the array... in PHP: foreach($array as $item); in jQuery, you can use $.each(array, function(key, value) { })
If you need to pass multiple values from the select box then you need to set a name with brackets to define it as an array, so you should use "Status[]" as you mentioned but the line to retrieve the value in your get1() function will no longer work since the name of the element has changed. I noticed you are sending all your inputs through post and that you're using jQuery so you might as well do this:
function get1() {
$.post('viewexisting.php',
$('form[name="reportform"]').serialize(),
function (output) {
$('#info').html(output).show();
});
}
I have a script wher users can find exercise from a database, I have checkboxes for the user to find specific exercises the script works fine when a least 1 checkbox is selected from each checkbox group however I would like it that if no checkboxes was selected then it would the results of all checkboxes.
my checkbox form looks like this
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="criteria">
<p><strong>MUSCLE GROUP</strong></p>
<input type="checkbox" name="muscle[]" id="abdominals" value="abdominals"/>Abdominals<br />
<input type="checkbox" name="muscle[]" id="biceps" value="biceps" />Biceps<br />
<input type="checkbox" name="muscle[]" id="calves" value="calves" />Calves<br />
ect...
<br /><p><strong>EQUIPMENT (please select a least one)</strong></p>
<input type="checkbox" name="equipment[]" id="equipment" value="bands"/>Bands<br />
<input type="checkbox" name="equipment[]" id="equipment" value="barbell" />Barbell<br />
<input type="checkbox" name="equipment[]" id="equipment" value="dumbbell" />Dumbbell<br />
ect....
<input type="submit" name="sub" value="Generate Query" />
</form>
and here is my script
<?php
if(isset($_POST['muscle']) && !empty($_POST['muscle'])){
if(isset($_POST['equipment']) && !empty($_POST['equipment'])){
//get the function
include ($_SERVER['DOCUMENT_ROOT'] .'/scripts/functions.php');
$page = (int) (!isset($_GET["page"]) ? 1 : $_GET["page"]);
$limit = 14;
$startpoint = ($page * $limit) - $limit;
// Runs mysql_real_escape_string() on every value encountered.
$clean_muscle = array_map('mysql_real_escape_string', $_REQUEST['muscle']);
$clean_equipment = array_map('mysql_real_escape_string', $_REQUEST['equipment']);
// Convert the array into a string.
$muscle = implode("','", $clean_muscle);
$equipment = implode("','", $clean_equipment);
$options = array();
if(array($muscle))
{
$options[] = "muscle IN ('$muscle')";
}
if(array($equipment))
{
$options[] = "equipment IN ('$equipment')";
}
$fullsearch = implode(' AND ', $options);
$statement = "mytable";
if ($fullsearch <> '') {
$statement .= " WHERE " . $fullsearch;
}
if(!$query=mysql_query("SELECT * FROM {$statement} LIMIT {$startpoint} , {$limit}"))
{
echo "Cannot parse query";
}
elseif(mysql_num_rows($query) == 0) {
echo "No records found";
}
else {
echo "";
while($row = mysql_fetch_assoc($query)) {
echo "".$row['name'] ."</br>
".$row['description'] ."";
}
}
echo "<div class=\"new-pagination\">";
echo pagination($statement,$limit,$page);
echo "</div>";
}
}
Im new with php so my code may not be the best. If anyone can help me or point me in the right direction I would be very greatful.
OK - I think I have figured it all out. You were right - the main problem was in your isset and isempty calls. I created some variations on your file, and this shows what is going on. Note - since I don't have some of your "other" functions, I am only showing what is going wrong in the outer parts of your function.
Part 1: validating function
In the following code, I have added two JavaScript functions to the input form; these were loosely based on scripts you can find when you google "JavaScript validation checkbox". The oneBoxSet(groupName) function will look through all document elements; find the ones of type checkBox, see if one of them is checked, and if so, confirms that it belongs to groupName. For now, it returns "true" or "false". The calling function, validateMe(formName), runs your validation. It is called by adding
onclick="validateMe('criteria'); return false;"
to the code of the submit button. This basically says "call this function with this parameter to validate the form". In this case the function "fixes" the data and submits; but you could imagine that it returns "false", in which case the submit action will be canceled.
In the validateMe function we check whether at least one box is checked in each group; if it is not, then a hidden box in the "all[]" group is set accordingly.
I changed the code a little bit - it calls a different script (muscle.php) instead of the <?php echo $_SERVER['PHP_SELF']; ?> you had... obviously the principle is the same.
After this initial code we will look at some stuff I added in muscle.php to confirm what your original problem was.
<html>
<head>
<script type="text/javascript">
// go through all checkboxes; see if at least one with name 'groupName' is set
// if so, return true; otherwise return false
function oneBoxSet(groupName)
{
var c=document.getElementsByTagName('input');
for (var i = 0; i<c.length; i++){
if (c[i].type=='checkbox')
{
if (c[i].checked) {
if (c[i].name == groupName) {
return true; // at least one box in this group is checked
}
}
}
}
return false; // never found a good checkbox
}
function setAllBoxes(groupName, TF)
{
// set the 'checked' property of all inputs in this group to 'TF' (true or false)
var c=document.getElementsByTagName('input');
// alert("setting all boxes for " + groupName + " to " + TF);
for (var i = 0; i<c.length; i++){
if (c[i].type=='checkbox')
{
if (c[i].name == groupName) {
c[i].checked = TF;
}
}
}
return 0;
}
// this function is run when submit is pressed:
function validateMe(formName) {
if (oneBoxSet('muscle[]')) {
document.getElementById("allMuscles").value = "selectedMuscles";
//alert("muscle OK!");
}
else {
document.getElementById("allMuscles").value = "allMuscles";
// and/or insert code that sets all boxes in this group:
setAllBoxes('muscle[]', true);
alert("No muscle group was selected - has been set to ALL");
}
if (oneBoxSet('equipment[]')) {
document.getElementById("allEquipment").value = "selectedEquipment";
//alert("equipment OK!");
}
else {
document.getElementById("allEquipment").value = "allEquipment";
// instead, you could insert code here that sets all boxes in this category to true
setAllBoxes('equipment[]', true);
alert("No equipment was selected - has been set to ALL");
}
// submit the form - function never returns
document.forms[formName].submit();
}
</script>
</head>
<body>
<form action="muscle.php" method="post" name="criteria">
<p><strong>MUSCLE GROUP</strong></p>
<input type="checkbox" name="muscle[]" id="abdominals" value="abdominals"/>Abdominals<br />
<input type="checkbox" name="muscle[]" id="biceps" value="biceps" />Biceps<br />
<input type="checkbox" name="muscle[]" id="calves" value="calves" />Calves<br />
<input type="hidden" name="all[]" id="allMuscles" value="selectedMuscles" />
etc...<br>
<br /><p><strong>EQUIPMENT (please select a least one)</strong></p>
<input type="checkbox" name="equipment[]" id="equipment" value="bands"/>Bands<br />
<input type="checkbox" name="equipment[]" id="equipment" value="barbell" />Barbell<br />
<input type="checkbox" name="equipment[]" id="equipment" value="dumbbell" />Dumbbell<br />
<input type="hidden" name="all[]" id="allEquipment" value="selectedEquipment" />
<br>
<input type="submit" name="sub" value="Generate Query" onclick="validateMe('criteria'); return false;" />
</form>
</body>
</html>
Part 2: what's wrong with the PHP?
Now here is a new start to the php script. It checks the conditions that you were testing at the start of your original script, and demonstrates that you never get past the initial if statements if a check box wasn't set in one of the groups. I suggest that you leave these tests out altogether, and instead get inspiration from the code I wrote to fix any issues. For example, you can test whether equipmentAll or muscleAll were set, and create the appropriate query string accordingly.
<?php
echo 'file was called successfully<br><br>';
if(isset($_POST['muscle'])) {
echo "_POST[muscle] is set<br>";
print_r($_POST[muscle]);
echo "<br>";
if (!empty($_POST['muscle'])) {
echo "_POST[muscle] is not empty!<br>";
}
else {
echo "_POST[muscle] is empty!<br>";
}
}
else {
echo "_POST[muscle] is not set: it is empty!<br>";
}
if(isset($_POST['equipment'])) {
echo "_POST[equipment] is set<br>";
print_r($_POST['equipment']);
echo "<br>";
if (!empty($_POST['equipment'])) {
echo "_POST[equipment] is not empty!<br>";
}
else {
echo "_POST[equipment] is empty!<br>";
}
}
else {
echo "_POST[equipment] is not set: it is empty!<br>";
}
if(isset($_POST['all'])) {
echo "this is what you have to do:<br>";
print_r($_POST['all']);
echo "<br>";
}
// if(isset($_POST['muscle']) && !empty($_POST['muscle'])){
// if(isset($_POST['equipment']) && !empty($_POST['equipment'])){
If you call this with no check boxes selected, you get two dialogs ('not OK!'), then the following output:
file was called successfully
_POST[muscle] is not set: it is empty!
_POST[equipment] is not set: it is empty!
this is what you have to do:
Array ( [0] => allMuscles [1] => allEquipment )
If you select a couple of boxes in the first group, and none in the second:
file was called successfully
_POST[muscle] is set
Array ( [0] => abdominals [1] => calves )
_POST[muscle] is not empty!
_POST[equipment] is not set: it is empty!
this is what you have to do:
Array ( [0] => selectedMuscles [1] => allEquipment )
I do not claim to write beautiful code; but I hope this is functional, and gets you out of the fix you were in. Good luck!
This question already has answers here:
Fastest way of deleting a value in a comma separated list
(4 answers)
Closed 6 months ago.
I want to remove one value from comma separated string variable
Eg hdnListCL ="'ABC','PQR','XYZ'"
i want to remove any one of them, how i can do this without converting this into array?
html code
<input type="hidden" name="hdnlistCL" id="hdnlistCL"/>
<table>
<tr>
<td>
<div id="ProjList"><?php print $strLocName; ?></div><br/>
<input type="text" name="txtCommonLocation" id="txtCommonLocation" size="40" value=""/>
<img src="images/plus.gif" title="Click Here" onclick="AddNewLocation()" style='cursor:pointer;' align="right"/> </td>
</tr>
</table>
javascript
<script type="text/javascript" src="../scripts/jquery.min.js"></script>
<script type="text/javascript">
function AddNewLocation()
{
var listCL = "";
this.strProjName;
if ( typeof strProjName == 'undefined' ) {
strProjName = '';
}
var newLoc = document.getElementById('txtCommonLocation').value;
document.getElementById('txtCommonLocation').value = "";
if(document.getElementById('hdnlistCL').value == '')
{
document.getElementById('hdnlistCL').value =newLoc;
}
else
{
document.getElementById('hdnlistCL').value += ","+newLoc;
}
listCL = newLoc;
if(listCL != '')
{
strProjName = strProjName + '<div id="'+listCL+'">'+listCL+'<div class="close" onclick="removeLocation(\''+listCL+'\')"></div></div>';
}
// alert(strProjName);
$('#ProjList').html(strProjName);
}
function removeLocation(pLocation)
{
var hdnListLocation = document.getElementById('hdnlistCL').value;
if(window.confirm("Are you sure you want to delete this?"))
{
url = 'test_st.php';
$.post(
url,
{"act":"Delete","DelLocation":pLocation,"hdnListLocation": hdnListLocation},
function(responseText){
alert(responseText);
return false;
window.location="test_st.php";
},
"html"
);
return false;
}
}
</script>
php code
<?php
if(isset($_POST['act']))
$act = $_POST['act'];
if($act == "Delete")
{
$arrhdnListLocation = explode(",", $_POST['hdnListLocation']);
if(in_array($_POST['DelLocation'],$arrhdnListLocation))
{
print("I want to remove'".$_POST['DelLocation']."' from hdnlistCL");
exit();
}
else
{
print("No");
exit();
}
}
?>
when i click close button i want to remove that location from hdnlistCL. how i can do this?
value of hdnListCL is ABC,PQR,XYZ i want to remove PQR from this
$string = "'ABC','PQR','XYZ'";
$remove = "'PQR'";
// you can use array_diff method to remove specific array item
$result = array_diff(str_getcsv($string), array($remove))
echo implode(',', $result); // output is "'ABC','XYZ'"
php fiddle example: http://phpfiddle.org/main/code/v260-p3cf
Please Try this
$hdnListCL ="'ABC','PQR','XYZ'";
$hdnListCL=explode(',',$hdnListCL);
$index = array_search('PQR',$hdnListCL);
if($index !== false){
unset($hdnListCL[$index]);
}
$hdnListCL=implode(',',$hdnListCL);
print_r($hdnListCL);