Questions regarding forms and php (clearing form, live refresh, multiline) - php

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>

Related

PHP: change page action of a form by url in select

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);
}
});

One submit button to send form data to one PHP destination OR another

I' new to HTML and PHP and was wondering if anyone out there could help me with a question... I'm trying to code a form that submits a selection from one menu OR another and, depending on which is chosen sends the data to one of two different PHP pages.
<form id="form1" method="post" action="">
<label for="SubjectID">Text Books by Subject</label>
</p>
<p>
<select "name="SubjectID" id="SubjectID">
<?php do { ?>
<option value="<?php echo $row_rsSubject['SubjectID']?>"><?php echo $row_rsSubject['SubjectName']?></option>
<?php } while ($row_rsSubject = mysql_fetch_assoc($rsSubject));
$rows = mysql_num_rows($rsSubject);
if($rows > 0) {
mysql_data_seek($rsSubject, 0);
$row_rsSubject = mysql_fetch_assoc($rsSubject);
} ?>
</select>
</p>
<p>
——— OR ———
</p>
<p>
<select name="CourseID" id="CourseID">
<?php do { ?>
<option value="<?php echo $row_rsCourse['CourseID']?>"><?php echo $row_rsCourse['CourseID']?></option>
<?php } while ($row_rsCourse = mysql_fetch_assoc($rsCourse));
$rows = mysql_num_rows($rsCourse);
if($rows > 0) {
mysql_data_seek($rsCourse, 0);
$row_rsCourse = mysql_fetch_assoc($rsCourse);
} ?>
</select>
</p>
<p>
<label for="CourseID">Text Books by Course</label>
</form>
So, the action should be (depending on which menu the user selects from) that the form submits to either subject.php or course.php, and I can't figure out how to do that with a single submit button. Can anyone help me?
first set onchange event to select:
<select name="CourseID" id="CourseID" onchange='myFunc(this)'>
Then:
<script>
function myFunc(element){
// set the form action depends on option chosen
// element.setAttribute('action', 'yourPageLink' );
}
</script>
You could update the action attribute with javascript when the user changes his selection, directing him to the relevant page.
Otherwise, why not submit to a single function and depending on the users selection call the relevant function?
Honestly I would use jquery's $.post to do this. To the best of my knowledge you can't really do that with straight html, and php is executed before the page loads so that's no help. With JQuery you could set an action to the button to call a function. Then your function could check the value of the select and pass the proper url to the $.post function.
You can read about that particular jquery function here: http://api.jquery.com/jQuery.post/
If you're not familiar with JQuery it's really easy to use with just a bit of reading if you're good with JavaScript.
Why not have a radio button in the form whose posted form value is processed by a central PHP form handler? That way, depending on what is entered on the radio button, you can process the request as necessary.
This might not be the answer you are looking for, but I am not clear if you want the user to be able to alter the destination or what.

Change link url with value from dropdown list

