I have got a form (php in html or the other way around). Once user selects an option in a drop down list, it would get the input value and create a few text boxes. It seems like I have to use onchange(). How do I read the input and perform logics within the script inself? Instead of opening another .php script?
Currently this is what I have.
<?php
$tables = $_POST["tables"];
?>
<html>
<body>
<form method="post" action="<?php echo $PHP_SELF;?>">
Table Name: <div id="tables">
<select name="tables">
<option value="Applications">Application</option>
<option value="Device">Device</option>
</select>
</div>
</form>
<?
echo "".$tables."";
?>
You can't interact with PHP once the HTML is sent to the browser without either
Refreshing the page, or
Using AJAX (JavaScript).
If you know the options in the <select> beforehand (which it seems like you do), you should write some JavaScript to accomplish what you need. Here is a simple example using jQuery.
$('#tables_select').change(
function( eventObject ){
alert('You chose ' + $(this).val());
switch( $( this ).val())
{
case 'Applications':
$('#tables').append('<input type="text" name="application_name" value="Enter an application name" />"');
break;
case 'Device':
$('#tables').append('<input type="text" name="device_name" value="Enter a device name" />"');
break;
}
}
);
You will need to add additional logic to remove the inserted elements if the user changes their choice, and to insert the correct <input> elements when the page first loads, but it is a good starting point.
if you want to add any input type ... here is the demo demo with code
you use following method.
<form method="post" action="<?php echo $PHP_SELF;?>" onChange="return createTxtbox()">
Table Name: <div id="tables">
<select name="tables">
<option value="Applications">Application</option>
<option value="Device">Device</option>
</select>
</div>
<span id="fooBar"> </span>
</form>
then write javascript,
<SCRIPT language="javascript">
function createTxtbox() {
var type="text";
//Create an input type dynamically.
var element = document.createElement("input");
//Assign different attributes to the element.
element.setAttribute("type", type);
element.setAttribute("value", type);
element.setAttribute("name", type);
var foo = document.getElementById("fooBar");
//Append the element in page (in span).
foo.appendChild(element);
}
</SCRIPT>
Related
Got a simple form made of a text input and a option select input. When submititing, Firebug shows me that on POST no value from the option input has been sent, only the value from the text one. After checking other similar questions, don't find any spelling mistake...
FORM:
<form id="turn_conf" method="POST" action="config/forms/turn_conf/turn_insert.php">
<div class="smartFormContent">
<p class="inputForm">
<label for="nombre">Nombre:</label>
<input id="tu_name" class="" type="text" value="" name="tu_name">
</p>
<p class="inputForm">
<label for="tipo">Tipo turno:</label>
<select id="tu_type" class="" name="tu_type">
<option value="1">Mañana</option>
<option value="2">Tarde</option>
<option value="3">Noche</option>
</select>
</p>
<input class="smartFormSubmit" type="submit" value="Crear" name="submit">
</div>
</form>
Firebug shows posted data as:
FIY: this POST form is sent by jQuery, here is the code:
function validaDatos(e)
{
var turnName = $('input[name=tu_name]').val();
var turnType = $('input[name=tu_type]').val();
$.post($(this).attr('action'), { tu_name:turnName, tu_type:turnType }).success(feedback);
var emptyRow='<div class="tableRow newRow"><div class="contentColumn60"><span class="tableContentText"></span></div><div class="contentColumn20"><span class="tableContentText"></span></div><div class="contentColumn10"><div class="tableIconLink"></div></div><div class="contentColumn10"><div class="tableIconLink"></div></div></div>';
$(emptyRow).prependTo('.tableContent').hide().slideDown(500);
messageInsert();
e.preventDefault();
}
function feedback (datos) {
var content= datos;
$('.newRow').html(datos);
}
There are duplicate FORM tags:
<form method="POST" action="config/forms/turn_conf/turn_insert.php" id="turn_conf">
<form id="turn_conf" method="POST" action="config/forms/turn_conf/turn_insert.php">
This will probably cause the browser not to post the data properly.
The two FORM tags also share the same ID which is not permitted id="turn_conf".
var turnType = $('input[name=tu_type]').val()
tu_type is not an input, is a select. This will work:
var turnType = $('select[name=tu_type]').val()
hy, i have a problem with a form. i know the question is simple but i can not have a solution. Well, this is my form:
<form id="search" method="post" action="cerca_redirect2.php" >
<select id="tipo" name="tipo"class="chzn-select" style="width:165px;" tabindex="1" >
<option value="http://case.vortigo.it/vendita-immobili/index.php"> Vendita</option>
<option value="http://case.vortigo.it/affitto-immobili/index.php">Affitto</option>
</select>
<input id="field" name="field" type="text" value=""/>
<input id="submit" type="submit" value="" />
</form>
my goal is when i select "Vendita" and i submit the form i have to go to the url in the select "Vendita", for each select. someone can help me? thanks
In the server side php code, do something like this
if (isset($_POST['tipo']) && !empty($_POST['tipo']))
{
header('Location: ' . $_POST['tipo']);
}
Note: This is a very basic version, you will want to ensure the url is valid by either maintaining a list of urls on the server, or something similar.
There are many different ways, but you can for example use following:
See the onsubmit part in the form definition
<form id="search" method="post" action="cerca_redirect2.php" onsubmit="this.action=document.getElementById('tipo')[document.getElementById('tipo').selectedIndex].value" >
If I understan your question correctly, you need a way to change the action value to the selected option's value
this is how to do that
$(document).ready(function(){
$("#tipo").on("change", function(){
$("#search").attr("action", $(this).val());
});
});
DEMO: http://jsfiddle.net/6ybMP/
You want to change the action of the form based on the select? The following should be along the lines of what you want.
$('#tipo').on('change', function() {
var newAction = this.val();
$('#search').prop('action', newAction);
}
UPDATE
You will want to wrap this code in $(document).ready() so that the event will be registered after the DOM has been loaded.
Like so:
$(document).ready(function() {
$('#tipo').on('change', function() {
var newAction = this.val();
$('#search').prop('action', newAction);
}
});
This is my js code:
function check() {
var delvar = "<? $_POST["del"]; ?>";
var answer = confirm("Are you sure you want to delete the article?")
if (answer) {
window.location = "adm-site.php?del=" + delvar + "&delete=true";
}
}
Now, my problem is that the delvar does not work. so the url is just ?del=&delete=true , instead of e.g. ?del=testarticle&delete=true
EDIT: My $_POST["del"] is a select tag with all the articles in it, so you will choose which to delete
The HTML code:
<select name="del">
<option value="none" SELECTED></option>
all articles echo'ed here by php
</select>
I believe you want this scenario:
User gets a page with a form containing the select tag having all the articles as values/options.
User selects an article, which he/she wants to delete.
User clicks a button.
Then you want to redirect user to URL adm-site.php?del=02&delete=true.
So, in this case, only JavaScript is getting the value of selected article value and embedding it in the redirect URL. So, PHP can do nothing here. All the action is happening client-side.
Try this HTML code:
<html>
<head>
<script language="JavaScript">
function check(){
var delvar=document.form1.del.options[document.form1.del.selectedIndex].value;
//alert(delvar); //debug
var answer = confirm("Are you sure you want to delete the article?")
if (answer) {
//alert("adm-site.php?del=" + delvar + "&delete=true");
window.location = "adm-site.php?del=" + delvar + "&delete=true";
}
}
</script>
</head>
<body>
<form name="form1">
<select name="del">
<option value="none" SELECTED>None</option>
<option value="01">Article 01</option>
<option value="02">Article 02</option>
<option value="03">Article 03</option>
</select>
<input type="button" value="Delete This Article" onclick="check();">
</form>
</body>
</html>
LIVE Demo at JSFiddle.net (Alerting the Redirecting URL)
Things I have edited/changed:
Added a name to form tag.
Changed the way var delvar is assigned the value of currently selected article.
Else all is same code as yours.
As mentioned by Pheonix, A bit secure code, doing the same thing as the above one, but by using $_POST. You need to use $_POST array instead of $_GET in your adm-site.php.
<html>
<head>
<script language="JavaScript">
function check(){
var delvar = document.form1.del.options[document.form1.del.selectedIndex].value;
var agree = confirm("Are you sure you want to delete Article " + delvar + " ?");
if (agree)
return true ;
else
return false ;
} //function check() ENDS
</script>
</head>
<body>
<form name="form1" action="adm-site.php" method="POST">
<select name="del">
<option value="none" SELECTED>None</option>
<option value="01">Article 01</option>
<option value="02">Article 02</option>
<option value="03">Article 03</option>
</select>
<input type="hidden" name="delete" value="true" />
<input type="submit" name="submit" value="Delete this Article" onClick="return check();" />
</form>
</body>
</html>
Demo at JSFiddle.net
var delvar = '<?php echo $_POST["del"]; ?>';
note the <?php instead of the discouraged shortcode too.
Your HTML contains " so you need to surround the PHP with single apostrophes. And if you're using the short tag, use it right. So in the end, it should look like this:
var delvar = '<?= $_POST["del"]; ?>';
Here's another way to think about it: make a link to the page you want to be sent to, and then give it an onclick like this:
<a href="/adm-site.php?del=<?php echo $_POST['del']; ?>&delete=true" onclick="return confirm('Confirm Deletion?')" >Delete</a>
This works, but it might not fit into your environment, depending on what triggers check().
var delvar = "<? $_POST["del"]; ?>";
You are trying to combine javascript and php but we don't have that type of possibility because javascript is client side scripting language, PHP is server side scripting language.
There is another way to combine javascript & php. Please refer this link.
I have a requirement for adding values selected in a select box to a input box with the same form and am not sure how to best go about this. The select box contains user email addresses and the input box needs to contain multiple email addresses. The idea is that when you select a email address from the select box it is then added to the input either automatically, or by clicking the add button which reload the page in PHP adding to a variable that is the value of the input box. I have tried to do this by having a form within a form but that does not work is there a better way of doing this?
Many thanks.
Well, in the select's onchange event, set the inputs value to all of the selected options concatenated together.
Here's some psuedo-code:
on select changed {
str= ''
for every element
if checked
str = str + value + ','
set input's value to the variable str
Again in jQuery:
$('select').onchange(function(){
str='';
$('option:selected').each(function(){
str+=this.value+','; });
$('input:text').value(str); });
Edit: Here's what you wanted, without multi-select.
$('select').onchange(function(){
$('option:selected').each(function(){
$('input:text').val($('input:text').val()+$(this).val()+',');})
.removeAttr('selected'); });
You can try this:
Write this code in the top of the page before DOCTYPE.
<?php
if(isset($_POST['add']))
{
$previous_email = $_POST['txt_email'];
$emails = $_POST['select_email'].",".$previous_email;
}
else
{
$emails = '';
}
?>
The javascript: you can put it in the head section of your html document
<script>
function add_email()
{
document.getElementById('txt_email').value = document.getElementById('select_email').value +','+ document.getElementById('txt_email').value;
}
</script>
And finally the html:
<body>
<form method="post" action="" name="myform">
<select name="select_email" id="select_email" onchange="add_email();">
<option value="email1#test.com">email1#test.com</option>
<option value="email2#test.com">email2#test.com</option>
<option value="email3#test.com">email3#test.com</option>
</select>
<textarea name="txt_email" id="txt_email"><?=$emails;?></textarea>
<input type="submit" value="add" name="add"/>
</form>
</body>
Hope it helps
I have several questions regarding forms and PHP but if I should put them into different posts then I will.
Here is my form code:
<form id="t-form" name="tForm" action="translate.php" method="POST">
<div id="t-bar">
<div class="t-select">
<select name="start-lang" id="choice-button">
<option value="english">English</option>
</select>
<label>into</label>
<select name="end-lang" id="choice-button" onChange="document.forms['tForm'].submit();">
<option value="caps"<?php if ($resLang == 'caps') echo ' selected="selected"'; ?>>CAPS</option>
<option value="lowercase"<?php if ($resLang == 'lowercase') echo ' selected="selected"'; ?>>lowercase</option>
</select>
<input type="submit" id="t-submit" value="Translate">
</div>
</div>
<div id="t-main">
<textarea id="txt-source" name="t-src" autofocus="autofocus" placeholder="Type in what you would like to convert…" onChange="document.forms['tForm'].submit();"><?php echo $source; ?></textarea>
<input type="button" id="t-clear" onclick="this.form.elements['t-src'].value=''">
<textarea id="txt-result" name="txt-result" readonly disabled="disabled" placeholder="result..."><?php echo $result; ?></textarea>
<input type="button" id="t-copy" name="t-copy">
</div>
</form>
Question 1: I currently have onclick="this.form.elements['t-src'].value=''" which clears one textbox when the button is pressed. Is it possible to have the same attribute clear both textareas in my form? I can't seem to find an answer anywhere for clearing 2 elements with 1 button. I do not want to clear the form as I would like to keep the selected dropdown values so that is why I'm doing it this way.
Question 2: How would I go about implementing a live refresh of the results textarea so they user can simply type and see the result? I've look at the ajax and jquery required and am confused as most don't show how to output to a form element and only to a div. (Similar to google's translate)
Question 3: I realized that if a user does a new line in the textarea, when they submit for translate, it gives them a php header error. Any ideas how I can avoid this? This is my header for the translate.php file used in the form:
header("location: /?txt-result=$result&t-src=$textSource&end-lang=$outputLang");
I am merely trying to do this as a learning excersise and would really appreciate any guidance or answers to the three questions. Many thanks for your help!
question 1
you should have:
onclick="clearTextboxes();"
and in javascript something like:
//if you want to delete all the inputs that are of type text
function clearTextboxes(){
var inputs = document.getElementById('t-form').getElementsByTagName('input');
for (var control in inputs){
if(inputs[control].getAttribute('type') == 'text'){
inputs[control].value = '';
}
}
}
question 2
it is far too broad to put here as an answer, you should really look at jQuery's $.ajax, and create a different question with specific doubts.
question 3
use the PHP urlencode() function
Answer 1: Have your onclick event call a function which clears those values for you:
<script type="text/JavaScript">
function clearTextareas()
{
this.form.elements["t-src"].value = "";
this.form.elements["txt-result"].value = "";
}
</script>
<input type="button" id="t-clear" onclick="clearTextareas()">
Answer 2: Add an onkeydown event in the source textarea that peforms the translation (or whatever it needs to do) and then puts the result in the result textarea:
<script type="text/JavaScript">
function translateText()
{
var text = this.form.elements["t-src"].value;
// do something
this.form.elements["txt-result"].value = text;
}
</script>
<textarea id="txt-source" name="t-src" autofocus="autofocus" placeholder="Type in what you would like to convert…" onkeydown="translateText()"><?php echo $source; ?></textarea>
Answer 3: Perhaps an onsubmit event in the form element that will sanitize the input from the text area. Have a look at JavaScript's encodeURIComponent. Perhaps this will work for you:
<script type="text/JavaScript">
function sanitize()
{
this.form.elements["t-src"].value = encodeURIComponent(this.form.elements["t-src"].value);
}
</script>