I have a form with a select tag. I need my form to change based on the selection from the user. I am given to believe that the easiest way to do this is to use JQuery.
Here is my code:
<div class="form-group">
<label for="category" >Category</label>
<select id="category" name="category" class="form-control">
<option value="0" >Select Category</option>
<?php
$sql_cat= "SELECT * FROM category";
$result = mysqli_query($conn,$sql_cat);
$cat_items="";
if($result) {
while($cats = $result->fetch_assoc()) {
echo '<option value="'.$cats['id'].'" >'.$cats['cat_name'].'</option>';
}
} else {
echo '';
}
?>
</select>
</div>
<div id="addhtml"></div>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#category").change(function() {
alert("event triggered");
var val = $(this).val();
if (val == "number" || val == "symbol") {
$("#addhtml").html(<?php include("html/form_number.html"); ?>);
} else if (val == "letter") {
$("#addhtml").html(<?php include("html/form_letter.html"); ?>);
} else {
$("#addhtml").html(<?php include("html/form_other.html"); ?>);
}
});
});
</script>
Note: the php while statement just sets up the current three options of "number", "symbol" or "letter" with ids of 1,2 and 3 respectively
When I change the category, it does not trigger the jquery.change()
I would like to code the form without using the addhtml div but am willing to use it if necessary.
Questions:
Is the reason the change function is not being triggered because I am using php to set the values of the select options?
If so how can I resolve?
If not, why isn't it being triggered?
How can I accomplish my goal of not using the addhtml div?
Is there a better way to accomplish what I am going for?
Thanks in advance.
EDIT:
Answers to initial questions: As stated by bistoco, php is pre compiled by the server and sent in as html so the issue is not from using php to set the values of the select tag.
I have now determined that it is due to the content of my php include files. I have determined that it registers the change event and loads the content just fine if my file is simple like this:
"<div><label>New Number</label></div>"
but if I add any white space or \n characters for human readability like this:
"<div>
<label>New Number</label>
</div>"
Not only does it not work, but it also completely skips the change event.
New Questions: Does the jquery html function have a list of illegal characters that would cause it to fail? Why is it not even registering the change function when it doesn't like the contents of my php include file?
First thing that you must understand is that php runs on the server, all the output is rendered and sent as html code to the browser, and is not available there.
That said, you have at least 2 options :
1.- echo all form options, each one inside a div, that you can hide/show based on the selected choice.
<div class="form-group">
<label for="category" >Category</label>
<select id="category" name="category" class="form-control">
<option value="0" >Select Category</option>
<?php
$sql_cat= "SELECT * FROM category";
$result = mysqli_query($conn,$sql_cat);
$cat_items="";
if($result) {
while($cats = $result->fetch_assoc()) {
echo '<option value="'.$cats['id'].'" >'.$cats['cat_name'].'</option>';
}
} else {
echo '';
}
?>
</select>
<!-- ECHOING ALL FORM OPTIONS -->
<div class="option-form" id="form-option-symbol"><?php include("html/form_number.html"); ?></div>
<div class="option-form" id="form-option-letter"><?php include("html/form_letter.html"); ?></div>
<div class="option-form" id="form-option-other"><?php include("html/form_other.html"); ?></div>
</div>
<style>
div.option-form {
display:none; /* HIDE ALL DIVS BY DEFAULT */
}
</style>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#category").change(function() {
// HIDE ALL DIVS
$('div.option-form').hide();
var val = $(this).val();
if (val == "number" || val == "symbol") {
$('form-option-symbol').show();
} else if (val == "letter") {
$('form-option-letter').show();
} else {
$('form-option-other').show();
}
});
});
</script>
2.- Using a template system or load partial html pieces with ajax.
PHP Is a pre-processor so adding later into the website is useless. Just create your form with either setting its html or by using .prepend() or .append() with your form elements.
<form class="myform">
</form>
and in jquery
$('.myform').html('<input type="submit">');
or
$('.myform').append('<input type="submit"');
EDIT :
Read your code wrong looked up
<?php include('test.html'); ?>
don't think that would work.
Instead of
$("#addhtml").html(<?php include("html/form_number.html"); ?>);
and such, try
$("#addhtml").html("<?php include("html/form_number.html"); ?>");
so that the html will be treated as a string.
Also make sure the form files don't have tags such as html, head, and body, and only contain the actual form.
EDIT: I just saw that #nnnnnn already stated this, gotta give credit where credit is due
I think you might just need to change your variable "val" declaration to get your code to work.
I don't think
var val = $(this).val();
will work. Based on the comparison you are making, I believe it should be:
var val = $(this).children("option:selected").text();
which will allow you to get the text value of the select element's selected option.
Related
OK, So not a big HTML or Javascript person. But I am doing what I can to get by.
I am working on a project for a Marine Cadets Explorers Post to create a online database for them to help manage their membership and other functions. In entering their membership records they will have multiple families that will have several kids in the post, so they don't want to have to re-enter their parents records. I wanted to create a drop down box that is populated by a SQL Database lookup (Which I did) and then, if they select a parent from that list, the form will populate, saving the entry.
I only provided a snipped of the HTML, since the form has over 50 fields and for example, I only really need to show one.
So the HTML is below.
<form name="YouthApp" class="form-application" method="post" id="application-form">
<div style="height:0.20in; left:1.75in; overflow:hidden; padding:2px; position:absolute; top:4.10in; width:1.48in; ">
<select name="selSupp" style="width:1.46in;">
<option value="">Existing Supporters</option>
<?php makeSuppDropdown() ?>
</select>
<div style="height:26px; left:0.36in; overflow:hidden; padding:2px; position:absolute; top:4.52in; width:353px; ">
<input style="height:0.20in; width:3.64in; " name="SuppFirst" required value="<?php if(isset($_POST['SuppFirst'])){ echo $_POST['SuppFirst']; } ?>" maxlength="20" type="text" placeholder="First Name" >
</div>
</div>
</form>
It calls a PHP Function that populates the drop down:
function makeSuppDropdown() {
include("dbconnect.php");
$sql = "SELECT SupporterId, ".
"CONCAT(LastName, ',', FirstName,' ',MidName,' ',trim(Suffix)) as 'SuppLookup' ".
"FROM tblsupporters ".
"ORDER BY LastName, FirstName, MidName, Suffix";
$sql_result = mysqli_query($conn,$sql);
$field= mysqli_fetch_fields($sql_result);
while ($row = mysqli_fetch_array($sql_result)) {
echo ' <option value="'.$row['SupporterId'].'" >'.$row['SuppLookup'].'</option>'.chr(10);
}
}
The function provided the following output:
<select name="selSupp" style="width:1.46in;">
<option value="">Existing Supporters</option>
<option value="32517-02" >Truxton,Karla Andrianne </option>
<option value="32517-01" >Truxton,Tommie Lee </option>
</select>
If the user selects a Parent Supporter then I wanted to start filling in the input fields. This is where I am having a problem.
Here is the PHP/Javacode I am using that is not working:
<?php
if (isset($_POST['selSupp'])) {
?>
<script type="text/javascript">
document.getElementById("SuppFirst").value = "Tommie";
</script>
<?php
} ?>
Now I know that PHP and Javascript don't always play well together, but I'm hoping that there is a solution that will allow me to fill in the fields.
Thank you in advance.
I don't really understand your question, however, to the best of my knowledge, you want the users after choosing their parents' information, a form appears with filled parents' info and extra fields.
If so, i suggest creating a submit button, since I'm not sure if a drop-down select can be submitted on itself:
if ($_POST['sbm']) { //if submit button is pressed
$option = mysqli_real_escape_string($conn, $_POST['select-name']);
//Get option from the users
if ($option == '') { //If $option == '' means if there is no value
header("Location: this_file.php?error=notselected"); //Redirect to the desired page
exit();
}
else {
header("Location: this_file.php?error=noerror");
exit();
}
}
And in the desired page (the page that contains the select form), you add:
if (isset($_GET['error'] && !empty($_GET['error'])) { //Check if error parameter exists
$error = $_GET['error'];
//Get the error
switch ($error) {
case "notselected": echo "<b style=\"color:red;\">Error!</b>"; break;
case "noerror": echo "<script>$(document).ready(function(){$('input-wanted-to-show').show();});</script>"; break; //Print out the script part that you need or show the hidden input. After this php code, please go to html and add desired input fields.
}
}
Overall, I know you want to submit that select form and add javascript if it is done, so I advice is to add a submit button, add parameter when option is valid, then use $_GET to check the parameter, print out the approriate tags.
If you still want to keep the select value, use AJAX.
If there is any problem, just comment.
I will be glad to help you figure out!
I am using the javascript code below to add option values to a select field.
<script type="text/javascript">
$("#location").append($("<option></option>").val("Any Location").text("Any Location"));
$("#location").append($("<option></option>").val("Location 1").text("Location 1"));
$("#location").append($("<option></option>").val("Location 2").text("Location 2"));
</script>
This works ok but as my form is setup with PHP, I need to use the following code so that the selected value is retained in the select field when the results page is shown.
<option value="Any Location"<?php if(isset($_SESSION['location'])) { if($_SESSION['location'] == "Any Location") { echo "selected";} } ?> >Any Location</option>
Is it possible to somehow integrate the PHP SESSION code with the javascript?
Thanks
Write it as JSON:
var dataLocation = <?php
if(isset($_SESSION['location']))
{
echo '{"location" : "'.$_SESSION['location'].'"}';
}
else {
echo '{"location" : "Unknown"}';
} ?>
Now JavaScript will parse this as valid code and you can retrieve the location with: dataLocation.location;
If you execute this at the top of the script you can do this:
$("#location").append($("<option></option>").val("Any Location").text("Any Location"));
$("#location").append($("<option></option>").val("Location 1").text("Location 1"));
$("#location").append($("<option></option>").val("Location 2").text("Location 2"));
//updated version:
var selectElement = $("#location > option[value='"+dataLocation.location+"']");
if (selectElement)
{
selectElement.attr("selected", true);
}
For this to work the value of the option needs to be identical to the location set in the session.
I've written a query that takes the usernames from the database and puts them in s like this:
<?php
$username_set = get_all_usernames();
while ($username = mysql_fetch_array($username_set)){
echo "<option>" . $username['username'] . "" . "</option>";
}
?>
That works fine but now I want to add a onchange function to my tags. I've done it like this:
<select name="user_result" onChange="top.location.href = this.form.user_result.options[this.form.user_result.selectedIndex].value,'_self';">
That works fine too, it is redirecting to the selected option. But I want to select a option and stay at the same page and display the (coming) information that username contains. But for now printing the username below the would be good enough.
If you want to execute code on change of a select, it's easy to include this in a javascript function. Not sure if you want the javascript or the jquery solution, so I'll include them both.
Plain javascript:
function show_user(data) {
var el = document.getElementById("show_username").innerHTML = data;
}
jQuery solution:
function show_user(data) {
$("#show_username").html(data);
}
Then you call this function on the select change:
<select name="user_result" onchange="show_user(this.options[this.selectedIndex].value);">
<option>--select a user--</option>
<option>username</option>
<option>username 2</option>
</select>
<div id="show_username">this will update to the selected user name</div>
jsfiddle for plain javascript: http://jsfiddle.net/CwFs5/
jsfiddle for jquery: http://jsfiddle.net/5PuX3/
I want to show the drop down selected value in textbox.
This is my design.
This is my php code for drop downlist...
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("storedb", $con);
$s=mysql_query("select * from dealerdetail order by Dealer asc ");
?>
Select Dealer Name:
<select name="dealer" id="dealer">
<option value="">---- select Dealer -----</option>
<?php
while($dd=mysql_fetch_array($s))
{
?>
<option value="<?php echo $dd['D_id'] ?>"><?php echo $dd['Dealer'] ?></option>
<?php
}
?>
</select>
Please help.
I think you are looking for
$('#dealer').val(); //return selected value
$( "#dealer option:selected" ).text() // return selected options text
Use the change event and text property of select box to access the value
$('#dealer').change(function () {
$("#idOfTextBox").val($("#dealer option:selected").text());
});
use jquery:
Live demo : http://jsfiddle.net/t6YHK/25/
$('#dealer').change(function () {
$("#your_input_id").val($(this).val());
});
Use this:
$("#dealer").change(function(){
$("textarea").val( $(this).val() );
});
AngularJS
http://angularjs.org/
Scroll down to below the black area.
Seems like you're taking your first steps in web development, and for this, i strictly recommend that you stop using DreamWeaver to learn more about the code and how things go.
Each element in your web page is in the DOM (see HTML Document Object Model). So using native javascript all of your elements using :
document.getElementById("elementId")
And this is ALL what you need. All other solutions using frameworks will use this line of code whether you see this or not.
so for your specific question we will create a javascript function to be used in the event of value change of your dropdown list (assuming your text field's id is myText)
function updateMyText()
{
var dd = document.getElementById("myDropDown");
var ddtext = dd.options[dd.selectedIndex].text;
document.getElementById("myText").value = ddtext;
}
to call it when a dropdown list item is selected you need the attribute onchange
<select name="dealer" id="dealer" onchange='updateMyText()'>
I have a simple PHP script with a form that has two select fields, both of which are simply numerical values. The script also has a maximum for the sum of the two fields. I'm trying to dynamically filter the second drop down, so that a user cannot select more than the maximum. E.g., if my maximum is 10, the first select dropdown would have 1-10 in it. A user selecting 6 would then only be able to select 0-4 in the second select dropdown.
I know this should be reasonably straightforward, but I'm a total JavaScript/jQuery novice. I have searched SO and Google, but I don't understand enough of the examples I've seen to know where to start, let alone figure out how to customise them to my needs. I've provided the code I have already, which clearly doesn't have any of the filtering I need.
Some sample code (assume $maximum defined already):
<script type="text/javascript">
var max = <?php echo $maximum; ?>;
</script>
<select name="dropdown1" id="dropdown1">
<?php
for ($i = 1; $i <= $maximum; $i++)
{
echo '<option value="'.$i.'">'.$i.'</option>';
}
?>
</select>
<select name="dropdown2" id="dropdown2">
<?php
for ($i = 0; $i <= $maximum; $i++)
{
echo '<option value="'.$i.'">'.$i.'</option>';
}
?>
</select>
Thanks in advance.
I now have the following piece of jquery in it's own .js file:
$(document).ready(function() {
// var max ??
$("#dropdown1").change(function() {
var selectedVal = $(this).find("option:selected").val();
$("#dropdown2 option").removeAttr("disabled").removeAttr("selected");
$("#dropdown2 option").each(function() {
if($(this).val() > max - selectedVal*1)
$(this).attr("disabled", "disabled");
});
});
});
However, I'm a bit stuck getting $maximum from my PHP script into the jQuery. I figure I have to create a JavaScript variable, but not quite sure how to pass it to the jQuery. I can figure out how to do it if I had the jQuery embedded in the same PHP script, just by echoing it out, but not quite so sure about passing it as a parameter.
Here is a working fiddle. And, the relevant jQuery code:
$(document).ready(function() {
$("#select1").change(function() {
var selectedVal = $(this).find("option:selected").val();
$("#select2 option").each(function() {
if($(this).val() >= selectedVal)
$(this).attr("disabled", "disabled");
});
});
});
I update code of legendofawesomeness for your case