form select object dynamically changing class name with php and javascript? - php

Having some trouble here with this.
The setup:
A select object with a choice of "Other"
User selects "Other".
Script runs when this specific value is chosen, and dynamically changes the class of input object from "hide" to "show" (hidden and visible with css display).
<p>Select a Grade:</p>
<select name="grade" id="grade" onchange="changeCssClass('otherGrade')">
<option value="No Specified Grade">Please Select</option>
<option value="201">201</option>
...
<option value="Secondary">Secondary</option>
<option value="otherGrade">Other</option>
</select>
<p>If "Other":</p>
<?php
$otherGrade = $_POST['grade'];
if($otherGrade = "otherGrade")
{
echo("<script language='javascript' type='text/javascript'>
function changeCssClass(objInputID)
{
if(document.getElementById(objInputID).className=='hide')
{
document.getElementById(objInputID).className = 'show';
}
else
{
document.getElementById(objInputID).className = 'hide';
}
}
</script>");
}
else
{
echo ("");
}
?>
<input type="text" name="otherGrade" id="otherGrade" class="hide" />
Should I remove the onchange event from the select object? If so, I am at a loss as how to have the script executed.
Any solutions would be greatly appreciated.

The script should always be included in your page, since you want this to run while you make the changes in the dropdown list..
<script language='javascript' type='text/javascript'>
function changeCssClass(objInputID, currentVal, correctVal)
{
if(correctVal == currentVal)
{
document.getElementById(objInputID).className = 'show';
}
else
{
document.getElementById(objInputID).className = 'hide';
}
}
</script>
<p>Select a Grade:</p>
<select name="grade" id="grade" onchange="changeCssClass('otherGrade', this.value, 'otherGrade')">
<option value="No Specified Grade">Please Select</option>
<option value="201">201</option>
...
<option value="Secondary">Secondary</option>
<option value="otherGrade">Other</option>
</select>
<p>If "Other":</p>
<input type="text" name="otherGrade" id="otherGrade" class="hide" />
Live example at : http://www.jsfiddle.net/MVymF/

why are you putting this in the post event? you can just render this as standard javascript as part of the page.

On post , the page will be refreshing , ad on reloading you are not saving the selected value of the select box.
The select box is not keep selected after posting. You have to do that.
>Other
As the value of option change the display hide also gone.
Fix that
If no need to submit the page . use this
http://api.jquery.com/val/
check demo of select

Related

Having trouble validating the <select> element within a larger <form> element - it won’t return an error message

I’ve been building a series of webpages that allows for dynamic data manipulation (CRUD). The pages are built with HTML, CSS, and PHP.
At this stage of the project, my goal is to have the site return an error message if data is not entered into a particular field.
I've made a small sandbox for the problem.
At the top of the page, I included the following PHP logic to outline the variables and how the page will behave if data is entered into the form fields (or not entered):
$routeType = "";
$hasRouteType = false;
$routeTypeError = false;
if( isset($_POST["add"]) ) {
if( isset($_POST['route-type']) ) {
$routeType = $_POST['route-type'];
if($routeType) {
$hasRouteType = true;
} else {
$routeTypeError = "Please select a route type.";
}
}
}
I made a dropdown menu as one of the elements in the form as follows:
<form method='POST'>
<field>
<label>Route Type</label>
<select name="route-type" id="route-type">
<option value="" selected="true" disabled="disabled">What type of route is this?</option>
<option value="interstate">Interstate</option>
<option value="stateRoute">State Route</option>
<?php if($routeTypeError) { ?>
<p class='error'><?=$routeTypeError?></p>
<?php } ?>
</select>
</field>
<form>
<button class='route-button' type="submit" name='add'>Add route</button>
At this stage, when the user doesn't choose anything from the dropdown, no error message is returned -- again, this is the goal of this stage of the project.
Steps I've tried to solve the problem so far (these didn't work)
I’ve tried changing the logic in the principal foreach statement.
if($routeType) {
$hasRouteType = true;
if($routeType != "") {
$hasRouteType = true;
I’ve tried changing the data type of the $routeType variable when it's initialized.
I’ve tried adding selected=“true” and disabled=“disabled” to the top element in the dropdown menu to make it the first thing that appears on the page — and also to make it impossible for the user to select it as an option from the menu.
<option value="" selected="true" disabled="disabled">What type of route is this?</option>
I've been told that "looping through the option elements" might be a possible solution, but I don't know how to implement this.
My goal is to have the error message "Please select a route type." returned if the user does not select anything from the dropdown menu.
Thanks very much for the help!
You need an option field with empty value and the required.
Solution with client-side check
<select name="route-type" id="route-type" required="required">
<option value="">What type of route is this?</option>
<option value="A" >Select A</option>
<option value="B" >Select B</option>
</select>
You don't need php for this.
Try to submit this without select a value and you will get an error message.
All html and javascript checks are just goodies, you always have to check all values ​​with php(when you use php) when you get them from a form.
Never trust any data and check every data you receive!
UPDATE:
Maybe this is a possible solution you looking for with php:
Solution with php check
<?php
$route_check = array(
'interstate'
,'stateRoute'
);
if(!in_array($_POST['route_type'] ?? '' , $route_check)){
?>
<form method="post">
<select name="route_type">
<option value="">SELECT A TYPE</option>
<option value="interstate">interstate</option>
<option value="stateRoute">stateRoute</option>
</select>
<input type="submit">
</form>
<?php
}
else{
echo "DO SOMETHING";
}
?>
If you wan't to check with the required option also on the client-side use:
<select name="route_type" required="required">
You can also build your option fields with a loop and use the values from the array.
Solution with php check and custom error message(javascript alert):
<?php
$route_check = array(
'interstate'
,'stateRoute'
);
if(!in_array($_POST['route_type'] ?? '' , $route_check)){
if( ($_POST['SEND'] ?? '') === 'SEND'){
echo "<script>alert('Please select type')</script>";
}
?>
<form method="post">
<select name="route_type">
<option value="">SELECT A TYPE</option>
<option value="interstate">interstate</option>
<option value="stateRoute">stateRoute</option>
</select>
<input type="submit" name="SEND" value="SEND">
</form>
<?php
}
else{
echo "DO SOMETHING";
}
?>
Solution with php check and custom error message(php in option field):
<?php
$route_check = array(
'interstate'
,'stateRoute'
);
if(!in_array($_POST['route_type'] ?? '' , $route_check)){
if( ($_POST['SEND'] ?? '') === 'SEND'){
$MESSAGE = 'NO TYPE SELECTED';
}
else{
$MESSAGE = 'SELECT A TYPE';
}
?>
<form method="post">
<select name="route_type">
<option value=""><?php echo $MESSAGE; ?></option>
<option value="interstate">interstate</option>
<option value="stateRoute">stateRoute</option>
</select>
<input type="submit" name="SEND" value="SEND">
</form>
<?php
}
else{
echo "DO SOMETHING";
}
?>
This is just a small example of how it could work, of course you can further optimize and adapt the code

How to have an HTML input field appear when the value 'other' is selected with PHP

What I am trying to figure out is how to have an html input field appear when the value of other is selected from a dropdown menu. Right now the values for the dropdown list are coming from the results of a MySQL DB query, which works, but I can not seem to figure out how to get an input to appear when I select the other option.
$query = mysql_query("SELECT type FROM Dropdown_Service_Type"); // Run your query
echo '<select name="service_type">'; // Open your drop down box
echo '<option value="NULL"></option>';
// Loop through the query results, outputing the options one by one
while ($row = mysql_fetch_array($query)) {
echo '<option value="'.$row['type'].'">'.$row['type'].'</option>';
}
echo '<option value="Other">Other</option>';
echo '</select>';// Close your drop down box
Use javascript, like in the example below. We can add an input field and have it hidden by default, using the style attribute:
<input name='otherInput' id='otherInput' type="text" style="display: none" />
var otherInput;
function checkOptions(select) {
otherInput = document.getElementById('otherInput');
if (select.options[select.selectedIndex].value == "Other") {
otherInput.style.display = 'block';
}
else {
otherInput.style.display = 'none';
}
}
<select onchange="checkOptions(this)" name="service_type" id="service_type">
<option value="NULL"></option>
<option value="43">43</option>
<!-- other options from your database query results displayed here -->
<option value="Other">Other</option>
</select>
<!-- the style attribute here has display none initially, so it will be hidden by default -->
<input name='otherInput' id='otherInput' type="text" style="display: none" />
There are 3rd party libraries like jQuery, AngularJS, PrototypeJS, etc., which can be used to make the code simpler by adding shortcut methods for DOM manipulation (though you should read this post). For example, with jQuery, using .on() (for the event handler binding), .show() and .hide() for the input display toggling, etc:
var otherInput;
var serviceTypeInput = $('#service_type');
serviceTypeInput.on('change', function() {
otherInput = $('#otherInput');
if (serviceTypeInput.val() == "Other") {
otherInput.show();
} else {
otherInput.hide();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="service_type" id="service_type">
<option value="NULL"></option>
<option value="43">43</option>
<option value="Other">Other</option>
</select>
<input name='otherInput' id='otherInput' type="text" style="display: none" />
$(function() {
$('#sample').change(function() {
var val = this.value; // get the value of the select.
if (val == 'other') { // if the value is equal to "other" then append input below the select
$('html').append('<input type="text" id="inputOther"/>');
} else { // else then remove the input
$('#inputOther').remove();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="sample">
<option value="test1">test1</option>
<option value="test2">test2</option>
<option value="test3">test3</option>
<option value="other">other</option>
</select>

How to link a HTML <select> list with a submit button

I have a webpage which consists of a select list with 6 options, along with a submit button. I need to code it in such a way that when one option is selected in the list and the submit button is clicked, it should open another linked page, whereas when another option is selected and submit button is clicked it should open some another page.
Basically I want each option to open some linked page when the submit button is clicked.
By googling a bit, I understood that I have to use php for this but I am not getting the appropriate code for the same.
I do not want the submit button to open only 1 specific page. Rather,I want it to open 6 different pages corresponding to different options selected.
Code Snippet :
<div>
<H1><FONT="TIMES ROMAN" FONT-COLOR="BLUE" > SELECT An subject:</H1>
<select>
<option value=""></option>
<option value="physics">physics</option>
<option value="chemistry">chemistry</option>
<option value="biology">biology</option>
<option value="maths">maths</option>
<option value="cs">cs</option>
<option value="electrical">electrical</option>
</select>
<br>
<input class="SubmitButton" type="submit" name="SUBMITBUTTON" value="Submit" style="font-size:20px; " />
</div>
Also i have learnt that it cannot be done using href tag because an option list cannot directly open pages, a submit button is required to perform an action.
Need help to resolve this.
I think ts wants to open multiple window according to selected values.
So here is example:
<div>
<H1>SELECT An subject:</H1>
<form id="link">
<select multiple="multiple">
<option value="">Choose links</option>
<option value="http://stackoverflow.com/">Stackoverflow</option>
<option value="http://google.com/">Google</option>
<option value="http://yahoo.com/">Yahoo</option>
<option value="http://bing.com/">Bing</option>
<option value="http://php.net/">PHP official</option>
<option value="http://w3c.org">W3C</option>
</select>
<br>
<input class="SubmitButton" type="submit" name="SUBMITBUTTON" value="Submit" style="font-size:20px; "/>
</form>
</div>
<script src="http://code.jquery.com/jquery-3.0.0.min.js"></script>
<script>
$('#link').on('submit', function (e) {
e.preventDefault();
var $form = $(this),
$select = $form.find('select'),
links = $select.val();
if (links.length > 0) {
for (i in links) {
link = links[i];
window.open(link);
}
}
});
</script>
First, you must set multiple attribute to select. Then via jquery you can open each link in new popup. Be careful browsers may block this popups.
UPDATE
If you want to open just one window, you can use #Anant's solution
Simplest solution based on jquery:-
<div>
<H1><FONT="TIMES ROMAN" FONT-COLOR="BLUE" > SELECT An subject:</H1>
<select id ="dropDownId"> <!-- give an id to select box-->
<option value="">Select Option</option>
<option value="physics">physics</option>
<option value="chemistry">chemistry</option>
<option value="biology">biology</option>
<option value="maths">maths</option>
<option value="cs">cs</option>
<option value="electrical">electrical</option>
</select>
<br>
<input class="SubmitButton" type="submit" name="SUBMITBUTTON" value="Submit" style="font-size:20px; " />
</div>
<script src = "//code.jquery.com/jquery-3.0.0.min.js"></script> <!-- add jquery library-->
<script type = "text/javascript">
$('.SubmitButton').click(function(){ // on submit button click
var urldata = $('#dropDownId :selected').val(); // get the selected option value
window.open("http://"+urldata+".html") // open a new window. here you need to change the url according to your wish.
});
</script>
Note:- This code will do below things:-
1.Select box page is never refreshed.
2.Based on selected value your URL'S are open in new window.
3.Also you can change URL format according to your requirement. I just gave a sample example.
Add this script in your html code
function showPage() {
var sel = document.getElementById('subjects');
var option = sel.options[sel.selectedIndex].value;
window.open(option + ".html");
}
and copy below html code and replace with yours
<select id="subjects">
<option value=""></option>
<option value="physics">physics</option>
<option value="chemistry">chemistry</option>
<option value="biology">biology</option>
<option value="maths">maths</option>
<option value="cs">cs</option>
<option value="electrical">electrical</option>
</select>
<input class="SubmitButton" type="button" value="Submit" onclick="showPage()" style="font-size:20px; " />
hope this helps :)
You can do this with PHP, but you will need to do 2 things:
Put the select and input into a form in your HTML, like this:
<form action="" method="post">
<select name="opt">
<option value="1">Link 1</option>
<option value="2">Link 2</option>
<!-- etc -->
</select>
<input type="submit" name="submit">Submit</input>
</form>
Have PHP catch the form's POSTed data and redirect to the appropriate page, like this: (put this at the top of your PHP page with the form)
<?php
if (isset($_POST['submit']))
{
if (isset($_POST['opt']))
{
if ($_POST['opt'] == '1') { header('Location: page1.php'); }
elseif ($_POST['opt'] == '2') { header('Location: page2.php'); }
// etc...
}
}
?>
Header redirects only work if there has been no HTML output before they're called, so make sure there's no HTML code before the PHP code block.

Show input box o if value from drop down menu is selected

I'm working on a simple php contact form and struggling to get the "other" selection on the dropdown to show a text field option when it's selected. The form is included onto the page with <?php require_once('includes/contact_form.php'); ?> and the footer is also an include (the footer is where I have added the JS).
But it just wont work...
Here is the Form:
<label>How did you hear about us?</label>
<select name="how" class="selectfield" id="how">
<option value="">Please Select...</option>
<option value="Advertisement">Advertisement</option>
<option value="Care at Home Today">Care at Home Today</option>
<option value="Email-Newsletter">Email/Newsletter</option>
<option value="Facebook">Facebook</option>
<option value="Family-Friend">Family or Friend</option>
<option value="Magazine">Magazine Article</option>
<option value="Twitter">Twitter</option>
<option value="Website-Search Engine">Website/Search Engine</option>
<option value="Other">Other</option>
</select>
<input type='text' id="other" class="hidden" />
<input name="contactus" type="submit" class="submit" id="contactus" value="Submit" />
</form>
Here is the JS
$('#how').change(function(){
var selected_item = $(this).val()
if(selected_item == "other"){
$('#other').val("").removeClass('hidden');
}else{
$('#other').val(selected_item).addClass('hidden');
}
});
Not sure if it is a typo in the question but your dropdown value is "Other" and in your js you are testing for "other". So there is a mismatch. Might be your issue
Here is a working fiddle of your example just changing the "other" to "Other" in your if statement.
DEMO
As coder1984 has suggested though, simply using jquery's .show() and .hide() in your if
statement would also work.
if(selected_item == "Other"){
$('#other').val("").show()
}else{
$('#other').val(selected_item).hide()
}
Your problem is in your string comparison, it should be:
if(selected_item == "Other"){
With the Uppercase O, Tested
Try:
$('#how').change(function(){
var selected_item = $(this).val()
if(selected_item == "Other"){ // 'Other'
$('#other').val('').show(); //show textbox if Other is selected
}else{
$('#other').hide(); //Hide textbox if anything else is selected
}
});

How to change a text box to visible depending on what item is selected in a drop down menu?

I have a drop-down menu with a list of school subjects in it, the last option is "Add New Subject" so when the user selects that option, I need a text box to appear.
My HTML form looks like this: (I have only included the relevant bits, there is a bit more stuff on it.
<form method="post" action="createQuestion.php" name="cq">
<select name="subject" id="subject">
<option value="biology">Biology</option>
<option value="maths">Maths</option>
<option value="economics">Economics</option>
<option value="newSub" <?php if($subject == "newSub1") { echo "SELECTED"; } ?>>
Add New Subject
</option>
</select>
<input type="text" name="newSubtxt" ID="newSubtxt" style="visibility:hidden">
</form>
I have spent ages trying to get this to work with javascript, and I just can't get it to work at all.
This is the js I wrote, but doesn't work
function addSubject(){
const newSub = document.getElementById('newSub').name;
const selectedSubject = document.getElementById('subject').value;
if (selectedSubject === newSub){
document.getElementById(newSubtxt).style.display = 'block';
}
}
I would be so grateful if someone could help me out with the javascript, so that it will work. Thanks in advance :)
Change your invisible input to:
<input type="text" name="newSubtxt" id="newSubtxt" style="display: none" />
and your js:
function addSubject() {
var selectedSubject = document.getElementById('subject').value;
if (selectedSubject == 'newSub') {
document.getElementById('newSubtxt').style.display = 'block';
}
}
Also see my jsfiddle.
Change the style of textbox with
<input type="text" name="newSubtxt" ID="newSubtxt" style='display:none;'>
I have used jQuery (javascript library) to solve your problem.
$(document).ready(function () {
$('#subject').change(function (){
if($('#subject').val()=='newSub')
$('#newSubtxt').show();
else
$('#newSubtxt').hide();
});
});
See my jsfiddle

Categories