jQuery: How can I add line break to form input? - javascript

I'm collecting information in a standard HTML form. I have, for example, <input type="text" name="UserName" id="name"/>. When the form is submitted, I want to add a line break to the value entered. So if the user entered "foo," the form would submit the value "foo\n."
Here's the jQuery function I'm using:
$("#formID").submit(function () {
$(":text").each(function () {
var value = $(this).val();
var newValue = value + " \n";
$(this).val(newValue);
});
});
When the form is submitted, however, the value assigned to the form field does not have the line break.
My goal is for the line break to survive the output of the back-end form processing, which generates an email. Since I don't have control over the script that generates the mail, I'm trying to impose some formatting with what I can control.
Any assistance is appreciated.

I posted my previous answer before I saw your comment that the output is plain text. Now try this:
$(document).ready(function() {
$("#formID").submit(function () {
$(":text").each(function () {
var value = $(this).val();
var myname = $(this).attr('name');
var newValue = value + " \n";
var hid = '<input type="hidden" name="' + myname + '" value="' + newValue + '"/>';
$(this).removeAttr('name');
$("#formID").append(hid);
});
});
});
Previous Answer
As Mark says, the line break character is not rendered as a line break when viewed in the browser (or email client for that matter), so instead of adding a line break character "\n", you should add a <br/>
$("#formID").submit(function () {
$(":text").each(function () {
var value = $(this).val();
var newValue = value + '<br/>';
$(this).val(newValue);
});
})

Textbox doesn't holds "\n" only textarea does. What you can do is post the data yourself to the controller or store the values in hidden fields and submit the form and read the hidden fields in the server, if you don't have much control there match the names to the hidden fields.

Related

getting the value of a textbox when user enters the name/id of the field

Using jquery to get the value of a textbox.
BUT
i need to enter the id of the textbox, then use that value to get the value of the textbox using jquery.
var tt = $("#fieldname").val()
that works
now how do i enter the fieldname at runtime, and get jquery to execute the val command as if it was hard coded?
There are a few ways that you could do this. One way is to listen to one of the keyboard or change events on the textbox you enter the id into, to help determine when the input has changed. So for example
$("#inputText").on("keyup", function(keyupEvent){
var textboxId = $("#inputText").val();
var textboxIdValue = $("#" + textboxId).val();
});
Or another way could be to use a click event with similar kind of logic, so for example
$("#clickMe").on("click", function(){
var textboxId = $("#inputText").val();
var textboxIdValue = $("#" + textboxId).val();
})
An example for the use case of both can be seen here https://fiddle.jshell.net/xpvt214o/114584/
Here is an example for you to get started with:
<body>
<p>Type "one" or "two" below</p>
<input id="search" />
<input id="one" value="This input is #one" />
<input id="two" value="And this is #two" />
<p id="result">No input specified</p>
</body>
And the corresponding jQuery code:
// Cache jQuery elements for performance and readability
var $search = $("#search");
var $result = $("#result");
$search.on("change", function() {
var search_value = $search.val();
if (search_value.length) {
search_value = "#" + search_value.toLowerCase().trim(); // Sanitise user input
if ($(search_value).length) {
$result.text($(search_value).val());
} else {
$result.text("Input not found");
}
} else {
$result.text("No input specified");
}
});
This will show the value of the specified input, if it exists.
You can see it in action here: https://jsfiddle.net/jeevantakhar/xpvt214o/114558/

Get variable via user input

