Write elements to textarea using jQuery - javascript

I want to get a text from a and add some attributes to the text and show it in another when a button is pressed.
Here is a part of my code - If I use console.log() the correct text will be logged, but the append(x) only writes the option[i] value without any HTML codes.
What should be the solution here?
var options;
$(function() {
options = $('div#Thelper2_container textarea').val().split('\n');
$.fillTextArea();
});
$.fillTextArea = function() {
for (let i = 0; i < options.length; i++) {
var y = i + 1;
var x = String('<span class="textToSelect" value="' + y + '"></span>' + options[i] + '</span>\n');
$('div#Thelper4_container textarea').append(x);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="Thelper2_container">
<textarea rows="5" cols="100">Line 1
Line 2
</textarea>
</div>
<div id="Thelper4_container">
<textarea rows="5" cols="100"></textarea>
</div>

Use val instead of append. Append is for non-form field container elements
Although you CAN append to a textarea, when you append, you append HTML and not text.
Also you have too many </span>s and spans do not have values. I changed to data-value
Lastly I filter empty lines
const $txtarea = $('#Thelper2_container textarea');
const $output = $('#Thelper4_container textarea');
const splitLines = val => val
.split('\n')
.filter(line => line.trim() !== "") // drop empty lines
.map((line,i) => `<span class="textToSelect" data-value="${i+1}">${line.trim()}</span>`)
.join("\n");
$(function() {
$output.val(splitLines($txtarea.val()));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="Thelper2_container">
<textarea rows="5" cols="100">Line 1
Line 2
</textarea>
</div>
<div id="Thelper4_container">
<textarea rows="5" cols="100"></textarea>
</div>

Try this:
$('div#Thelper4_container textarea').append(document.createTextNode(x));
Please note the 'document.createTextNode'.

You're appending another </span>\n at the end of the string without opening it anywhere.
Try this code and see if it works:
var x = String('<span class="textToSelect" value="' + y + '"></span>' + options[i] + '\n');

Related

How to show input value and label from a div

Goal: Show a label, and input value from a different div and display it in a different section
I have a div that dynamically generates a set of input fields, and I am trying to then display that input fields value and their corresponding labels in a different section.
For example:
Step 1 - User enters in the number 5 into an input field.
Step 2 - There are 5 input fields created (based on value entered from step 1). Those input fields are labeled #1, #2, #3, etc... all the way to #5 or whatever number the user entered in Step 1.
Step 3 - User is presented with a new HTML section that lists off the labels (#1, #2, #3, etc.) and next to the labels is the value the user entered for those corresponding input fields.
Here is the code created for Step 2:
<label>#' + count + '</label>
<input type="number" name="length_field" value="" class="form-control length_field" />
Then, I need some javascript/jquery to take the labels and their corresponding input values and display then something like this:
<p>[LABEL #1] <span>[LABEL #1 INPUT VALUE]</span></p>
<p>[LABEL #2] <span>[LABEL #2 INPUT VALUE]</span></p>
<p>[LABEL #3] <span>[LABEL #3 INPUT VALUE]</span></p>
Etc...
For step 2 you need to check the value of your length_field input and create that many inputs by JavaScript. Set some helper ID and CLASS attributes so you can get values later.
For step 3 use that attributes to get input field values and set them as result div's html.
$(document).on('change', '#length_field', function() {
var inputsCount = parseInt($(this).val());
$('#inputsWrapper').html('');
$('#result').html('');
for (var i = 1; i <= inputsCount; i++) {
// Create custom input with label
var tempInput = document.createElement('input');
tempInput.setAttribute('name', i);
tempInput.setAttribute('id', i);
tempInput.setAttribute('class', 'customInputs');
var tempInputLabel = document.createElement('label');
tempInputLabel.setAttribute("for", i);
tempInputLabel.innerHTML = 'Input #' + i + ": ";
$('#inputsWrapper').append(tempInputLabel);
$('#inputsWrapper').append(tempInput);
// Create corresponding value presenter in result div
var resultRow = document.createElement('p');
resultRow.setAttribute('id', 'result-' + i);
resultRow.innerHTML = 'Label #' + i + ':';
$('#result').append(resultRow);
}
});
$(document).on('keyup', '.customInputs', function() {
var id = $(this).attr('id');
var inputValue = $(this).val();
$('#result-' + id).html('Label #' + id + ': <span> ' + inputValue + '</span>');
});
#inputsWrapper input {
display: block;
margin-bottom: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="length_field">Enter the number of inputs you want:</label>
<input type="number" name="length_field" id="length_field" />
<br/>
<div id="inputsWrapper">
</div>
<hr>
<div id="result">
</div>
This is really quick'n'dirty but it works.
I'm using a for-loop in both steps, in the first step the for-loop is generating the input fields and outputting them after.
In the second step I'm saving the html of the resulting paragraphs in a variable, because I can't override the document, because my wanted values are in the input fields.
The on keypress listener is optional and ensures that you don't have to press the Submit button with your mouse ;)
If I could help you i would appreciate if you could mark this answer as accepted.
let number = 0;
$(document).on("click", "#step1", function() {
number = $("input").val();
if (number > 0) {
let html = "", i;
for (i = 1; i <= number; i++) {
html += "<label for='input_" + i + "'>#" + i + "</label>: <input type='text' id='input_" + i + "'><br>";
}
html += "<button id='step2'>Submit</button>"
$("body").html(html);
}
})
$(document).on("click", "#step2", function() {
let html = "", i;
for (i = 1; i <= number; i++) {
html += "<p>Label #" + i + ": <span>" + $("#input_" + i).val() + "</span></p>";
}
$("body").html(html);
})
$(document).on('keypress', function(e) {
if (e.which == 13) {
$("button").trigger("click");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" placeholder="Number of fields">
<button id="step1">Submit</button>

populate input fields from php / javascript

How can I populate 50 html5 input fields from an external delimited "|" text file ("players.txt"):
Smith, Bob|Jones, James|Cavanaugh, Harvey|
I have input fields like so:
<input type="text" name = "N01" id = "I01">
<input type="text" name = "N02" id = "I02">
<script>
$jQuery.get('assets/players.txt', function(data) {
splitString = dataString.split("|");
$('#I01').val(splitString[0]);
$('#I02').val(splitString[1]);
$('#I03').val(splitString[2]);
});
</script>
Try getting html elements using jquery $ sign such as
$('#I01').val(splitString[0]);
$('#I02').val(splitString[1]);
$('#I03').val(splitString[2]);
You're currently referencing the wrong data variable dataString, instead reference data. Also, if you know your IDs are sequential, you can avoid writing 50 different lines of JS and run a for loop, for instance:
for(i=0; i<splitString.length; i++){
id = "#I0"+(i+1);
$(id).val(splitString[i]);
}
Don't set the value of each element individually, use a forEach loop.
Make sure to take into account string padding.
splitString.forEach((str, i) => {
document.querySelector('#I' + String(i).padStart(2, '0'))
.value = str;
});
let dataString = "Smith, Bob|Jones, James|Cavanaugh, Harvey|";
let splitString = dataString.split("|");
for (let i = 0; i < splitString.length; i++) {
$("#I0" + i).val(splitString[i]);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="N01" id="I01">
<input type="text" name="N02" id="I02">
Example without ajax:
$(function(){
var splitString = 'Smith, Bob|Jones, James|Cavanaugh, Harvey';
splitString = splitString.split("|");
$('#playersInputs').empty();
$.each(splitString, function(i,v){
$('<input type="text" />')
.attr('name', 'N'+("0"+(i+1)).slice(-2))
.attr('id', 'I'+("0"+(i+1)).slice(-2))
.val(v)
.appendTo('#playersInputs');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='playersInputs'>
</div>
Example With ajax:
you must replace /path/to/your/text-file with the actual url
$(function(){
$.get('/path/to/your/text-file', function(data) {
var splitString = data.split("|");
$('#playersInputs').empty();
$.each(splitString, function(i,v){
$('<input type="text" />')
.attr('name', 'N'+("0"+(i+1)).slice(-2))
.attr('id', 'I'+("0"+(i+1)).slice(-2))
.val(v)
.appendTo('#playersInputs');
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='playersInputs'>
</div>

Adding bullet points to multiple textareas with same Javascript

I found the below code online to add bullet points to a textarea, and it works quite well for a single textarea.
Script
var CRLF = 10;
var BULLET = String.fromCharCode(45);
function Init() {
var textareas = document.querySelectorAll('textarea');
[].forEach.call(textareas, function(element) {
element.addEventListener("input", OnInput, false);
});
}
function OnInput(event) {
char = event.target.value.substr(-1).charCodeAt(0);
nowLen = txt.value.length;
if (nowLen > prevLen.value) {
if (char == CRLF) txt.value = txt.value + BULLET + " ";
if (nowLen == 1) txt.value = BULLET + " " + txt.value;
}
prevLen.value = nowLen;
}
HTML
<body onload="Init ();">
<h4>Automatic bullets in a text box</h4>
<textarea id="txt" oninput="OnInput(this, 'prevLen');" rows="15" cols="40"></textarea>
<input type="hidden" id="prevLen" value="0"/>
</body>
However, I can't figure out how to create a similar function such that I can use it on multiple textareas.
I would like something where I can pass through the id of the hidden input, so I can specify that way which input to add the bullet points to, but can't get a working solution.
Suggestions/solutions welcome.
Get a list of all textareas and add the event listener
var textareas = document.querySelectorAll('textarea');
[].forEach.call(textareas, function(element) {
element.addEventListener("click", OnInput, false);
});
You can use any valid CSS3 selector to get the desired textareas.
As per your edit:
You can group the elements together so you can access them as a group. Now you can use the input in any way you like.
<div class="some_wrapper">
<textarea id="txt" oninput="OnInput(this, 'prevLen');" rows="15" cols="40"></textarea>
<input type="hidden" id="prevLen" value="0"/>
</div>
var wrappers = document.querySelectorAll('some_wrapper');
[].forEach.call(wrappers, function(wrapper) {
var textarea = wrapper.querySelector("textarea"),
input = wrapper.querySelector("input");
//process "input" to get the desired "id", "class",.....
textarea.addEventListener("click", function(e) {
OnInput(e, input)
}, false);
});
Solution to my query/issue:
Script/app.js:
var CRLF = 10;
var BULLET = String.fromCharCode(45);
function Init() {
var wrappers = document.querySelectorAll('panel-body');
[].forEach.call(wrappers, function(wrapper) {
var textarea = wrapper.querySelector("textarea"),
input = wrapper.querySelector("input");
textarea.addEventListener("input", OnInput(), false);
});
}
function OnInput(ta,inp) {
char = ta.value.substr(-1).charCodeAt(0);
nowLen = ta.value.length;
if (nowLen > inp.value) {
if (char == CRLF) ta.value = ta.value + BULLET + " ";
if (nowLen == 1) ta.value = BULLET + " " + ta.value;
}
inp.value = nowLen;
}
HTML
<body onload="Init ();">
<div class="panel-body">
<h4>Automatic bullets in a text box</h4>
<textarea id="ta1" oninput="OnInput(ta1, pv1);" rows="15" cols="40"></textarea>
<input type="hidden" id="pv1" value="0"/>
<h4>Automatic bullets in a text box</h4>
<textarea id="ta2" oninput="OnInput(ta2,pv2);" rows="15" cols="40"></textarea>
<input type="hidden" id="pv2" value="0"/>
</div>
</body>
The above solution solves the issue of adding bullets to multiple textareas.

passing/displaying values from JavaScript to HTML page

I have the following JS code which use's local storage to display the 'name' and 'age' entered previously:
This HTML code currently displays the date, time, name and age of a person in a table. how can i pass these values to be displayed in a HTML form as labels instead of in that table?
HTML only bringing back the start time, name and age aren't being displayed:
<div id="history_list"></div>
<div id="name"> </div>
<div id="age"></div>
JS:
function loadHistoryList() {
for(var i = numberOfHistory; i >= 1; i--) {
var historyData = new historyElement(db.getItem(i.toString()));
if(historyData === null) {
console.error('error');
continue;
}
$('#history_list').append(historyData.startTime);
$('#name').append(historyData.name);
$('#age').append(historyData.age);
}
}
instead of
var div = '<div id="history_element"><div id="element_title">' + historyData.startDate + ' ' + historyData.startTime + '</div><table>';
var div = '<div id="name"><tr><td>name: </td><td>' + historyData.name+ '</td></tr>';
var div = '<div id="age"><tr><td>age: </td><td>' + historyData.age+ '</td></tr>';
div += '</table></div>';
$('#history_list').append(div);
$('#name').append(div);
$('#age').append(div);
Do this:
$('#history_list').append(historyData.startTime);
$('#name').append(historyData.name);
$('#age').append(historyData.age);
In short: you can (and should in this case) simply add the desired value to the container (the DIV, Form field, or whatnot)
those three lines starting witn var div (...) are overwriting each previous line, but that is a side note.
Overall, you should read up more on JavaScript and/or JQuery.
To populate the form field First you have to add a form element like input field
HTML
<div id="history_list">
</div>
<input type="text" id="name" name="name">
JS
function loadHistoryList() {
for(var i = numberOfHistory; i >= 1; i--) {
var historyData = new historyElement(db.getItem(i.toString()));
if(historyData === null) {
console.error('error');
continue;
}
$('#name').val(historyData.name);
}
}

How can I add a max length message with Jquery 'after' to a class of inputs and update it

I'm trying to get Jquery to append ('after') to some (class) of my inputs so the user knows how much more they can type. Is this even possible?
<script>
$(function() {
$(".maxinputmessage") .after("<br><em>(Maximim characters: " + document.getElementById(this).maxLength + ") You have " + ( document.getElementById(this).maxLength - document.getElementById(this).Length) + " characters left.</em>");
});
</script>
with:
<label for="EditPVComment">PV Comments</label>
<textarea class="maxinputmessage" id="EditPVComment" name="EditPVComment" cols="80" rows="10" maxlength="3000" style="width:400px;">Some text here maybe.</textarea>
I got stuck with the maxLength and I would also like to update as they type and tell them how many characters they have left. (Is this to much for Jquery?) Thanks!
Try this. When inserting the element to display the remaining count, I would recommend including a span or a div tag holder that you can use to update the information during "keyup" bind event on the textarea
<label for="EditPVComment">PV Comments</label>
<textarea class="maxinputmessage" id="EditPVComment" name="EditPVComment" cols="80" rows="10" maxlength="3000" style="width:400px;">Some text here maybe.</textarea>
<br>
<label for="EditManPVComment">Man PV Comments</label>
<textarea class="maxinputmessage" id="EditManPVComment" name="EditManPVComment" cols="80" rows="10" maxlength="3000" style="width:400px;">Some Man text here maybe.</textarea>
<script>
$().ready(function(){
var $this = $(".maxinputmessage");
$this.each(function()
{
var charMaxLen = $(this).attr("maxLength");
var charLen = $(this).val().length;
$(this).after("<em>(Maximim characters: " + charMaxLen + ") You have <span>" + (charMaxLen - charLen) + "</span> characters left.</em>");
$(this).on("keyup",function()
{
var charMaxLen = $(this).attr("maxLength");
left = charMaxLen - $(this).val().length;
$(this).next("em").find("span").text(charMaxLen - $(this).val().length);
});
});
});
</script>
Working example : http://jsfiddle.net/rpcwt2ng/4/
HTML
<input type="text" id="ipText" />
Remaining <span id="remaining"></span>
JavaScript
var limit = 50;
$("#ipText").keyup(function() {
$("#remaining").text(limit - $("#ipText").val().length);
});
Working demo here

Categories