HTML textarea show br - javascript

i have a textarea in HTML. In the textarea the blank line is is looks br.
I try to have the value of the some text. And posting with get. After i received with php. And i changed the value of the some text to variabled i get with get.
Like this :
a<br />b c
Code (post with javascript):
<script type="text/javascript">
function nl2br (str, is_xhtml) {
var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
}
function menusec(secilen){
var deger = secilen.options[secilen.selectedIndex].value;
var urunadi = document.getElementById("okulueua").value;
var urunfiyati = document.getElementById("okulueuf").value;
var kargofiyati = document.getElementById("okuluekf").value;
var aciklama = nl2br(document.getElementById("okulueat").value);
alert(aciklama);
window.location.href = "okulue.php?menu=" + deger + "&urunadi=" + urunadi + "&urunfiyati=" + urunfiyati + "&kargofiyati=" + kargofiyati + "&aciklama=" + aciklama;
}
</script>
Code (get with php) :
<?php
if (isset($_GET['menu'])) {
$secilendeger = filter_input(INPUT_GET, "menu");
$urunadiget = filter_input(INPUT_GET, "urunadi");
$urunfiyatiget = filter_input(INPUT_GET, "urunfiyati");
$kargofiyatiget = filter_input(INPUT_GET, "kargofiyati");
$aciklamaget = filter_input(INPUT_GET, "aciklama");
echo($aciklamaget);
?>
<script type="text/javascript">
function br2nl($content){
$content = str_ireplace("<br /> ", "\n", $content);
return $content;
}
function br2nl1($input){
return preg_replace('/<br(\s+)?\/?>/i', "\n", $input);
}
document.getElementById("menusecme1").style.width = "315px";
document.getElementById("okulueua").value = "<?php echo($urunadiget); ?>";
document.getElementById("okulueuf").value = "<?php echo($urunfiyatiget); ?>";
document.getElementById("okuluekf").value = "<?php echo($kargofiyatiget); ?>";
document.getElementById("okulueat").value = "<?php echo($aciklamaget); ?>";
$('select[name^="ms1"] option[value="<?php echo($secilendeger); ?>"]').attr("selected","selected");
</script>
Code (HTML) :
<input type="text" class="okulueuat" name="okulueua" id="okulueua">
<input type="text" class="okulueua2t" name="okulueua2" value="1000" readonly="yes">
<input type="text" class="okulueuft" name="okulueuf" id="okulueuf">
<input type="text" class="okuluekft" name="okuluekf" value="5" id="okuluekf">
<input type="submit" class="tamamb2" value="Tamam" name="submit">
<input type="button" class="iptalb2" value="İptal" onclick="location='okulul.php'">
<input type="file" name="okuluef[]" class="resimeklec" multiple="multiple">
<textarea id="okulueat" name="okuluea"></textarea>
How can i solve this problem?
I need your help.
Note : I don't have a good English. Pardon me. I hope you understand.

Try this:
<textarea>a
b c</textarea>

Related

Create text-input on button click in form

I want to create another input field, everytime the button "+" inside the form is clicked. I searched for a solution but i can't find anything. The input field should be created inside the form over the "+" button.
Here is my current code:
<div class="row">
<div class="col-md-12">
<form method="post" id="create-form" action="create.php" enctype="multipart/form-data">
<?php
/* getting sample questions */
/* checks result and creates variables from result */
if ($sampleamount > 0) { // amount
$samplequery->bind_result($questionid_sample, $question_sample);
while ($samplequery->fetch()) { // while page can use this variables
/* echo text-box, value from db */
$required = $questionid_sample === 1 ? "required" : ""; // one question is always required
echo "<input class='question-box' type='text' name='" . $questionid_sample . "' placeholder='Write your question in here.' maxlength='255' size='70' value='" . $question_sample . "'" . $required . "> <br>";
}
} else {
/* no result (db=sample_question) */
header('Location: ../index.php');
}
$samplequery->close();
closeDB($conn);
/* adds more input for user */
for ($i = ($sampleamount + 1); $i <= ($additionalquestions + $sampleamount); $i++) {
echo "<input class='question-box' type='text' name='" . $i . "' placeholder='Write your question in here.' maxlength='255' size='70'> <br>";
}
?>
<br>
<input class="createsurvey2" type="button" id="addqbtn" name="addqbtn" value="+" >
<br>
<input class="createsurvey2" type="submit" name="btnSubmit" value="Create Survey!" >
</form>
</div>
</div>
</div>
<script>
function addquestion() {
var counter = 2;
var addqbtn = document.getElementById('addqbtn');
var form = document.getElementById('create-form');
var addInput = function() {
counter++;
var input = document.createElement("input");
input.id = 'additionalquestion-' + counter;
input.type = 'text';
input.class = 'question-box';
input.name = 'name';
input.placeholder = 'Write your question in here.';
form.appendChild(input);
};
addqbtn.addEventListener('click', function(){
addInput();
}.bind(this));
};
</script>
<html>
<body>
<button onclick="createNewFiled()" id="incrementBtn" type="button">Click here</button>
<form id="form" action="">
</form>
</body>
</html>
<script type="text/javascript">
var counter = 0;
var incrementBtn = document.getElementById('incrementBtn');
var form = document.getElementById('form');
var createNewFiled = function() {
counter++;
var input = document.createElement("input");
var br = document.createElement("br"); // If you need new line after each input field
input.id = 'input-' + counter;
input.classList.add("inputClass");
input.type = 'text';
input.name = 'name'+counter;
input.placeholder = 'Input field ' + counter;
form.appendChild(input);
form.appendChild(br); // If you need new line after each input field
};
</script>

Remember last selected option from dropdown

I want that our website should remember the last selected option from drop down when he visit again. I'm trying it with jQuery cookies but it's not working.
Here is my select dropdown code
<form action="results.php" method="POST" enctype="multipart/form-data" id="form">
<input id="search" type="text" name="search" placeholder="Search.." autocomplete="off">
<select name="city" id="city">
<?php
$sql="SELECT * FROM tcity";
$connect= mysqli_query($conn, $sql) or die ("Failed To Connect.");
while($rows= mysqli_fetch_array($connect, MYSQLI_ASSOC)){ ?>
<option value= "<?php echo $rows['c_id']?>" id="optin_val"><?php echo $rows['city_nm'];?></option>
<?php }
?>
</select>
</form>
Beacuse i'm using it as filter with my search bar i read the value on keyup function my jquery i tried is
$(document).ready(function(){
$('#search').keyup(function(){
var value = $(this).val();
var val = $('#city').val();
Cookies.set('dropdown',val);
if ( value != ""){
$('#my-search').show();
var dropCookie = Cookies.get('dropdown');
$.post('functions/search_bar.php', {value: value, val: dropCookie}, function(data){
$('#my-search').html(data);
});
}else{
$('#my-search').hide();
}
});
As you can see I tried to use cookie to remember the selection but its not working as it takes the first option again when the page is refreshed.
You can use Jquery.Cookie for this case.
https://github.com/carhartl/jquery-cookie
Then save dropdown value in cookie like :
jQuery(document).ready(function(){
var selectedVal = jQuery.cookie("selected-val");
if (selectedVal) {
jQuery("#city").val(selectedVal);
}
jQuery("#city").on("change", function(){
var selection = jQuery(this).val();
jQuery.cookie("selected-val", selection, {expires: 365, path: '/'})
});
});
I assume you are using js-cookie or similar?
This is not tested, but if the cookie is set then you could do the following:
<form action="results.php" method="POST" enctype="multipart/form-data" id="form">
<input id="search" type="text" name="search" placeholder="Search.." autocomplete="off">
<select name="city" id="city">
<?php
$sql="SELECT * FROM tcity";
$connect= mysqli_query($conn, $sql) or die ("Failed To Connect.");
while($rows= mysqli_fetch_array($connect, MYSQLI_ASSOC)){ ?>
<option value= "<?php echo $rows['c_id']?>" id="optin_val" <?php echo (!empty($_COOKIE['dropdown']) && $_COOKIE['dropdown'] == $rows['c_id'] ? 'selected' : ''); ?>><?php echo $rows['city_nm'];?></option>
<?php }
?>
</select>
</form>
Notice where php checks $_COOKIE['dropdown'] and outputs selected if it equals the option value on this line:
<option value= "<?php echo $rows['c_id']?>" id="optin_val" <?php echo (!empty($_COOKIE['dropdown']) && $_COOKIE['dropdown'] == $rows['c_id'] ? 'selected' : ''); ?>><?php echo $rows['city_nm'];?></option>
Please refer this answer you might get some help..
$(document).ready(function(){
$('#search').keyup(function(){
var value = $(this).val();
var val = $('#city').val();
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
document.cookie = "dropdown=" + val + expires + "; path=/";
// Cookies.set('dropdown',val);
if ( value != ""){
$('#my-search').show();
var dropCookie = getCookie("dropdown");
$.post('functions/search_bar.php', {value: value, val: dropCookie}, function(data){
$('#my-search').html(data);
});
}else{
$('#my-search').hide();
}
});
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
if (c.indexOf(name) == 0) {
return (c.substring(name.length, c.length));
}
}
}

Javascript AJAX upload of BLOB image using php. $_FILES is empty

Hi I am trying to upload a BLOB image onto my localhost wampserver through AJAX using Javascript and PHP.
I am trying to obtain the image in $_FILES but for some reason $_FILES is empty. I have set enctype and checked php.ini for file_uploads = On.
Here is my html form:
<h1>CREATE A NEW ENTRY</h1>
<form name="insertForm" method="post" enctype="multipart/form-data">
Name: <input type="text" id="insert_name" /> <br />
Age: <input type="text" id="insert_age" /> <br />
WPM: <input type="text" id="insert_wpm" /> <br />
Sex: <select id="insert_sex">
<option>M</option>
<option>F</option>
</select><br />
Photo : <input type="file" name="photo" id="insert_photo" /> <br />
<input type="button" onClick="insertFunction()" value="UPDATE LIST" />
</form>
<br>
<br>
<div id="preview"><img id="preview_img" src="images/placeholder.png"/></div>
<div id="message"></div>
Here is the javascript that runs the AJAX :
function insertFunction()
{
var ajaxRequest = createAjaxObject(); // checks for browser type and returns corres. ajax object
var name = document.getElementById('insert_name').value;
var age = document.getElementById('insert_age').value;
var wpm = document.getElementById('insert_wpm').value;
var sex = document.getElementById('insert_sex').value;
var image = document.getElementById('insert_photo').files[0];
var imageType = image.type;
alert(imageType);
var match = ["image/jpeg", "image/png", "image/jpg"]
if (!((imageType==match[0]) || (imageType==match[1]) || (imageType==match[2])))
{
document.getElementById('preview').innerHTML = '';
document.getElementById('preview').innerHTML = '<img id="preview_img" src="images/noimage.png"/ alt="../images/noimage.png">';
document.getElementById("message").innerHTML = "<p class='error'>Please Select A valid Image File</p>"+"<h4>Note</h4>"+"<span id='error_message'>Only jpeg, jpg and png Images type allowed</span>";
}
else
{
var reader = new FileReader();
reader.onload = function(e) {
document.getElementById('preview').innerHTML = '';
document.getElementById('preview').innerHTML = '<img id="preview_img" src="' + e.target.result + '" alt="' + e.target.result + '">';
};
reader.readAsDataURL(image);
var dataString = "name=" + name + "&age=" + age + "&wpm=" + wpm + "&sex=" + sex + "&photo=" + image;
ajaxRequest.open("POST", "insert-example.php", true);
ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxRequest.send(dataString);
document.getElementById('insertDiv').innerHTML = "processing...";
ajaxRequest.onreadystatechange = function() {
if (ajaxRequest.readyState == 4)
{
var insertDiv = document.getElementById('insertDiv');
insertDiv.innerHTML = ajaxRequest.responseText;
}
}
}
}
And here is the php that updates the localhost.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$dbhost = "localhost";
$dbuser = "root";
$dbpassword = "";
$dbname = "ajaxtutorial";
$link = mysqli_connect($dbhost, $dbuser, $dbpassword, $dbname);
if (mysqli_connect_errno())
{
echo "Connection failed: %s" . mysqli_connect_error();
}
mysqli_connect($dbhost, $dbuser, $dbpassword) or die(mysql_error());
mysqli_select_db($link, $dbname) or die("Cannot connect to database");
$name = mysqli_real_escape_string($link, $_POST['name']);
$age = mysqli_real_escape_string($link, $_POST['age']);
$wpm = mysqli_real_escape_string($link, $_POST['wpm']);
$sex = mysqli_real_escape_string($link, $_POST['sex']);
// Image file code below
if (false)
{
$photo = $_FILES["photo"];
echo $photo;
}
else
{
echo var_dump($_FILES);
}
}
?>
The output I get from the var_dump is :
array (size=0)
empty
Could someone please tell me what is going wrong with my code?
Try to use jQuery, way more simple: (so replace everything in your js file with this script and keep the HTML and PHP)
$.ajax({
type: 'post',
url: 'update.php', //php script
data: new FormData($('form')[0]), //form data
processData: false,
contentType: false,
success: function (result) {
//do something cool when it is succesfully updated
});
PS: don't forget to include this BEFORE the script because it is jQuery: <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.2.min.js">
try this
var imageData = new FormData(image);
var dataString = "name=" + name + "&age=" + age + "&wpm=" + wpm + "&sex=" + sex + "&photo=" + imageData;
Sending files using a FormData object

change local URL based on dopdown list

I want to change the local URL (on/of the same page) from
example.php
to
example.php?month=year-month
I have following script:
<script type=\"text/javascript\">
function select() {
var url = window.location.href;
var year = document.getElementById('myyear').value;
var month = document.getElementById('mymonth').value;
document.my_months.action = url + '?month=' + year + '-' + month;
}
</script>
And follwing form:
echo "<form id =\"my_months\" name= \"my_months\" method=\"post\" onsubmit=\"return select();\">
<select name = \"myyear\" id = \"myyear\">";
foreach (range(2012, date('Y')) as $years) {
if ($years == date('Y')) {
echo "<option value= \"".$years."\" selected= \"".$years."\">".$years."</option>";
} else {
echo "<option value= \"".$years."\">".$years."</option>";
}
}
echo "</select>
<select name = \"mymonth\"> id = \"mymonth\"";
foreach ($myMonths as $id => $months) {
if ($months == date('F')) {
echo "<option value= \"".$id."\" selected= \"".$id."\">".$months."</option>";
} else {
echo "<option value= \"".$id."\">".$months."</option>";
}
}
echo "</select>
<input type=\"submit\" id=\"Submit_m\" name=\"Submit_m\" value=\"Ok\">
</form>";
But it doesn't work. The page will be reload without modifying the URL!
What I'm doing wrong here?
Here is the code:
echo "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\" dir=\"ltr\">
<head>
<title>title</title>
<meta name=\"description\" content=\"\" />
<meta name=\"robots\" content=\"index,follow\" />
<meta name=\"keywords\" content=\"\" />
<!--<meta http-equiv=\"refresh\" content=\"5\">-->
<script type=\"text/javascript\" language=\"javascript\" src=\"../js/jquery-1.9.1.js\"></script>
<script type=\"text/javascript\" language=\"javascript\" src=\"../js/modules/exporting.js\"></script>
<script type=\"text/javascript\">
function select() {
var url = window.location.href;
var year = document.getElementById('myyear').value;
var month = document.getElementById('mymonth').value;
document.my_months.action = url + '?month=' + year + '-' + month;
}
</script>
<script type=\"text/javascript\">
$(document).ready(
function () {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'spline',
zoomType: 'xy'
},
...
});
}
)
</script>
</head>
<body>";
//here some data and arrays
echo "<form id =\"my_months\" name= \"my_months\" method=\"post\" onsubmit=\"return select();\">
<select name = \"myyear\" id = \"myyear\">";
foreach (range(2012, date('Y')) as $years) {
if ($years == date('Y')) {
echo "<option value= \"".$years."\" selected= \"".$years."\">".$years."</option>";
} else {
echo "<option value= \"".$years."\">".$years."</option>";
}
}
echo "</select>
<select name = \"mymonth\"> id = \"mymonth\"";
foreach ($myMonths as $id => $months) {
if ($months == date('F')) {
echo "<option value= \"".$id."\" selected= \"".$id."\">".$months."</option>";
} else {
echo "<option value= \"".$id."\">".$months."</option>";
}
}
echo "</select>
<input type=\"submit\" id=\"Submit_m\" name=\"Submit_m\" value=\"Ok\">
</form>
<p><div id=\"container\" style=\"min-width: 200px; height: 400px; margin: 0 auto\"></div></p></body></html>";
<script type=\"text/javascript\">
function select() {
var url = window.location.href;
var year = document.getElementById('myyear').value;
var month = document.getElementById('mymonth').value;
url += '?month=' + year + '-' + month;
// set the url in your location bar
history.pushState({date:"true"}, "", url);
}
</script>
all suggested tries were not successfull. However I've changed the method of the form from post to get and the url changed to
example.php?myyear=myyear_value&mymonth=mymonth_value&Submit_m=OK
whwn submiting the button named Submit_m
With these variables I'm now abel to the get the values with $_GET['myyear'] and $_GET['mymonth']
Now I get the behavior expected

