jquery to signify if an option is not selected - php

I would like to add a small code snip to check out whether an option is selected
This usually is easily done if the page is html, now my code snip looks something like this
echo "<td>Language</td>";
echo "<td><select id='language' name='language'>
<option value=''>Select...</option>
<option value='en_US'>English(US)</option>
<option value='en_AU'>English(AU)</option>
<option value='en_UK'>English(UK)</option>
</select><span id="info"></span>
</td>";
if it is html
<script>
$('#language').change()
{
if('Select...'==$('#language').text())
{
$('#info').html("Please select a value...");
}
}
</script>
[UPDATE]
I would like to add that the above php source code used to generate html code is put in a form tag that is
echo "<form action='checkdb.php' method='POST'>
// all above and more
</form>"
the page checkdb.php used the posted data to update database.
How can I add in the jquery code piece as mentioned in the current file (the file with the html code is being generated) ? I am thinking as people once told me that javascript can't be called in the middle of the php execution and I wonder if I may need to use ajax get function. Please offer some help. Thank you.

// Listen, and respond to, the change even on our select
$("#language").on("change", function(e){
// Set the html content of our info element
$("#info").html(function(){
// If the selected option has no value, ask to select a value
return e.target.value === "" ? "Please select a value." : "" ;
});
// Trigger upon page load
}).trigger("change");
Demo: http://jsbin.com/owaqaz/2/edit
Note the last line, $.trigger("change") - this will cause the page to immediately populate the #info element if the select element currently has no value.

Change your jQuery to:
$('#language').change(function() {
if ('Select...' == $('#language option:selected').text()) {
$('#info').html("Please select a value...");
}
});​
jsFiddle example.
Update: Or a more brief version:
jQuery:
$('#language').change(function() {
$('#info').html(('Select...' == $('#language option:selected').text()) ? "Please select a value...":"");
});​
jsFiddle example.

Sorry but what was your question?
A PHP page turns into a HTML Page after processing (a user never sees the PHP source code), and you can easily use javascript to check for the value.

Related

drop down changes from other drop down with calculation. Jscript / Ajax?

I have a Jscript Query.
I have done a bit of reading and found out that AJAX is just a side server for a lfash script that can be used on Linux with php. (please correct me if I have interperated that wrong)
I have no knowledge on how scripts work so this is new, I have tried a couple of different tries but no luck.
I have one drop down box (Box1) (populated from Database)
I have another box (Box2) for a calculation to insert into my database for other uses on ohter parts of hte site.
I need the Box2 to change the figure when someone changes Box1 dropdown before hitting the submit button.
I think because I have the calcualtion this is getting me stuck... Code is as below... Can someone please help me figure out (I think I need some form of Script to do this.) the answer...
Box1
<td><p>selection 1</p>
<select id="t1_type" name="t1_type">
<?php $result = mysql_query("SELECT * FROM `t2` ORDER BY t2_value");
while($valuerow = mysql_fetch_array($result)){
echo '<option value="'.$valuerow['t2_name'].'">'.$valuerow['t2_name'].'</option>'; } ?>
Box2
<input name="t1_value" id="t1_value" value="
<?php
$var1 = $row_value['t2_value'];
$var2 = $row_dropdown['t1_number'];
$total = round ($var2 * $var1);
echo "" . $total . "";
?>" />
I hope this is all the code you need, (Let me know if more required)
What it needs to do is show new calculation whenever someone changes the box1 option BEFORE the submit button is clicked, so it submits the correct calculation to the database for future use.
I think it would need pretty much "t2_value" from box2 to change when ever "t2_name changed from box1.
And once again the best link to learn about the solution. (Learnt about Joins now from my last question!! Almost a intermediate user. ;-) )
Edit :
I saw that your second box was a textbox I believe, if thats the problem then you should do something like this
<select id="t1_type" name="t1_type" onchange="change(this);">
<?php
$result = mysql_query("SELECT * FROM `t2` ORDER BY t2_value");
while($valuerow = mysql_fetch_array($result))
{
echo '<option value="'.$valuerow['t2_name'].'">'.$valuerow['t2_name'].'</option>';
}
?>
</select>
This defines your <select> box like you did in your question.
Add an onChange event into your first <select> and then create a function to handle to onChange event. An onChange event fires whenever the user changes the item in the <select> element.
Javascript :
( put this part of the code above the </head> )
<script language="javascript" type="text/javascript">
function change(element)
{
// do here whatever you want
// you can change the value of the <input> box with :
// document.getElementById(element.id).value = your_value
// If you want to see if this part works, then try adding this :
// alert("It works!");
// If you want to get the text of the item which has been selected in Box1 use :
// $("#t1_type option:selected").text();
}
</script>
Note: because PHP is server side, you can't update your Box2 dynamically without a page refresh, Javascript however is Client Side and CAN do this.
Note : the $("#t1_type option:selected").text(); code requires you to include the jQuery library into your script. Be sure to convert this variable to a float, int or double if you want to calculate with it, else the outcome will give NaN (Not a Number)
Tutorial on including jQuery Libary :
http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery
If you're new to JavaScript, you should try some tutorials. The ones at w3Schools.com helpt me alot, but some people say they're not always correct, but anyhow, read some stuff about Javascript to actually know what you are doing, instead of copypasting code :)

