I have a textarea html element and I want to save its value to a JSON file by stringifying it:
document.querySelector("#button").addEventListener("click", () => {
const rawText = document.querySelector("#textarea").value;
const jsonText = JSON.stringify(rawText);
console.log(jsonText);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<textarea id="textarea" cols="30" rows="10"></textarea>
<button id="button">log json stringified</button>
</body>
</html>
Running the snippet above, we can see two problems:
When the user types in a special character, JSON.stringify() automatically escapes it.
When the user enters a new line, JSON.stringify() adds a \n special character.
How to format the output such that it preserves any special characters that the user types and ignores new lines entered by the user?
For example when user types in:
one\ntwo\tthree\\nfour
five
I want to log:
"one\ntwo\tthree\\nfourfive"
Instead I am currently logging:
"one\\ntwo\\tthree\\\\nfour\nfive"
You could just remove the new lines:
const rawText = document.querySelector("#textarea").value.replace(/\n/g, "");;
Expanding from Eugen Sunic's answer, the solution is:
const rawText = document.querySelector("#textarea").value.replace(/\n/g, "");
const jsonText = JSON.stringify(rawText).replace(/\\\\/g, "\\");
Related
PLeaseHelp. it wont show the Value, even for form authentication, to get username & password values,I was trying the same methods.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=<device-width>,initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1 id="result">Selected movie is </h1>
<select id="movie" onchange="showmovie()">
<option value="Spiderman">Spiderman</option>
<option value="Spiderman2">Spiderman2</option>
<option value="Spiderman3">Spiderman3</option>
</select>
</body>
</html>
<script>
var movie = document.getElementById("movie").value
function showmovie(){
alert("Changed")
document.getElementById("result").innerHTML="Movie chosen is"+movie
}
</script>
Try with this function showmovie
<script>
function showmovie() {
//Selected option
var selectedMovie = document.getElementById("movie").value;
document.getElementById("result").innerHTML = "Movie chosen is " + selectedMovie;
}
</script>
The issue here is because of the line var movie = document.getElementById("movie").value being executed just one time at the beginning (you could verify that adding console.log(movie); just after the movie variable declaration)
(movie stores then the value 'Spierdaman') and it never executes again with the calls for showmovie() function, so you could just move the movie declaration line above inside the function so it executes each time the action occurs and then having the good values.
Other details : To have a compliant code i suggest moving the script bloc to part just before and dont forget to add semicolons ';' at the end of each line ! + Better approach would be to use an eventListener as suggested by #T.J. Crowder in comments section above
I am calling a SOAP service in my Javascript code, and the response of this service is correct but strings returned does not show letters with accents. So, I have a problem with encoding charset and I am trying the following actions:
1) I ensure that the HTTP response returning string data has the correct charset defined. So, I have checked with https://validator.w3.org/i18n-checker/ that the encoding charset of the URI that I am calling is "utf-8".
2) I have defined charset in the head section of html:
<meta charset='utf-8' content-type="text/xml;charset=UTF-8"/>
3) Also, I call this service with a function in module.js, I have also defined
<script src="node_modules/my_module.js" charset="utf-8"></script>
All three with the same wrong result.
I added an image with the some examples:
image with result strings, where in green square have to say 'Sant Martí de Tous', in red 'Moianès', in blue 'Santa Bàrbara', 'Montsià', in orange 'Torroella de Montgrí', etc
This is a minimum sample code to call SOAP service with tinysoap library:
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' content-type="text/xml; charset=utf-8"/>
<title>Test Charset Encoding</title>
<link rel="stylesheet" href="https://js.arcgis.com/4.15/esri/themes/light/main.css"/>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="node_modules/tinysoap/tinysoap-browser-min.js"></script>
<script src="https://js.arcgis.com/4.15/"></script>
<script>
var tinySoap=this.tinysoap;
require(["esri/Map"], function(Map) {
var inputCtrl = document.getElementById("inputString"); // gironès
var outputCtrl = document.getElementById("outputString");
inputCtrl.onchange = function() {
var userTxtValue = inputCtrl.value;
var args = {nom: userTxtValue};
//console.log("[INPUT] : ",args);
//outputCtrl.innerHTML = "<br><b>Input ... </b>" + userTxtValue +"<br>";
tinySoap.createClient(url, function(err, client){
client.localitzaToponim(args, function(err, result) {
var data = result['item'];
//console.log("[OUTPUT] : ",data);
//outputCtrl.innerHTML += "<b>Output ... </b>";
//data.forEach(element => {
// outputCtrl.innerHTML += "<br> "+ element.Nom;
//});
});
});
}
});
</script>
</head>
<body>
Look for place or address ...
<input id="inputString" size="50" value=""><br>
<span id="outputString"></span>
</body>
</html>
This is the result of this process for 'gironès' as input string
There is the error: "Refused to set unsafe header", but I can not see where to set header parameters to connection.
I am still working in that problem: I have checked that strings are encoded as UTF16 with this library: https://github.com/polygonplanet/encoding.js/
using Encoding.detect(string), but Encoding.convert(string,'utf8','utf16') does not work for me, neither Encoding.convert(string,'latin1','utf16'), etc
What is the right way to define the encoding charset? Thank you
I have a textbox in html where I want to remove all the special characters at the start & end of the string, there are lots of answers to remove the string at index 0/str.length or using string.replace or regex. But if there is no answer about how to get rid of all the special characters in the start & end of the textbox data. I have the character range as .,:'-_ / that cannot be at the start or end of input.
In jquery, I have a blur event which will do the task of trimming out the chars in the range
Eg pseudo code:
$( "#txtbox1" ).blur(function(){
var regex = "(\.\,\:\'\\\-\_\/)+";
var str = $(this).val();
$(this).val(str.replace(regex,""));
});
But somehow I am not able to understand how to specify that the replace is suppose to be only at start & end not in the middle. As the textbox can have two sentences. Any suggestions are appreciated.
You can use the regex below to achieve your result:
^[-.,:'_/]+|[-.,:'_/]+$
Explanation of the above Regex:
^ - Represents the start of the test String.
| - Represents alternation.
$ - Represents end of the given test string.
[-.,:'_/]+ - Start or end of the string contains one or more of the characters mentioned.
Demo of the above regex here.
Implementation in JAVASCRIPT(JQUERY). You can modify the code accordingly.
const regex = /^[-.,:'_/]+|[-.,:'-_/]+$/gm;
const str = `bsvisbvskbvksv
nvlvnlvlv slcls
vnelvnelvnelv vnvsvnlvnl!
ocnsocnsocnosc ohoiIBIBiiwciv!
:nvkvnskvbskv
-bvksvbskvbsk sncksncks -cnscns-
--bvsjvbjvbjbvdbvkdbvkd-- vvnskvnskd --
lsvnslvnlsvnls:
Hello world
hellow WOLDF`;
//Notice in the 6th case above; only the last "-" gets replaced
const subst = ``;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
So... I'm fairly new to regex but I've worked out something that should work for you, if not let me know:
$('#form').on('submit', (e) => {
e.preventDefault();
let value = $('input[name="input"]').val();
value = value.replace(
/^[!##$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/, // Replace first character
''
);
value = value.replace(
/[!##$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]$/, //Replace last character
''
);
console.log(value); // => Gives you the replaced value
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<form id="form">
<input type="text" name="input" />
<input type="submit" />
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</body>
</html>
JSON.parse is giving error Unexpected end of Json data on this json encoded string which contain single quotes
[{"size":"20cm\/S","characters_cost":[{"characters":"~!##$%\"'","cost":"78"}]}]
const json = document.querySelector('#cCalc').textContent;
const array = JSON.parse(json);
console.log(array);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<input type="hidden" id="cCalc" value="[{"size":"20cm\/S","characters_cost":[{"characters":"abcdefghijklmnopqrstuvwxyz0123456789","cost":"42"},{"characters":"ABCDEFGHIJKLMNOPQRSTUVWXYZ","cost":"48"},{"characters":"~!##$\"'","cost":""}]},{"size":"25cm\/M","characters_cost":[{"characters":"abcdefghijklmnopqrstuvwxyz0123456789","cost":"52"},{"characters":"ABCDEFGHIJKLMNOPQRSTUVWXYZ","cost":"60"}]},{"size":"30cm\/L","characters_cost":[{"characters":"abcdefghijklmnopqrstuvwxyz0123456789","cost":"62"},{"characters":"ABCDEFGHIJKLMNOPQRSTUVWXYZ","cost":"71"}]},{"size":"38cm\/XL","characters_cost":[{"characters":"abcdefghijklmnopqrstuvwxyz0123456789","cost":"75"},{"characters":"ABCDEFGHIJKLMNOPQRSTUVWXYZ","cost":"86"}]}]">
</body>
</html>
You have two major problems.
textContent gives you the text in the child nodes of an element. An input is a void element. It has no child nodes. It's value can be read with the value property.
Your HTML is invalid. You are trying to use raw " characters in the value attribute's value, but that value is delimited with " so the first one marks the end of the value. You need to express them as " instead of "
Such:
const textContent = document.querySelector('#cCalc').textContent;
const json = document.querySelector('#cCalc').value;
const array = JSON.parse(json);
console.log({textContent, json, array});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<input type="hidden" id="cCalc" value="[{"size":"20cm\/S","characters_cost":[{"characters":"abcdefghijklmnopqrstuvwxyz0123456789","cost":"42"},{"characters":"ABCDEFGHIJKLMNOPQRSTUVWXYZ","cost":"48"},{"characters":"~!##$\"'","cost":""}]},{"size":"25cm\/M","characters_cost":[{"characters":"abcdefghijklmnopqrstuvwxyz0123456789","cost":"52"},{"characters":"ABCDEFGHIJKLMNOPQRSTUVWXYZ","cost":"60"}]},{"size":"30cm\/L","characters_cost":[{"characters":"abcdefghijklmnopqrstuvwxyz0123456789","cost":"62"},{"characters":"ABCDEFGHIJKLMNOPQRSTUVWXYZ","cost":"71"}]},{"size":"38cm\/XL","characters_cost":[{"characters":"abcdefghijklmnopqrstuvwxyz0123456789","cost":"75"},{"characters":"ABCDEFGHIJKLMNOPQRSTUVWXYZ","cost":"86"}]}]">
</body>
</html>
The value attribute is not correctly sanitized:
You first need to HTML-entity encode the attribute contents, and then you will be able to correctly parse the JSON on the client.
I have created a simple login page with hardcoded username and password, I was successful in calling the next page once the login credentials are passed but I am having a tough time passing the user name entered in page 1 to appear on page 2.
I tried to find a way to make user inputs as global variables in js file so I can use the same variables in the second page but I am unsuccessful.
greeter.html
<body>
<h1>Simple Login Page</h1>
<form name="login">
Username<input type="text" name="userid"/>
Password<input type="password" name="pswrd"/>
<input type="button" onclick="check(this.form);" value="Login"/>
<input type="reset" value="Cancel"/>
</form>
<p id = "passwarn"></p>
<script language="javascript" src="source.js">
</script>
</body>
source.js
function check(form) { /*function to check userid & password*/
/*the following code checkes whether the entered userid and password are
matching*/
let uid = form.userid.value;
let pswrd = form.pswrd.value;
if(uid == "shiva" && pswrd == "mypswrd") {
window.open('test.html')/*opens the target page while Id & password
matches*/
}
else {
document.getElementById("passwarn").innerHTML = "User name or
password is incorrect!"/*displays error message*/
}
}
test.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script language="javascript" src="source.js"></script>
<h1> Hello <span id = "UI"></span></h1>
</body>
</html>
I want Hello shiva printed on the test.html page, I do not want to use jquery while doing so, is there any way?
You can simply reference the value from the opening page in test.html.
To make things more straightforward, add an ID to the Username field :
Username <input type="text" name="userid" id="userid">
Then you can grab and display the value from the opened window like this :
<h1> Hello
<script>
document.write(window.opener.document.getElementById("userid").value)
</script>
</h1>
If you want to do things a little more elegantly, you could keep the scripting in your .js file and change the innerHTML of your "UI" span from there.
Bear in mind that cross-origin scripting rules mean that this will only work when served from the same domain.
Following on from the comments from your question two key points to identify
This is a very insecure way to do this
You may want to use cookies if the user if going to traverse many pages (not sponsoring, but I would recommend js-cookie, I have used it for a while and it's pretty robust)
In order to get what i believe you wanted to work i had to do a couple of this.
Put your JS on the page as for testing it quicker to have it all accessible on one page
I use function that is for parameter grabbing (yes this is completely insecure but would achieve what you want, a cookie would be more secure) you can find it here.
I renamed your inputs from names to ID's as they are more accessible in javascript this way.
This function when used with decode and encode URI components in javascript will help you pass the data from one page to another see code below
Greeter.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1>Simple Login Page</h1></script>
<form name="login">
Username<input type="text" id="userid"/>
Password<input type="password" id="pswrd"/>
<input type="button" value="Login" id="LoginSubmit"/>
<input type="reset" value="Cancel"/>
</form>
<p id = "passwarn"></p>
<script type="text/javascript" src="./source.js"></script>
</body>
</html>
then your test.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1> Hello <span id="UI"></span></h1>
<script type="text/javascript" src="./source.js"></script>
</body>
</html>
Finally your source.js
window.onload = checkpage(window.location.href);
function checkpage(url){
if(url.split('/').pop() == 'greeter.html'){
document.getElementById('LoginSubmit').addEventListener('click',function () {
var uid = document.getElementById('userid').value;
var pswrd = document.getElementById('pswrd').value;
console.log(uid, pswrd);
check(uid, pswrd);
});
}
else{
document.getElementById("UI").innerHTML = getAllUrlParams(decodeURIComponent(window.location.href)).uid;
}
}
function check(uid, pswrd) { /*function to check userid & password*/
/*the following code checkes whether the entered userid and password are
matching*/
let redirect = "test.html"
let parameters = encodeURIComponent('uid='+uid);
if(uid == "shiva" && pswrd == "mypswrd") {
window.open(redirect+"?"+parameters)/*opens the target page while Id & password
matches*/
}
else {
document.getElementById("passwarn").innerHTML = "User name or password is incorrect!"/*displays error message*/
}
}
function getAllUrlParams(url) {
// get query string from url (optional) or window
var queryString = url ? url.split('?')[1] : window.location.search.slice(1);
// we'll store the parameters here
var obj = {};
// if query string exists
if (queryString) {
// stuff after # is not part of query string, so get rid of it
queryString = queryString.split('#')[0];
// split our query string into its component parts
var arr = queryString.split('&');
for (var i = 0; i < arr.length; i++) {
// separate the keys and the values
var a = arr[i].split('=');
// set parameter name and value (use 'true' if empty)
var paramName = a[0];
var paramValue = typeof (a[1]) === 'undefined' ? true : a[1];
// (optional) keep case consistent
paramName = paramName.toLowerCase();
if (typeof paramValue === 'string') paramValue = paramValue.toLowerCase();
// if the paramName ends with square brackets, e.g. colors[] or colors[2]
if (paramName.match(/\[(\d+)?\]$/)) {
// create key if it doesn't exist
var key = paramName.replace(/\[(\d+)?\]/, '');
if (!obj[key]) obj[key] = [];
// if it's an indexed array e.g. colors[2]
if (paramName.match(/\[\d+\]$/)) {
// get the index value and add the entry at the appropriate position
var index = /\[(\d+)\]/.exec(paramName)[1];
obj[key][index] = paramValue;
} else {
// otherwise add the value to the end of the array
obj[key].push(paramValue);
}
} else {
// we're dealing with a string
if (!obj[paramName]) {
// if it doesn't exist, create property
obj[paramName] = paramValue;
} else if (obj[paramName] && typeof obj[paramName] === 'string'){
// if property does exist and it's a string, convert it to an array
obj[paramName] = [obj[paramName]];
obj[paramName].push(paramValue);
} else {
// otherwise add the property
obj[paramName].push(paramValue);
}
}
}
}
return obj;
}
So long as your HTML files are in the same folder you can run this. The main thing to notice is that you are binding the event listener to the element, getting the values input and then submitting them to the function.
I have added a function that retrieves the url of the page location and pops out the last bit of it and runs a check on it to ensure you are looking at the right place to run the correct code. as this runs on load then the subsequent functions run after. You can further refactor this to modularise it and ensure that it's cleaner to read if you wanted.
Splitting it out this way will make it easier when trying to implement a cookie as you can in the event listener (with a cookie created) can save those values to it on your greet page and then call them back after on your test page.
Hope that helps