I want that the user can see the value of a variable by writing it's name in a textarea, simpliefied:
var money = "300$";
var input = "money"; //user wants to see money variable
alert(input); //This would alert "money"
Is it even possible to output (in this example) "300$"?
Thanks for help!
Instead of seprate variables, use an object as an associative array.
var variables = {
'money': '300$'
}
var input = 'money';
alert(variables[input]);
You can use an object and then define a variable on the go as properties on that object:
var obj = {}, input;
obj.money = "300$";
input = "money";
alert(obj[input]);
obj.anotherMoney = "400$";
input = "anotherMoney";
alert(obj[input]);
A simple way,you can still try this one :
var money = "300$";
var input = "money"; //user wants to see money variable
alert(eval(input)); //This would alert "money"
Here is an answer who use the textarea as asked.
JSFiddle http://jsfiddle.net/7ZHcL/
HTML
<form action="demo.html" id="myForm">
<p>
<label>Variable name:</label>
<textarea id="varWanted" name="varWanted" cols="30" rows="1"></textarea>
</p>
<input type="submit" value="Submit" />
</form>
<div id="result"></div>
JQuery
$(function () {
// Handler for .ready() called.
var variables = {
'money': '300$',
'date_now': new Date()
}
//Detect all textarea's text variation
$("#varWanted").on("propertychange keyup input paste", function () {
//If the text is also a key in 'variables', then it display the value
if ($(this).val() in variables) {
$("#result").html('"' + $(this).val() + '" = ' + variables[$(this).val()]);
} else {
//Otherwise, display a message to inform that the input is not a key
$("#result").html('"' + $(this).val() + '" is not in the "variables" object');
}
})
});

How to capture text value from input field, and pass it to new input field

I want couple of things happen simultaneously on keypress() event, I got two pages, default.html where there is a input text box and another page.html with another input text box, Now what I need is that the moment a key is pressed to type a letter in to the input text box on default.html, keypress() fires (I need this on keypress, not on keyup or keydown) and the 'letter' is captured
var c = String.fromCharCode(e.which);
and at same time page is redirected
document.location= "page.html"; return false;
to 'page.html' showing the 'letter' in the input text field which was typed on previous page.
I have got incomplete code..
$(document).keypress(function(){
var c = String.fromCharCode(e.which);
document.location= "page.html";
return false;
}
});
don't know how to use var c here to show the value into the text field on next page(page.html).
javascript code on page.html...please correct and help with this code..
I picked it up from another post..I can see that the value typed on
default.html page shows up in the address bar of page.html
but does not show in the input text box, I know for sure I
am doing it incorrectly. The code is mentioned below.
input field on default.html - <input id="search" type="text" name="searchbar">
input field on page.html - <input id="search2" type="text" name="searchbar2">
<script type="text/javascript">
var queryString = new Array();
$(function () {
if (queryString.length == 0) {
if (document.location.search.split('?').length > 1) {
var params = document.location.search.split('?')[1].split('&');
for (var i = 0; i < params.length; i++) {
var key = params[i].split('=')[0];
var value = decodeURIComponent(params[i].split('=')[1]);
queryString[key] = value;
}
}
}
if (queryString["name"] != null) {
var data = "<u>Values from QueryString</u><br /><br />";
data += "<b>Name:</b> " + queryString["name"];
$("#search1").html(data);
}
});
</script>
You can send the character in the query string like this:
document.location = "page.html?c=" + c;
Then, you can read it in JavaScript on page.html with
document.location.search

appent text to input field

