Remove white space from Text-Area , Why is it there? - php

I would like to understand why my <textarea> box contains white space when I land on the page. I have put in place an if(empty ($_POST['textarea']) to check if it has text before submission. I couldn't get the if(empty ($_POST['textarea']) to work at first until I noticed white space in the <textarea>. As soon as I remove the white space the if(empty ($_POST['textarea']) condition works.
Before I ever click into the textarea there's already white space - Why is this happening and how can I prevent it?
Here is my code.
Text-Area:
echo '<div id="container">
<textarea style=width:500px; font-size:14px; height:60px;font-weight:bold;
name= "name" id="name" >
</textarea>
</div>
I'm using jQuery to send via AJAX:
<script src="js/jquery.js"></script>
<div id="showResult"></div>
<script>
$(document).ready (function()
{
// Focus on textarea
$('#name').focus();
// '#msg' id of button
$('#msg').on('click', function() {
//to disable button after click
this.disabled = true;
// '#name' is the id value of textarea name
var info = $('#name').val();
$.ajax ({
method: "POST",
url: "actions/message_action.php",
//pass my variables to ajax - jq here in data name:
data: {name: info, recptid: '<?php echo $_GET["id"]; ?>'
},
//feed the success my data to return results
success: function(data){
$('#data').append(status);
$("#showResult").text(data);
//window.alert(data);
$('#data').val('Sent');
}
});
return false;
});
});
</script>

The white space is generated by the way you have formatted your HTML:
<textarea style=width:500px; font-size:14px; height:60px;font-weight:bold;
name= "name" id="name" >
</textarea>
This creates a space and newline in the textarea. Change your HTML to this:
<textarea style=width:500px; font-size:14px; height:60px;font-weight:bold;
name= "name" id="name" ></textarea>
EDIT
I can see that you have named your textarea name, which indicates to me that you might want to use a <input type="text"> instead, since textareas are for multiline text.

Use can use trim to remove whitespace in your textbox, before and after possible content:
var info = $('#name').val().trim();

It's because you have space in between
<textarea style=width:500px; font-size:14px; height:60px;font-weight:bold;
name= "name" id="name" >// this creates space
</textarea>
Use
<textarea style=width:500px; font-size:14px; height:60px;font-weight:bold;
name= "name" id="name" ></textarea>

Try putting the closing </textarea> tag on the same line removing the white space.

Related

How to make jquery serialize ignores an input field in a div that toggles between hide and show

I have a form where one of the controls(inside a div) has a display of none. When a user checks a particular radio button the hidden div will display which contains an input element allowing him to enter some input.
When I tested it with PHP (using isset() function), I realized that the input variable is set, even if it's parent(div with id of details) is not shown.
What I want however is that serialize should only send the variable to the server when the div containing the input field is displayed. If I however gives display of none to the input element directly, it works as I want. But I want it to be on the div because some controls like labels and many other possible input fields need to also be hidden. One quick solution will be to give all the controls or elements in the div a class and toggles their display using the radio buttons, but I rather prefer the class to be on the div wrapping them all.
HTML:
<form id="form">
<div class="form-group">
<label for="firstname">First Name</label>
<input type="firstname" class="form-control" name="firstname" autofocus placeholder="First Name">
</div>
<div class="form-group">
<label for="surname">Surname</label>
<input type="surname" class="form-control" name="surname" placeholder="Surname">
</div>
<label>1. Do you program?: </label>
<label class="radio-inline">
<input type="radio" name="one" value="Yes"> Yes
</label>
<label class="radio-inline">
<input type="radio" name="one" value="No" checked> No
</label>
<div class="form-group" id="details" style="display:none;">
<label class="control-label">State your Languages</label>
<input type="text" name="language" class="form-control" autofocus>
</div>
<div class="form-group">
<button id="submit" class="btn btn-primary">Submit</button>
</div>
</form>
JavaScript
$(function(){
$('#form input[name=one]').change(function(event) {
$('#details').toggle();
});
$('#submit').on('click', function(event) {
event.preventDefault();
var form = $('#form');
$.ajax({
url: 'process.php',
type: 'POST',
dataType: 'html',
data: form.serialize()
})
.done(function(html) {
console.log(html);
})
.fail(function() {
console.log("error");
})
});
});
PHP
if(isset($_POST['language'])) {
echo 'Language is set';
} else {
echo 'Not set';
}
The PHP reports 'Language is set' even if the div containing the input with name of language is given display of none;
disabled input elements are ignored by $.serialize()
<input type="hidden" name="not_gonna_submit" disabled="disabled" value="invisible" />
To Temporarily enable them.
var myform = $('#myform');
// Find disabled inputs, and remove the "disabled" attribute
var disabled = myform.find(':input:disabled').removeAttr('disabled');
// serialize the form
var serialized = myform.serialize();
// re-disabled the set of inputs that you previously enabled
disabled.attr('disabled','disabled');
OR
You could insert input fields with no "name" attribute:
<input type="text" id="in-between" />
Or you could simply remove them once the form is submitted (in jquery):
$("form").submit(function() {
$(this).children('#in-between').remove();
});
Instead going for complex workaround in JavaScript, you could accomplish it in PHP easy way. Check if the radio button Yes is selected and if it is selected, you can do other processing based on that.
if(isset($_POST['one']) && $_POST['one'] === 'Yes') {
if(!empty($_POST['language'])) {
echo $_POST['language'];
} else {
echo "Language is given empty!";
}
} else {
echo 'Language is not selected!';
}
The PHP code above is a simple workaround. You could go for that. If you're only looking to do that in JavaScript itself, I would direct you to the answer given by Bilal. He has some workaround with JavaScript.
EDIT
I've come up with my own simple workaround in JavaScript. Hope it could help you.
<script>
$(function() {
var details = $('#details');
$('#details').remove();
$('#form input[name=one]').click(function() {
if(this.value === 'Yes') {
details.insertBefore($('#form div.form-group:last-of-type'));
details.show();
} else {
$('#details').remove();
}
});
});
</script>
Storing the reference to div of id details in a variable before removing the details div from the DOM.
Based on the value selected in the radio button, the details div will be added to the DOM and displayed or removed from the DOM in case No is selected.
Hope it helps!

Type input characters in html form need match - jQuery?

How do I type in a HTML textbox and if the first 3 characters dont match a set variable - then display an error? I need to lose the error and display text next to the input after the 3rd character
I'm thinking jQuery, AJAX, PHP - not sure. I just don't want to use an alert box.
And this needs to be before a user enters the submit button...
<form>
<input type="text" id="test"/><br>
<input type="button" id="txt" value="Submit" />
</form>
$(document).ready(function(){
$("#txt").click(function(){
var text = $("#test").val();
var comparingText = "yes";
if (text != comparingText){
alert( $("#test").val());
}
});
});
It will show this alert after write yes.
you can use it as you want.
$( "#test" ).keyup(function() {
var test = $( "#test" ).val();
if(test == 'yes'){
alert( "your Error msg" );
}
});
You can use a <span> element, next to the <input> element to display an error message and, as you said, avoid using the alert box.
JS
HTML
<form>
<input type="text" id="test" oninput="submitData(this.value)"/>
<span id="textError"></span><br/>
<input type="button" id="txt" value="Submit" />
</form>
JS
function submitData(input) {
if (input != "yes") {
document.getElementById("textError").innerHTML = "Your Error MSG";
} else {
document.getElementById("textError").innerHTML = "";
}
}
JS + jQuery
In this case I'm taking Mamunur Rashid's answer to complement the code.
HTML
<form>
<input type="text" id="test"/> <span id="textError"></span><br/>
<input type="button" id="txt" value="Submit" />
</form>
jQuery
$(document).ready(function(){
$("#test").keyup(function(){
var test = $("#test").val();
if (test != "yes") {
$("#textError").html("Your Error MSG");
} else {
$("#textError").html("");
}
});
});

how to get text area value in jquery?

i am trying to send the value of text area into database but i am unable to get the values of text area. and also i want once data is saved to database i want to show that data in text area. kindly help me.
Thanks.
here is my code.
<script type="text/javascript" >
function save()
{
var mail = {
aboutus: $('textarea#area1').val(),
services: $("#area2").val(),
contact: $("#area3").val()
};
$.ajax({
url: "user_stall_add.php",
type: "POST",
enctype: "multipart/form-data",
data: mail,
success: function(data) {
alert("Content Added");
}
});
}
</script>
<script type="text/javascript" src="../nicEdit.js"></script>
<script type="text/javascript">
bkLib.onDomLoaded(function() { nicEditors.allTextAreas() });
</script>
<h4 style="margin-left:4em;">About Us Content</h4>
<textarea name="area1" id="area1" style="margin-left:4em;" cols="60" rows="10"></textarea>
<input type="button" style="margin-left:4em;" value="Save" onclick="save();"><br />
<h4 style="margin-left:4em;">Services Content</h4>
<textarea name="area2" id="area2" cols="60" rows="10">
Some Initial Content was in this textarea
</textarea>
<input type="button" style="margin-left:4em;" value="Save" onclick="save();"><br />
<h4 style="margin-left:4em;">Contact Content</h4>
<textarea style="margin-left:4em;" id="area3" name="area3" cols="60" rows="10">
HTML <b>content</b> <i>default</i> in textarea
</textarea>
<input style="margin-left:4em;" type="button" value="Save" onclick="save();"><br />
</div>
You have used nicEditors,
var aboutus = new nicEditors.findEditor('area1').getContent();
var services = new nicEditors.findEditor('area2').getContent();
var contact = new nicEditors.findEditor('area3').getContent();
var mail = {
aboutus: aboutus,
services: services,
contact: contact
};
REF: http://nicedit.com/demos.php
Doc: http://wiki.nicedit.com/w/page/521/Javascript%20API
Returns the current HTML of the nicInstance
For example:
nicEditors.findEditor('myArea2').getContent();
returns the HTML in the content editor that replaced the element on the page with ID 'myArea2'.
try
aboutus: $('textarea#area1').val(),
services: $('textarea#area2').val(),
contact: $('textarea#area3').val()
Please try $('#area1').val() to match your other textarea(s). Also, make sure there is a value in the textarea - or you'll get an undefined. Finally, your sample works fine when I just use
function test() {
// These both work for me.
console.log($("textarea#area1").val());
console.log($('#area1').val());
}

JQuery Post - Why I can't see response?

This is my HTML PAGE
I want to send some values with ajax then I want to get them with ajax response but I can't see any character in my div which called with id=result . Where is the problem?
<html>
<head>
<!-- JQuery v1.8.2 -->
<script src="theme/scripts/jquery-1.8.2.min.js"></script>
</head>
<body>
<div class="row-fluid">
<div class="span4">
<input type="text" id="title"/><br>
<textarea rows="10" cols="50" id="content"></textarea><br>
<input type="submit" id="gonderBtn" name="gonderBtn" />
<div id="result"></div>
</div>
</div>
<script type="text/javascript">
jQuery(document).ready(function(){
$("#gonderBtn").click(function(){
var title = $("title").val();
var content = $("content").val();
$.ajax({
url: "deneme_action.php",
dataType: "html",
type: 'POST',
data: {
title: title,
content: content
},
success: function(data){
$("result").html(data);
}
});
});
});
</script>
</body>
</html>
deneme_action.php
<?php
if(isset($_POST["gonderBtn"])){
$result = "Sonuc:".$_POST["title"];
echo "Selam:".$result;
}
else{
echo "no post";
}
?>
Because you don't have a tag with class="result" but you have a tag with id="result".
Either change the jQuery selector to:
$("#result").html(data);
Or the div tag to:
<div class="result"></div>
and selector to:
$(".result").html(data);
And you are not sending gonderBtn with the POST - fix it too:
$("#gonderBtn").click(function(){
var title = $("#title").val();
var content = $("#content").val();
var gonderBtn = $(this).val();
$.ajax({
url: "deneme_action.php",
dataType: "html",
type: 'POST',
data: {
title: title,
content: content,
gonderBtn: gonderBtn,
},
I've also fixed the selectors for input and textarea too.
Check this line:
echo "Selam:"+$result;
Here the plus operator is an error so the php script is not returning anything.
Check this link that documents the use of + operator in php.
var title = $("title").val();
var content = $("content").val();
should be
var title = $("#title").val();
var content = $("#content").val();
You will also need to change:
$("result").html(data);
to
$("#result").html(data);
You should also wrap your inputs in a form.
Edit:
You might want to give your button input a value.
<input type="submit" id="gonderBtn" name="gonderBtn" value="go!" />
Edit 2:
You will also need to give your html elements a name.
<input type="text" id="title" name="title"/><br>
<textarea rows="10" cols="50" id="content" name="content"></textarea><br>
You're not selecting your #result div properly, add a # before
$("#result").html(data);
the same goes for all your selectors
var title = $("#title").val();
var content = $("#content").val();
Since your ajaxing your form you'll have to manually pass your button parameter, although an ajax parameter would be more appropriate.
data: {
title: title,
content: content,
gonderBtn: 'gonderBtn'
},
echo "Selam:"+$result;
In php use "." to concatenate strings.
echo "Selam:".$result;

JavaScript form submits, but post data not available in PHP

It seems the form submits (to the same page - contact.php), but I can not use posted data, for example $_POST["message"] . seems they are empty (I tried to echo them and nothing printed out).
This is JavaScript (in head section of page):
$(document).ready(function (){
$('#contactform').submit(function(){
var action = $(this).attr('action');
$.post("contact.php", {
name: $('#name').val(),
email: $('#email').val(),
company: $('#company').val(),
subject: $('#subject').val(),
message: $('#message').val()
}, function(data,status){
alert("status = " + status);
$('#contactform #submit').attr('disabled','');
if(data=='Message sent!') $('#contactform').slideUp();
});
return false;
});
});
this is form:
<form action="contact.php" method="post" id="contactform">
<ol>
<li>
<label for="name">First Name *</label>
<input name="name" id="name" class="text">
</li>
<li>
<label for="email">Your e-mail *</label>
<input id="email" name="email" class="text">
</li>
<li>
<label for="company">Company Name</label>
<input id="company" name="company" class="text">
</li>
<li>
<label for="subject">Subject<br>
</label>
<input id="subject" name="subject" class="text">
</li>
<li>
<label for="message">Message *</label>
<textarea id="message" name="message" rows="6" cols="50"></textarea>
</li>
<li class="buttons">
<input type="image" name="submitbtn" id="submitbtn" src="images/but_send_message.gif">
</li>
</ol>
</form>
The alert("status = " + status); section on javascript pops up the status as sucess.
UPDATED
And this is PHP part at the top of contact.php
<?php
if(isset($_POST["message"])){
echo '<script>alert("some dummy text");</script>';
};
?>
It is not just that echo does not print anything, but I can not access values from posted data. PHPMailer works fine with manually assigned text to parameters.
If $_POST returns empty data. Make sure that you don't have any htaccess causing this.
I had this problem once. My htaccess always emptied the post data. After modifying the htaccess I got my problem solved.
Just try this code to post the form and check will getting $_POST on contact.php or not
<script type="text/javascript">
$(document).ready(function (){
$("#submitbtn").click(function(){
$("#contactform").attr("action" , "contact.php");
$("#contactform").submit();
});
</script>
If in contact.php if you get $_POST then show success message
<?php
if(isset($_POST["message"])){
echo '<script>alert("some dummy text");</script>';
};
?>
Since you asked for the answer that was a comment
Well, it seems fine, but alternatively you can try
$('#contactform').serialize();
to get all the form values for you and since you asked that, what is the better way to determine that the form has been submitted, well, in this case you can check the submit button instead of a text box or other form fields that could be left empty, so you can ue
if( isset( $_POST['submitbtn'] ) ) {
// process the form
}
Do the Following:
1) provide an id or a class to the li class button's child's input tag
2) Then in jquery write a code to handle :
$('.inputButton').click(function(){
var data = $('#contactform').serializeArray();
$.each(data, function(key, field) {
// Perform your validations over the data here
console.log('field Name == '+field.name+', field value == '+field.value);
});
// Make an ajax call using this data
$.post("contact.php", data, function(returnData) {
// Handle your code for after form submission response
});
});
3) Then in PHP you can get values as :
$name = $_POST["name"]; // and so on...
Hope this helps you solve your problem
as Sheikh heera mentioned in his comment on my question, I tried this:
$(document).ready(function (){
$('#contactform').serialize(function(){
var action = $(this).attr('action');
$.post("contact.php", {
name: $('#name').val(),
email: $('#email').val(),
company: $('#company').val(),
subject: $('#subject').val(),
message: $('#message').val()
}, function(data,status){
$('#contactform #submit').attr('disabled','');
if(data=='Message sent!') $('#contactform').slideUp();
});
return false;
});
});
and it works fine now! thanks to other users that suggested alternate solutions which may be working on this case but as I found the solution, there is no need to check them.
Save your post values in a variable. For example:
$name = $_POST["name"];
You can echo this variable in your script:
var name ="<?php echo $name; ?>";

Categories