How to obtain text from a textbox in Javascript

UPDATE
Ok, after trying ".value" for god knows x amount of time again, it some how worked..... Problem solved. Thanks a lot for those who has responded.
UPDATE
How can I obtain the text(strings) from my form on my HTML page with Javascript?
I just want to take whatever was inputted into the text box and write into my XML file.
For example, if I type "HELLO" into the text box, I want "HELLO" written in the XML file.
I have tried both ".value" and ".text", they don't work. Also tried ".textcontent", no good too. I'm thinking that I need to use a different code.
Here's an image of what I'm trying to do:
http://img94.imageshack.us/img94/5677/sdfsdfsdfs.jpg
Here are the files if you want to mess with them personally:
http://www.mediafire.com/?e29t6ipatsqun70
Here's my HTML file:
<html>
<!--onSubmit="SaveXML(person);"-->
<head>
<title>Registration</title>
<link rel="stylesheet" type="text/css" href="CSS_LABs.css" />
</head>
<body>
<script type="text/javaScript" src="LoginJS.js"> </script>
<script type="text/javaScript" src="writeXML.js"> </script>
<div class="form">
<form id="Registration" name="reg" action="" method="get" onSubmit="initialize_array()">
Username:<input type="text" name="Usrname" id="Usrname" maxlength="10"/> <br/>
Password:<input type="password" name="Pswd" id="Pswd" maxlength="20"/> <br/>
<hr>
PersonID:<input type="text" name="PersonID" id="PersonID"/> <br>
<hr>
First Name:<input type="text" name="FirstName" id="FirstName"/> <br>
Last Name:<input type="text" name="LastName" id="LastName"/>
<hr>
DOB:<input type="text" name="DOB" id="DOB"/> <br>
<hr>
Gender:<input type="text" name="Gender" id="Gender"/> <br>
<hr>
Title:<input type="text" name="Title" id="Title"/> <br>
<hr>
<!--Secret Question:<br>
<select name="secret?">
</select> <br>
Answer:<input type="text" name="answer" /> <br> <br>-->
<input type="submit" value="submit" />
</form>
</div>
</body>
</html>
Here's my Javascript file:
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
var fso = new ActiveXObject("Scripting.FileSystemObject");
var FILENAME = 'G:\\CST2309 - Web Programming 1\\Copy of Take Home Exam - Copy\\PersonXML2.xml';
function SaveXML(UserData)
{
var usrn = document.getElementById("Username").text;
var pswd = document.getElementById("Pswd").text;
var pid = document.getElementById("PersonID").text;
var fname = document.getElementById("FirstName").text; //This is where I'm having trouble with
var lname = document.getElementById("LastName").text;
var gender = document.getElementById("Gender").text;
var dob = document.getElementById("DOB").text;
var title = document.getElementById("Title").text;
var file = fso.CreateTextFile(FILENAME, true);
file.WriteLine('<?xml version="1.0" encoding="utf-8"?>\n');
file.WriteLine('<PersonInfo>\n');
for (countr = 0; countr < UserData.length; countr++) {
file.Write(' <Person ');
file.Write('Usrname="' + UserData[countr][0] + '" ');
file.Write('Pswd="' + UserData[countr][1] + '" ');
file.Write('PersonID="' + UserData[countr][2] + '" ');
file.Write('FirstName="' + UserData[countr][3] + '" ');
file.Write('LastName="' + UserData[countr][4] + '" ');
file.Write('Gender="' + UserData[countr][5] + '" ');
file.Write('DOB="' + UserData[countr][6] + '" ');
file.Write('Title="' + UserData[countr][7] + '"');
file.WriteLine('></Person>\n');
} // end for countr
file.Write(' <Person ');
file.Write('Usrname="' + usrn + '" ');
file.Write('Pswd="' + pswd + '" ');
file.Write('PersonID="' + pid + '" ');
file.Write('FirstName="' + fname + '" ');
file.Write('LastName="' + lname + '" ');
file.Write('Gender="' + gender + '" ');
file.Write('DOB="' + dob + '" ');
file.Write('Title="' + title + '" ');
file.WriteLine('></Person>\n');
file.WriteLine('</PersonInfo>\n');
file.Close();
} // end SaveXML function --------------------
function LoadXML(xmlFile)
{
xmlDoc.load(xmlFile);
return xmlDoc.documentElement;
} //end function LoadXML()
function initialize_array()
{
var person = new Array();
var noFile = true;
var xmlObj;
if (fso.FileExists(FILENAME))
{
xmlObj = LoadXML(FILENAME);
noFile = false;
} // if
else
{
xmlObj = LoadXML("PersonXML.xml");
//alert("local" + xmlObj);
} // end if
var usrCount = 0;
while (usrCount < xmlObj.childNodes.length)
{
var tmpUsrs = new Array(xmlObj.childNodes(usrCount).getAttribute("Usrname"),
xmlObj.childNodes(usrCount).getAttribute("Pswd"),
xmlObj.childNodes(usrCount).getAttribute("PersonID"),
xmlObj.childNodes(usrCount).getAttribute("FirstName"),
xmlObj.childNodes(usrCount).getAttribute("LastName"),
xmlObj.childNodes(usrCount).getAttribute("Gender"),
xmlObj.childNodes(usrCount).getAttribute("DOB"),
xmlObj.childNodes(usrCount).getAttribute("Title"));
person.push(tmpUsrs);
usrCount++;
} //end while
if (noFile == false)
fso.DeleteFile(FILENAME);
SaveXML(person);
} // end function initialize_array()
You can use document.getElementById("UsrName").value to get tha value of a field in your form. Due to you use id for every field, so there is no problem using this code.
Something around: http://www.tek-tips.com/viewthread.cfm?qid=1143011&page=1
Here is an example of it working. I changed some functionality around just to show that the function was seeing the values correctly:
http://jsfiddle.net/73gbH/1
But like everyone said change .text to .value

Categories