Default value if input field empty - php

I have a search form with various field but i want to set a default into the url if the field is empty:
<input type="text" name="price-max" class="form-control" placeholder="Max Price" >
and when the form is submited my url looks something like this
search.php?location=location&category=Category&status=lease&price-max=
instead i want a default value so that when i submit the form with an empty price field the url should like.
search.php?location=location&category=Category&status=lease&price-max=999

(Just) Do it server-side:
$price_max = empty($_GET['price-max']) ? 999 : $_GET['price-max'];
// /\ default value
That way, when you use $price_max in your query, it will be either user input or the default value (999 - or whatever value you decide to go with).
You don't even have to mess with the url to achieve that.
The previous code is the same as:
if(empty($_GET['price-max'])){
$price_max = 999; // default value
}else{
$price_max = $_GET['price-max'];
}
Sidenotes:
You could combine the above code with trim;
There's info / example in the docs: Example #3 Assigning a default value;
You didn't show the php code, but make sure you are protected against sql-injections;
You could put your default value as placeholder in the input, just so the user 'sees' something in there.

If you want to put default value, you should define value in each input field.
<input type="text" value="defualt_value" name="price-max" class="form-control" placeholder="Max Price" >

Instead of sending the form directly, call a function to validate the form fields. In that function, check if that field is empty and then add your default value. Finally that function submits the form.

You just need to define feild default value
<input type="text" name="price-max" class="form-control" placeholder="Max Price" value="999">

1st method
Define value attribute in your input field but this will show your default value in text field
<form method = "GET" action="search.php">
<input type="text" name="price-max" class="form-control" placeholder="Max Price" value = "<?php echo $_GET['price-max'] ? $_GET['price-max'] : 999 ?>">
<input type="submit" value="submt">
if you didn't input then it will carry price-max = 999 otherwise whatever you will type
2nd Method
Use jQuery or javascript for this
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<form method = "GET" action="search.php" id="my_form">
<input type="text" name="price-max" id="price-max" class="form-control" placeholder="Max Price">
<input type="submit">
</form>
<script type="text/javascript">
$(document).ready(function() {
$("#my_form").submit(function() {
if($("#price-max").val()=="") {
$("#price-max").val('999');
}
});
});
</script>
I have added id attribute to form and price-max field

in controller example
public function getMessages(Request $request){
$page = request('page', 1);
$limit = request('limit', 100);
$status = request('status', 'all');
$sort = request('sort', 'asc');
$id = request('id', 'asc');
$referenceId = request('referenceId', '');
$from = request('from', '');
$to = request('to', '');
$ack = request('ack', '');
.......
}

Related

PHP: How can I set a default value for $_POST array?

I'm building an e-commerce webpage and working on the "add to cart" button on the checkout page. Here, when the first page is loaded, I want to show a default value "1". And after that, the customer can adjust the quantity. I'm using the POST method to save the quantity input, but I'm not sure how to set the default value "1". Below is my code:
<section>
<?php
if (!empty($_POST)) {
$error = false;
if (empty($_POST["quantityInput"])) {
echo "<p class='errorMessage'> Quantity must be entered. </p>";
$error = true;
}
}
?>
<td class="quantityColumn">
<form action="cart.php" method="post">
<input type="number" id="quantityInput" name="quantityInput" min="1" max="10"
<?php
if (isset($_POST["quantityInput"])) echo "value='" . $_POST["quantityInput"] . "'";
?>>
<input type="submit" id="updateButton" value="Update">
</form>
</td>
</section>
I tried setting $_POST['quantityInput'] = "1", but when I enter a new value and submit the form, it only shows "1", and not the new value... Is there a way to set a default value using PHP? What method/function should I look into?
You can use null coalescing operator if quantityInput is not defined
Eg.
$_POST["quantityInput"] = $_POST["quantityInput"] ?? 1;
// Or on the short form
$_POST["quantityInput"] ??= 1;
It will set $_POST["quantityInput"] to 1 if not exist, by mean default value
The input field can be written like this:
<input
type="number"
id="quantityInput"
name="quantityInput"
min="1"
max="10"
value="<?= isset($_POST["quantityInput"]) ? 1 : $_POST["quantityInput"] ?>"
>

PHP POST values from selected textboxes

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'.

PHP default input value won't change on save