Showing value data from dropdown in html

I created a script which get from my database the states and price of shipping by number of products.
So...I have 2 dropdown, one for quantity and the second one for state.
This is my main php file: http://pastebin.com/U6dncsZ6
This is the second php file (for database connect) - findcity.php : http://pastebin.com/AuEXrnpD
As you see, in my second php file I have this line:
<option value=<?=$row['price']?>><?=$row['title']?></option>
I want to display the shipping price from the database ($row['price'] on the page.
I specify that using "Inspect element" in my browser I can see the prices added as value for the states, like:
<option value="48.11">State</option>
Please help :(
Le: As I stated in a comment, I finally found that like here it's working: jsfiddle.net/Dkn4n/1/
But for some reasons, it's not detected but it's not working in my page, maybe because the value is not set in html, I can't see the values in source, only in "Inspect element". The value is set as I specified above, with $row['price']
Your select statement looks like this on the page:
<select id="provincia">
<option value="10.00">CA</option>
<option value="20.00">NY</option>
</select>
So using javascript/jQuery you can do the following to get the value of the selected option.
$(document).ready(function(){
$("#provincia").change(function(){
alert(this.value);
//do stuff here to set the value where you want it.
});
});
Here's a demo: http://jsfiddle.net/Dkn4n/
Adding to "Chase"s Answer:
$(document).ready(function(){
$("#provincia").change(function(){
$("#selectedprice").html(this.value);
//<div id=selectedprice></div> should show your value
});
});
and expanding it:
at this line:
document.getElementById('provinciadiv').innerHTML=req.responseText;
do
$("#provincia").change(function(){
$("#selectedprice").html(this.value);
//<div id=selectedprice></div> should show your value
});
again!
Because the "change" binding is gone once you replace the part...

How do I get dropdowns in a PHP script to submit the form on change?

Ok... First off, I know this isn't a new question.
But, for some reason none of the suggestions Google has found for me (dating back to the begining of time even) are working. So, please bear with me.
Let's say, I have a script structured something like this:
<?php
try {
print "<table><form id='menu' action='index.php' method='POST'><tr>";
print "<td>Select A Fruit</td><td><select name=fruit>
<option value=''></option>
<option value='apple'>Apple</option>
<option value='orange'>Orange</option>
<option value='pear'>Pear</option></select></td></tr>";
print "<tr><td><input type='submit' name='submit' value='Submit'></td></tr></form></table>";
if (isset($_POST['submit'])){
if (!empty($_POST['fruit'])){
//Do whatever the form is supposed to trigger.
}
else {
//Nothing selected; handle however makes sense.
}
}
}
catch(Exception $e) {die( print_r( $e->getMessage() ) );}
?>
And instead of using the button, I want it to submit the form as soon as an option is selected.
Based on my searches, the textbook answer appears to be to modify the Select tag with an onchange attribute calling a JavaScript method like so:
<select name='fruit' onchange='document.getElementById('menu').submit()'>
or the short form:
<select name='fruit' onchange='this.form.submit()'>
But here is where I'm stuck...
None of the posts I found explain where you tell the browser/interpreter to drop out to JavaScript to make that work. So, this change does nothing for me.
What am I missing here?
I would get away from the dom level 0 handler and set the select's onchange handler to a function that grabs your form, and calls submit on it.
document.getElementById("yourSelectId").onchange = function() {
document.forms["formsId"].submit();
};
I'm showing you a more robust way of adding event handlers to dom elements. Instead of saying onchange="blah()" you can set up a body onload function that'll run when your dom is ready, then you can use JavaScript to add your handlers:
<body onload="init()">
function init() {
document.getElementById("yourSelectId").onchange = function() {
document.forms["formsId"].submit();
};
}
Or, you can skit the ugly <body onload="init()"> altogether and just put the code
document.getElementById("yourSelectId").onchange = function() {
document.forms["formsId"].submit();
};
in a regular script block at the bottom of your body
Your markup isn't valid, a table-element cannot have a form as child-element(wrap the form around the table)
Choose another name for the submit-button, otherwise you will receive an error in IE when calling submit()
I would suggest using an event listener rather than adding the attribute to your code. Also, it is recommended to have the static page display the submit button, and simply remove it via javascript after the page loads.
element.addEventListener Example
<script type="text/javascript">
document.getElementById("yourSelectId").addEventListener("change", function(){document.forms["yourFormId"].submit();});
</script>
To read more about element.addEventListener (esp. to see why it's important to use it), check out the article on element.addEventListener at MDN.
How javascript works in onchange attribute
But here is where I'm stuck... None of the posts I found explain where you tell the browser/interpreter to drop out to JavaScript to make that work. So, this change does nothing for me.
Attributes such as onchange, onclick, etc (notice "on" at the beginning) parse the value as javascript. Ergo, that is where you are telling the browser to use javascript to make it work :)

Selecting an option value with Javascript, using PHP

Ok, so here is my code. I am trying to select a picklist value using Javascript, from PHP (I do not want a direct method to do this with PHP, as this won't work for my particular program)
Here's the code:
ECHO '<script type="text/javascript">
var pl = document.getElementById("cultpicklist");
pl.options[37].selected = true;
</script>';
However when I try to run this, it does not seem to work and it says pl.options[37] is undefined.
What am I doing wrong?
Note, there is a multiple select list which has an option with a value of 37.
EDIT: I seem to get this error or warning message:
Element referenced by ID/NAME in the global scope. Use W3C standard document.getElementById() instead.
admin.php?org=7()admin.php?org=7 (line 68)
pl.options[37].selected = true;
Here's the relevant HTML:
<fieldset><label for="culture">Culture:</label>
<select name="culture[]" multiple="multiple" id="cultpicklist"><?php
while ($cultrow = mysql_fetch_array($rescult)) {
ECHO '<option name="culture[]" value="'. stripslashes($cultrow['cult_id']) .'">'. stripslashes($cultrow['cult_desc']) .'</option>';
}
?>
</select></fieldset>
Here's the generated HTML code:
<select id="cultpicklist" multiple="multiple" name="culture[]">
<option value="36" name="culture[]">test1</option>
<option value="37" name="culture[]">test2</option>
<option value="38" name="culture[]">test3</option>
<option value="39" name="culture[]">test4</option>
</select>
The index of the options IS NOT the value of the option. When you use pl.options[37] you saying to JS to get the thirty-seventh option in the select and not the option with the value 37.
Try this:
<script type="text/javascript">
var pl = document.getElementById("cultpicklist");
for(var i=0; i<pl.options.length;i++) {
if(pl.options[i].value == "") { // Between the quotes you place the comparison value!
pl.options[i].selected = true;
}
}
</script>
BTW: If you already use jQuery on your page it's more correct to use it's functions, but if you don't use jQuery is too much code to add to your page just to change a select value.
You are likely putting the cart before the horse. You cannot use JavaScript to manipulate DOM elements until they've been rendered in the browser.
Put your script AFTER your HTML or check to see of the DOM is ready before running your script.
Why not use JQuery first of all...
$('#cultpicklist').val('myvaluetoselect');
Is MUCH easier to code, read and works instead of using bulky old school javascript...
Using jQuery, you could still put your code in between <head></head> tags. You would use $(document).ready() thus executing your code after the whole document has rendered.

Autofill form when link is pressed

I have this webpage. It has a page called "services.php". I have several buttons (made of classes), that belong to different "package" prices i offer.
I want the links that say "Select" to autofill a form in another page, or alternativly in a popup form in the page..
I don't really know how to explain it, but as short as possible:
When link is pressed autofill form (in this or other page) with the type of package they chose. Only text autofill
What you seem to be asking is 'loading' a page pre-filled with specific information, you can do this a number of ways, either by utilizing javascript (like jQuery for instance). Or using your PHP, make links that pass variables (say a flag or a reference to pre-fill the fields -- if you want a popup or next page, etc).
Your url would like like the following for the button that a user presses (button would be a simple http link):
http://mywebsite.com/prefill.php?user=bob&package=2
This would have the values bob as the user that requests it (you can reference an id for user info here as well), and package=2 to designate your package options.
Then on the prefill.php page, you would have something that checks for:
$user = $_GET['user'];
$package = $_GET['package'];
Hope that helps
This will populate form fields with whatever you pass to the autoFill() function. This would be a same page example.
<html>
<body>
<form>
<input type="text" id="packageDescription">
<input type="text" id="packagePrice">
</form>
<script>
function autoFill(packageDescription, packagePrice) {
document.getElementById('packageDescription').value = packageDescription;
document.getElementById('packagePrice').value = packagePrice;
}
</script>
Premium Package<br>
Platinum Package
</body>
</html>
You could do something like this:
<select id="packages">
<option value="package1">Package 1</option>
<option value="package2">Package 2</option>
</select>
Submit
When the link is clicked, the following javascript will fire off:
function submitPackage()
{
var package = $("#package").val();
window.open("http://your-site.com/some-script.php?package=" + package);
}
The above will open a pop up window to a page such as this:
http://your-site.com/some-script.php?package=package1
In some-script.php you will do something like this:
You selected the package: <b><?php echo $_GET['package'];?></b>.
Or:
<?php
//Put the packages in an array:
$packages = array();
$packages['package1'] = 'Package 1';
$packages['package2'] = 'Package 2';
//...
?>
<select id="package">
<?php foreach ($packages as $name => $text):?>
<? $selected = ($name == $_GET['package']) ? 'selected' : '';?>
<option value="<? php echo $name;?>" <?php echo $selected;?>>
<?php echo $text;?>
</option>
<? endforeach;?>
</select>
The above will auto select the package they selected in a dropdown box.
if i understood your problem, you want to fill some input fields with information when the user clicks on some links
i can think of 2 ways of doing this : either have the links point to a page like services.php?req=package1 (or any other url you want) and on that page generate the input fields with the information you need (set the default values in the fields with the ones you want), or, use javascript to change the values of the forms without changing the actual page (either via ajax or predefined values)
for javascript you can use the jQuery framework, it has a pretty extensive community of enthusiasts and plenty of examples to get you started with it.
an example for your case would be
$('#btn1').bind('click', function() {
$('#input1').val("value");
$('#input2').val("value2");
});
replace btn1 with the id of the first button or link you have, input1 with the id of the first input in your form, and value with the value you want
I just did this myself. My solution was with jQuery. Just assign an id to your link. The first ID in the code is the link id and the second is the id for the input element you want to populate.
Here is the script:
<script>
$(document).ready(function() {
$('#link_id').click(function() {
$('#input_id').val( $(this).text() ).keyup();
return false;
});
});
</script>
Hope it works!
I've ran several time into the same issue, so I had to write my own script doing this. It's called Autofiller and its pretty simple but does great job.
Here is an example
http://example.com/?autofiller=1&af=1&pof=package&package=package1
So basically it takes several parameters to init the script:
autofiller=1 - init AutoFiller
af=1 - Autofill after page is loaded
pof=package - Find the parent form element of the select with name attribute package. Works also with input form elements.
package=package1 - Will set the select element's value to package1
Hope it helps you! :)

Categories