Is there any way to append a text to input field?
So lets say instead of:
<input type="text" id="val" name="val" value="http://" style="width: 140px;" />
with "http://" already written, have a "http://" added automatically when someone types an address, and if someone types full url "http://www.****.com" the http should not be added so it's not doubled.
Any one has any ideas? I can't use php.
Why not just add the http:// if it is missing?
var input = document.getElementById('val').value;
if (input.search('http://') === -1) {
input = 'http://' + input;
}
edit: if you need to allow https also, change the search to a regex:
if (input.search(/https?:\/\//) === -1) {
http://jsfiddle.net/jbabey/Bt67X/
I strongly suggest using a scripting framework, e.g. jQuery (http://jquery.com) to access the input field.
See here:
http://jsfiddle.net/5BLrU/
Here is the JS code for reference
$(function() {
$("#some-form").submit(function(){
var $val = $("#val");
var url = $val.val();
if (!/^http:\/\/.+/.test(url)) {
$val.val("http://" + url);
}
// remove this to submit the form!
return false;
});
});
The following example assumes the ID of the target element is val.
// Store current element
var elem = document.getElementById('val'),
// Store current value
currentValue = elem.value;
// Prepend something if not present
if (currentValue.match(/^http:\/\//) == false) {
currentValue = 'http://' + currentValue;
}
// Re-assign
elem.value = currentValue;
Append:
document.getElementById('val').value += "http://www.google.co.uk";
Remove Duplicate:`
document.getElementById('val').value.replace("http://http://","http://");
This way, if they did type http:// twice, it would just remove it.

Populating a textarea from several textfields

I have several textfields which will populate a text area.
I managed to populate it with a javascript function. On the onblur event of a textfield, the value of the textfield is passed and the textarea is field with this value.
However, my problem is the following:
If I modify a previously filled textfield, the textarea will simply append it again.
What I need is some functionality that if:
1: If I give focus to the textfield which is already been filled and I don't modify it, it will not be appended (I implemented this with an if statement and substring.
2: If I modify a previously filled textfield, the text area DOES NOT append it again at the end of the string BUT it replaces the part of the textarea with just that text field new value.
Take for instance the following 2 textfields:
<input type="text" id="txtName" name="txtName" />
<input type="text" id="txtSurname" name="txtSurname" />
If I fill up these textfields with John and Doe respectively, the textarea value will become:
txtName=John,txtSurname="Doe"
I managed to implement this.
What I need is that if I edit txtName from John to Alex, the textarea value will be as follows:
txtName=Alex,txtSurname=Doe
and not like is currently being displayed, i.e.
txtName=John,txtSurname=Doe,txtName=Alex
Should I achieve this by using an array which will store all the textfields values?
Any help would be greatly appreciated.
Many thanks in advance.
the following code should work for you. I have wrapped the textboxes inside a div. and also registered a onkeyup event on both the textboxes.
The javascript code iterates through each textboxe inside the div, and prints its name and value in the textarea.
HTML
<div id="textBoxContainer">
<input type="text" id="txtName" onkeyup="UpdateTextArea();" name="txtName" />
<input type="text" id="txtSurname" onkeyup="UpdateTextArea();" name="txtSurname" />
</div>
<textarea id="textAreaResult"></textarea>
Javascript
<script type="text/javascript">
function UpdateTextArea() {
var textBoxContainerDiv = document.getElementById("textBoxContainer");
var textboxes = textBoxContainerDiv.getElementsByTagName("input");
var finalResult = "";
var textAreaFinalResult = document.getElementById("textAreaResult");
for (var i = 0; i < textboxes.length; i++) {
finalResult = finalResult + textboxes[i].id + "=" + textboxes[i].value + ",";
}
textAreaFinalResult.value = finalResult;
}
</script>
Hope this Helps! :)
For the record, I feel like this code is an ugly hack, but it should do the trick...
var fieldName = "txtName"; //your field name
var newValue = "Alex"; //your new value
var value = document.getElementById("my-textarea").value;
value = "," + value; //add a comma so we can ensure we don't replace the wrong value where the fieldname is a substring of another fieldname
if(value.indexOf("," + fieldName + "=") > 0) //see if a value is already defined
{
var index = value.indexOf("," + fieldName + "=") + fieldName.length + 2;
var start = value.substring(0, index); //get the portion before the value
var end = value.substring(index); //get everything else
if(end.indexOf(",") > 0)
{
end = end.substring(end.indexOf(",")); //remove the value by reducing the end to the location of the next comma
}else{
end = ""; //if there isn't another comma it was the last value in the list, so set the new end to nothing
}
value = start + newValue + end;
value = value.substring(1); //remove the starting comma we gave it
document.getElementById("my-textarea").value = value;
}else{
//append it to the end as you are already doing
}

Categories

Resources