I'm trying to change a series of links by inserting values from a dropdown box. I found this straight forward to do with php (code below) but I'd like to be able to change the links without 1) having a page refresh (these links are near the bottom of the homepage) and 2) without a submit button if possible.
Here is the php code:
<form name="test" action="<?php echo
htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<select name="county" id="select13">
<option value="All">All</option>
<option value="County1">County1</option>
<option value="County_2">County 2</option>
...
</select>
<input type="submit" name="submit" value="Set County">
</form>
<?php
if(isset($_POST['submit']))
{
$county = $_POST['county'];
$www = "http://www.website.com/";
$food = "/topics/Food/programs.aspx";
$meals = "/topics/Meals/programs.aspx";
....
echo "<a href=$www/$county/$food>Food</a><br>";
echo "<a href=$www/$county/$meals>Meals</a><br>";
The above code works fine, but requires a page refresh. I was attempting to use jquery to just take a list of links, such as:
Food
And just replace "county" with the value from a dropdown box.
function changelinks(){
var countyvals = $("#county").val();
$("a[href^='http://www.webpage.com/topics/']")
.each(function(){
this.href = this.href.replace(/^http:\/\/www\.webpage\.com\/topics\//,"http://www.webpage.com/topics/"+countyvals);
});}
The above code works fine changing the link once, but after the link is changed I can't target the links anymore. I just started teaching myself jquery today, so I've no idea where to look for a better solution.
What might be the best way of changing these links?
Should I try some ajax on the php code, or is there a better/simpler solution through jquery?
THANKS!
I would use HTML 5 data attributes. Have a data-relativeurl attribute on each anchor of interest, then you can use
function changelinks(){
var countyvals = $("#selector13").val();
$("a[href^='http://www.webpage.com/topics/']")
.each(function(){
this.href = "http://www.webpage.com/" + countyvals + $(this).attr('data-relativeurl');
});}

How to change and add new HTML objects with Javascript?

I know a bit of PHP and so also HTML/CSS, and I have made a simple quiz program allowing users to create and do quizzes that are stored in a MySQL database. Now what I am trying to do is improve the usability and efficiency of the program.
On the createQuestions form, there are eight textboxes, users can fill in between 2 or 8 of these boxes with answers. Although I think this looks messy with all eight, and what I would like is to have 2 textboxes, and when there is text in the second one, the third one appears and so on.. up to eight
I spent a few hours learning a bit of basic JS, and managed to get it, so that there was a button that changed the visibility propities of the input box, label and radio button of each row. Although I wrote it really inefficiently lots of lines of code to do not much :p - giving each object a separate ID, and it still didn't work that well.
Below is an example of how my HTML is laid out, I have eight of these, though I could replace this with one, and a PHP for loop with a limit of 8.
<div id="c">
<p class="subFont" id="cT" style="display:none;">Answer 3</p>
<input type="text" name="optionC" class="textbox" style="display:none;" id="cI">
<input type="radio" name="correctAns" value="c" id="cR" style="display:none;">
<input type ="button" name="add" value="d" style="background-color:green;" onclick="addBox('d', 'inline')" id="cB" style="display:none;">
</div>
Any suggestions on how to write the script descried above? Please could you comment or briefly explain your workings, so I can learn from it :)
Thank you loads in advance, I'm so grateful to all you guys on stackoverflow ;)
ps, any suggestions for learning js resources?
Pure Javascript
to hide/show object id="cR"
// hide
document.getElementById('cR').style.display = 'none';
// show
document.getElementById('cR').style.display = 'block';
to append textarea to
document.getElementById('c').innerHTML += '<textarea name=".." id=".."></textarea>';
events:
<input type="text" id="xxx" onchange="your action here" />
jQuery
to hide/show object id="cR"
// hide
$('#cR').hide();
$('#cR').fadeIn(); // with fade in effect
// show
$('#cR').show();
$('#cR').fadeOut(); // width fade out effect
to append textarea to
$('#c').append('<textarea name=".." id=".."></textarea>');
events:
$('#xxx').change(function() {
your action here
});
another way to add element dynamically in page..
<html>
<head>
<script>
function addElement(obj) {
text_limit = 5; // limit text then add text after that.
var text_lenght = obj.value.length;
if(text_lenght >= text_limit){
var mainElement = document.getElementById('myDiv');
var counter= mainElement.getElementsByTagName('textarea').length;
var newTextArea = document.createElement('textarea');
var textareaname = 'txt_area'+counter;
newTextArea.setAttribute('id',textareaname );
newTextArea.onkeydown= function() {
addElement(this);
}
mainElement.appendChild(newTextArea);
}
}
</script>
</head>
<body>
<div id="myDiv">
<textarea id="txt_area2" onkeyup="addElement(this);"></textarea></div>
</body>
</html>

Reading and printing user inputs in HTML in PHP

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>

Categories