I need a textarea to include a set of double quotes at the start and end of the textarea value. The below code works in that double quotes are added to the start and end of the field, but if the user enters text and then goes back to the field, multiple double quote sets can be added. How can I prevent this? A jQuery solution is also acceptable.
<textarea name="quoteName" id="quoteName" style="width:100%" rows="4" onChange="quotes();" autofocus></textarea>
function quotes(){
var quoteValueBefore = document.getElementById("quoteName").value;
var ensureQuotes = "\"" + quoteValueBefore + "\"";
document.getElementById("quoteName").value = ensureQuotes;
}
Check to see if the text already begins with a quote, and if it already ends with one. If either is missing, add it.
Also check that the length >= 2, otherwise " would pass the test (ends with a quote? check. begins with a quote? check.)
function quotes() {
var quoteValue = document.getElementById("quoteName").value;
if (!quoteValue.match(/^"/))
quoteValue = '"' + quoteValue;
if (!quoteValue.match(/"$/))
quoteValue += '"';
if (quoteValue.length < 2)
quoteValue += '"';
document.getElementById("quoteName").value = quoteValue;
}
<textarea name="quoteName" id="quoteName" style="width:100%" rows="4" onChange="quotes();" autofocus></textarea>
function checkQuotes(id) {
str = document.getElementById(id).value;
if (str[0] != '"') {
str = '"'.concat(str);
}
if (str[str.length - 1] != '"') {
str = str.concat('"')
}
return str
}
function quotes() {
withQuotes = checkQuotes("quoteName");
document.getElementById("quoteName").value = withQuotes
}
<textarea name="quoteName" id="quoteName" style="width:100%" rows="4" onchange="quotes()">testing the quotes feature</textarea>
This snippet will check if the first character is a quote, if it isn't it will prepend it. It also checks if the last character is a quote, if it isn't it will append it. This probably isn't the most friendly UI solution, and I recommend either adding this through CSS if you're using it for display purposes, or using PHP or whatever you're doing for the backend form submission.
Related
One simple way to remove whitespaces in my case is to do like this -
<textarea id="thetext" lines="8" style="width: 100%; height: 8em;">
hello, how are you
i'm fine
And i hope the same from you
</textarea><br>
<button onclick="whitespaces()">Vanish</button>
<script>
function whitespaces() {
var input = document.getElementById("thetext");
input.value = input.value
.replace(/\t{1,}/g, "")
.replace(/\n{3,}/g, '\n\n')
.replace(/ {1,}/g, ' ')
.replace(/^ /gm, '')
.replace(/ $/gm, '')
.replace(/^\n{1,}/g, '')
.replace(/\n{1,}$/g, '');
}
</script>
However I'm trying to achieve the same objective with negative condition. That is by using minus or something like that. As i'm new to js, i'm not familiar with negative conditions. So can anyone tell me how to use negative condition in this case. The code should look something like this -
function whitespaces() {
var input = document.getElementById("thetext");
input.value = input.value.replace(all whitespaces [\s] minus linebreak [\n] and paragraph breaks [\n\n])
}
SOLUTION 1
You can use the following regular expression to match all whitespace characters except newlines.
[^\S\r\n]
That is, not-not-whitespace (the capital S complements) or not-carriage-return or not-newline. Distributing the outer not (i.e., the complementing ^ in the character class) with De Morgan's law, this is equivalent to “whitespace but not carriage return or newline.” Including both \r and \n in the pattern correctly handles all of Unix (LF), classic Mac OS (CR), and DOS-ish (CR LF) newline conventions.
From this stackoverflow answer.
SOLUTION 2
In javascript you can also use a replacer function to check each match and return the replacement string only if it meets certain conditions. The replacer function here checks for each whitespace whether it is a line break.
<textarea id="thetext" lines="8" style="width: 100%; height: 8em;">
hello, how are you
i'm fine
And i hope the same from you
</textarea><br>
<button onclick="whitespaces()">Vanish</button>
<script>
function whitespaces() {
var input = document.getElementById("thetext");
var inputVal = input.value;
inputVal = inputVal.replace(/\s/g, function(match){
return match === '\n' ? match : '';
});
input.value = inputVal;
}
</script>
SOLUTION 3
Another possible solution is to first replace all the paragraph breaks and line breaks by some bogus text (without whitespaces). Then do the whitespace replacement. After that convert the bogus texts back to paragraph and line breaks. (Note that since paragraphs are double line breaks, you do not need the line with the paragraph break replacement.)
<textarea id="thetext" lines="8" style="width: 100%; height: 8em;">
hello, how are you
i'm fine
And i hope the same from you
</textarea><br>
<button onclick="whitespaces()">Vanish</button>
<script>
function whitespaces() {
var input = document.getElementById("thetext");
var inputVal = input.value;
inputVal = inputVal.replace(/\n\n/g, "somebogustextforparagraphbreaks");
inputVal = inputVal.replace(/\n/g, "somebogustextforlinebreaks");
inputVal = inputVal.replace(/\s{1,}/g, "");
inputVal = inputVal.replace(/somebogustextforparagraphbreaks/g, "\n\n");
inputVal = inputVal.replace(/somebogustextforlinebreaks/g, "\n");
input.value = inputVal;
}
</script>
I have a div in which I render through javascript inputs and text dynamically. I am trying to capture the text of this div (both input values and text).
My first step if to capture the parent div:
let answerWrapper = document.getElementById("typing-answer-wrapper");
The issue now is that using the innerHTML will give me the whole html string with the given tags and using the inerText will give me the text, excluding the tags.
In the following case scenario:
the console inspect is:
What is the way to capture: $2.4 if the inputs have 2 and 4
and $null.null if the inputs are blank.
Any help is welcome
You could iterate over all of the element's child nodes and concatenate their wholeText or value else 'null'. For inputs the wholeText will be undefined. If they have no value we'll return 'null'. Be aware that spaces and line-breaks will also be included so you may want to strip these later (or skip them in the loop) but as a proof of concept see the following example:
var typingAnswerWrapper = document.getElementById("typing-answer-wrapper");
function getVal(){
var nodeList = typingAnswerWrapper.childNodes;
var str = "";
for (var i = 0; i < nodeList.length; i++) {
var item = nodeList[i];
str+=(item.wholeText || item.value || "null");
}
console.log(str);
}
getVal();
//added a delegated change event for demo purposes:
typingAnswerWrapper.addEventListener('change', function(e){
if(e.target.matches("input")){
getVal();
}
});
<div id="typing-answer-wrapper">$<input type="number" value=""/>.<input type="number" value="" />
</div>
Here's how you could do it :
function getValue() {
var parent = document.getElementsByClassName('typing-answer-wrapper')[0],
text = [];
const children = [...parent.getElementsByTagName('input')];
children.forEach((child) => {
if (child.value == '')
text.push("null")
else
text.push(child.value)
});
if (text[0] != "null" && text[1] == "null") text[1] = "00";
document.getElementById('value').innerHTML = "$" + text[0] + "." + text[1]
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
<div class="typing-answer-wrapper">
$
<input type="number"> .
<input type="number">
</div>
<button onclick="getValue()">get value</button>
<div id="value"></div>
You can fetch input feild values by their respective ids $('#input_feild_1').val() will give the first feild value and similarly $('#input_feild_2').val() for second feild and contruct use them to construct whatever as u wish. As in your case this should work
value_1 = $('#input_feild_1_id').val()
value_2 = $('#input_feild_2_id').val()
you need something like "$ + value_1 + . + value_2"
I want to convert all the + sign in the textarea field where the user types and parse that + sign and the text after it until the newline character into an HTML input checkbox.
For example, if the user, in the textarea, types:
+ Feed the kittens
+ Call the doctor
+ Go buy grocery
I want to parse it to something like:
<input type="checkbox"><label>Feed the kittens</label>
<input type="checkbox"><label>Call the doctor</label>
<input type="checkbox"><label>Go buy grocery</label>
I need to return this as a string with the HTML in it.
I created a function called listNote(note) that takes in note which is the text in the textarea. How should I go about writing this?
you may refer below code for an idea:
$(document).ready(function() {
$("#parseButton").click(function() {
var str = $("#mytext").val(); //get the text entered by user
var allLabels = str.split("+"); //split the text assuming that user will be writing data in required fashion
allLabels.shift(); //skip the 0th index of array which will be blank
var htmlString = "";
//iterate over all the tasks one by one to form html string
$.each(allLabels, function(index, value) {
htmlString += '<input type="checkbox"><label>' + value + '</label>';
});
//append the html to div
$("#myHtml").html(htmlString);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<textarea id="mytext" rows="4" cols="50">
+ Feed the kittens
+ Call the doctor
+ Go buy grocery</textarea>
<button id="parseButton">Parse</button>
</br>
</br>
Output:
<div id="myHtml"></div>
Here's what you need to do :
split the textarea content into separate notes, either splitting over + (but you need to ignore the first item of the array) or linefeed (but then you can't have multilines notes)
remove the leading + (a simple substring is enough)
add the tag opening and closing (string concatenation)
Hope it gets you started !
Try with simple split and ArrayMap
function change(){
var final="";
var res =$('textarea').val().split("+");
res.map(function(a){
if(a != ""){
final += '<input type="checkbox"><label>'+a+'</label>';
}
})
console.log(final)
$('body').append(final)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea cols="20" rows="4" >+ Feed the kittens
+ Call the doctor
+ Go buy grocery </textarea>
<button onclick="change()">click</button>
I have a string that conains HTML. In this HTML I have a textbox with text inside:
<div class="aLotOfHTMLStuff"></div>
<textbox>This textbox must be terminated! Forever!</textbox>
<div class="andEvenMoreHTMLStuff"></div>
Now I want to remove the textbox from that string, including the text inside. The desired result:
<div class="aLotOfHTMLStuff"></div>
<div class="andEvenMoreHTMLStuff"></div>
How can I achieve it? The two main problems: It is a string and not part of the DOM and the content inside the textbox is dynamic.
Here is an example that will look for the opening and closing tags in the string and replace anything in between.
const template = document.querySelector('#html')
const str = template.innerHTML
function removeTagFromString(name, str) {
const reg = new RegExp('<' + name + '.*>.*<\/'+ name +'.*>\\n*', 'gm')
return str.replace(reg, '')
}
console.log('before', str)
console.log('after', removeTagFromString('textbox', str))
<template id="html">
<div class="aLotOfHTMLStuff"></div>
<textbox>This textbox must be terminated! Forever!</textbox>
<div class="andEvenMoreHTMLStuff"></div>
</template>
If it is text string not HTML, you can convert it to DOM:
var str = '<div class="aLotOfHTMLStuff"></div><textbox>This textbox must be terminated! Forever!</textbox><div class="andEvenMoreHTMLStuff"></div>';
var $dom = $('<div>' + str + '</div>');
Then remove element from DOM:
$dom.find('textbox').remove();
If you need, can get string back:
console.log($dom.html());
Try this:
var string = '<div class="aLotOfHTMLStuff"></div><textbox>This textbox must be terminated! Forever!</textbox><div class="andEvenMoreHTMLStuff"></div>';
if ( string.includes("<textbox>") ) {
var start = string.indexOf("<textbox>");
var stop = string.indexOf("</textbox>");
string = string.replace(string.slice(start, stop+10), "");
}
console.log(string);
You can use parseHTML to convert string to html,
like..
var str = '<div class="aLotOfHTMLStuff"></div><textbox>This textbox must be terminated! Forever!</textbox><div class="andEvenMoreHTMLStuff"></div>';
var a = $.parseHTML(str);
var newstr = "";
a.forEach(function(obj) {
if ($(obj).prop('tagName').toLowerCase() != "textbox") {
newstr += $(obj).prop("outerHTML")
}
});
It's very simple and you can remove any tag in future by just replacing "textbox"
It is a string and not part of the DOM and the content inside the
textbox is dynamic.
So that html is in a js variable of type string? like this?:
var string = '<div class="aLotOfHTMLStuff"></div><textbox>This textbox must be terminated! Forever!</textbox><div class="andEvenMoreHTMLStuff"></div>';
So in that case you could use .replace(); like this:
string = string.replace('<textbox>This textbox must be terminated! Forever!</textbox>', '');
I am trying to make a simple replacement in a javascript form.
The form is submitting invoicenumber and amount to external payment gateway. The problem is the payment gateway doesn't accept , (comma) as seperator between the integer and fraction parts (ie. dollar,cent) but only (dollar.cent).
I want to make sure it accepts both characters . (dot) AND , (comma) so customer can use both and the form will just send . to external server.
UPDATE:
This is current javascript code:
`
function startPayment() {
var objForm = document.getElementById("ePay");
if (objForm.merchantnumber.value.length < 7) {
alert("Please enter your merchant!");
return false;
}
paymentwindow = new PaymentWindow({
'windowstate': 1,
'paymentcollection': 1,
'language': 1,
'merchantnumber': objForm.merchantnumber.value,
'amount': objForm.amount.value * "100",
'currency': "208",
'orderid': objForm.orderid.value,
});
paymentwindow.open();
}
function init() {
var sURL = String(window.location);
var arrURL = sURL.split("/");
var sAcceptURL = "";
var objForm = document.getElementById("ePay");
var n;
for (n = 0; n < arrURL.length - 1; n++)
sAcceptURL += arrURL[n] + "/";
objForm.cancelurl.value = sURL;
objForm.accepturl.value = sAcceptURL + "accept.html";
}
</script>`
This is the HTML code:
<tr>
<td>Amount:</td>
<td>
<input type="text" name="amount" value="" style="width: 200px;" />
</td>
<td>
Amount to pay
</td>
The solution to this would be either to replace the ',' with a '.' if that's what you're looking to do:
amount.replace(/,/g, '.');
What this line will do is use RegExp to find the occurrence of ',' and replace it with '.'. However, because you are creating a secure form to the back end, some recommended practices are to parse it at the back end first and confirm that there is no trace of things like SQL injection and make sure all input is valid. For example, if you are only looking to accept numbers and '.' in your input, I would use:
var rxCheck = /[0-9\.]*/g;
if (!rxCheck.test(amount)) {
// TODO: .. code if the input is invalid ..
}
Good luck in your search!
You can try this:
objForm.amount.value.split(",").join(".");
Or this:
objForm.amount.value.replace( /,/g, "." )
Beware: if your code is going to run in more cultures, you should handle this another way.