I had my site working as follows:
Input url in Wordpress options, save and it saves.
Now I want it so set a default value in the input (url of the server) and if I change and save it, on page re-load the new value should appear, not the default value.
Before
<label for="site">
<strong>Site:</strong>
<input type="text" name="url" value="<?php echo $this->getOption($options, 'url') ; ?>">
</label><em>
My attempt
I have now set a default value of the input to be that of the server url but obviously on page re-fresh it will display this value, just unsure how to fix this so if I update the input and press save, on page re-fresh it will retain my last input rather than updating it with the default value.
<label for="site">
<strong>Site:</strong>
<input type="text" name="url" value="http://<?php echo str_replace('www.','', $_SERVER['SERVER_NAME']); ?>/"/>
</label><em>
My suggestion is to set a variable to the original $_SERVER value.
If a value is posted from the form, set the variable to that value instead.
Then, use that variable to populate the input value, rather than the original $_SERVER value.
Something like this:
<?php
// this uses a ternary operator. if ? then : else.
// if value is posted set to that value, otherwise set to $_SERVER value
$url= !empty($_POST['url'])
? $_POST['url']
: 'http://'.str_replace('www.','', $_SERVER['SERVER_NAME']);
// show a message if data is posted (for debugging purposes)
if (!empty($_POST)) {echo "<p>Data was posted.</p>";}
?>
<form action="" method="post">
<label>
<strong>Site:</strong>
<input type="text" name="url" value="<?php echo $url ?>" />
</label>
</form>

Javascript onclick html field value without editing .js file

<input type="text"
name='username'
onblur="if(this.value=='')this.value='Username';"
onfocus="if(this.value=='Username')this.value='';"
value="Username"
class="register"/>
This is the code that I am using but the way my code is setup I want the text to be viewable in the field before the user types in their information but the way the form is setup now the
value="<?php echo $db_first_name; ?>"
but the code i'm using needs
value="Username"
to display username in the field before clicked by user and put in their own information.
I tried
value="Username<?php echo $db_first_name; ?>"
But obviously that did not work. Any Ideas?
Link to view functionality of form: http://odconnect.com/beta/registration2.php
Try the placeholder attribute (valid as of HTML5):
<input type="text" name="username" id="username" placeholder="Username" value="<?= $db_first_name; ?>" />
Alternatively (in other words, if you want to support users whose browsers don't support HTML5), you can test to see whether the user already has a username entered. If it's null or an empty string, set the value to "Username" otherwise, set the value to the value of $db_first_name. Then change the onBlur event to check for the length of the value of the field, and if the length is zero, have it display "Username". Finally, change the onFocus event to listen for a mouse-click - when the user gives focus to the field, set the value to an empty string.
<input type="text" name="username" id="username" value="<?= $db_first_name == "" ? "Username" : $db_first_name ?>" onBlur="checkUsernameBlur(this, 'Username');" onFocus="checkUsernameFocus(this, 'Username');" />
<script type="text/javascript" language="javascript>
function checkUsernameBlur(inputObj, label) {
var strLen = inputObj.value.length;
if (strLen == 0) {
inputObj.value = label;
}
}
function checkUsernameFocus(inputObj, label) {
var value = inputObj.value;
if (value == label) {
inputObj.value = "";
}
}
</script>
To work in lower html versions not only in html5 change the Username text in all the three places to the wanted word or php variable
<input type="text" name='username' name='username' onblur="if(this.value=='')this.value='<?php echo $db_first_name; ?>';" onfocus="if(this.value=='<?php echo $db_first_name; ?>')this.value='';" value="<?php echo $db_first_name; ?>" class="register"/>

Trouble passing slider value to php mail script

I want to email the value of the slider along with some things they entered into my form to my php email script. This is how the form looks that will pass data to the POST method of mailer.php:
<form method="POST" action="mailer.php">
Name:
<input type="text" name="name" size="19"><br>
<br>
E-Mail:
<input type="text" name="email" size="19"><br>
<input type="hidden" name="slider_value" size="19" value=document.getElementById('sliderValue').value><br>
<br>
<input type="submit" value="Submit" name="submit">
</form>
document.getElementById('sliderValue').value is the call I make to get the value of the slider but when I pass this to the value of my hidden input slider_value I get back "document.getElementById('sliderValue').value" in the email that is sent by my php script. How would I pass the value instead?
document.getElementById is a Javascript function. It probably won't do what you want it to unless you put it in a place where Javascript is accepted.
One way to pass the slider value is by putting the sliderValue element in the form that you are submitting.
If that is not an option, you can set the value of the slider_value element with Javascript. Either set an onsubmit attribute to the form like this:
<form method="POST" action="mailer.php"
onsubmit="this.slider_value.value = document.getElementById('sliderValue').value">
or add an event listener to do it:
var form = document.forms[0]; //this may need to be changed depending on your form
function addSliderValue() {
this.slider_value.value = document.getElementById('sliderValue').value;
}
if (form.addEventListener) { //most browsers
form.addEventListener("submit", addSliderValue, false);
} else if (form.attachEvent) { //IE
form.onsubmit = addSliderValue;
}
Bind a function to the sliders "onSlide/onChange/whatever it's called" event that will update the hidden input field with the slider value. Also set the input value to the initial slider value on slider init. That should do the trick.

Categories