This question already has answers here:
Trim string in JavaScript
(20 answers)
Closed 9 years ago.
I need your help,
I can't seem to be able to strip away the whitespaces in my data string before adding them to my select box.
(BTW the spaces in between the data string are deliberate as I am working with an old dataset and slowly converting it to a non-space string)
How do you accomplish this? I thought that I had the logic all right:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function parseData() {
var data = "1234567, 8910111, 9632587,6541237,9631478, 1010232"
var options = data.split(",");
var select = document.getElementById('list')
select.innerHTML = ""
for(var i=0; i<options.length; i++)
select.options[i] = new Option(options[i], i);
}
</script>
</head>
<body>
<input type="button" value="load list" onclick="parseData()"/>
<br>
<select id="list"></select>
</body>
</html>
You can trim whitespaces when filling the selector:
options[i].replace(/^\s+|\s+$/g, '')
The jsfiddle is here.
No Regex required, use Options[i].trim() (trim removes any whitespace (including line breaks, tab stops and whatevs) on both sites of the string)
for(var i=0; i<options.length; i++)
select.options[i] = new Option(options[i].trim(), i);
Try this:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function parseData() {
var data = "1234567, 8910111, 9632587,6541237,9631478, 1010232"
var options = data.split(",");
var select = document.getElementById('list')
select.innerHTML = ""
for(var i=0; i<options.length; i++)
select.options[i] = new Option(options[i].replace(" ", ""), i); // cross browser
// or this one
//select.options[i] = new Option(options[i].trim(), i); // ie9+ and all other browsers
}
</script>
</head>
<body>
<input type="button" value="load list" onclick="parseData()"/>
<br>
<select id="list"></select>
</body>
</html>
Related
i'm making a web application which helps people to seek what disease they have according to the symptoms.
I want to the user to click specific symptom to add in the "u_symptom_i" array and show all of the changed array elements by alert function
However, i cannot see the added element by alert function
<script>
var j = 0;
while(j < escaped_cc.length) {
document.write('<th><button id="symptom_button">' + escaped_cc[j] + '</button></th>');
document.getElementById("symptom_button").value = escaped_cc[j];
j = j + 1;
}
$("button").click(function() {
u_symptom_i.push($(this).val());
alert($(this).val());
});
</script>
<!DOCTYPE html>
<html>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<body>
<h2>Insert Array</h2>
<input type="text" id="example" name="value">
<button id="button">Add array new item</button>
</body>
<script>
var array=[];
$("#button").click(function() {
var str = $("#example").val();
array.push(str);
alert(array);
});
</script>
</html>
Can you try this code? Adds each new value entered to an array named array and displays the records.
I want to replace a character in a string (original) with another string.
I am getting an error on running the debugger.
I dont understand what is wrong with the syntax.
<!DOCTYPE>
<html>
<head>
<title>HI there</title>
<meta lang="english">
</head>
<body>
<div>
Enter the original string<input id="original" value="" type="text"> <br>
Enter the replacing string<input id="replacing" value="" type="text"><br>
Enter the location to be replaced<input id="tobereplaced" value="" type="text"><br>
</div>
<br>
<button type="submit" onclick="replace()">Submit</button>
<br> Here you go the replaced string is:
<script>
function replace() {
var original = document.getElementById("original").value;
var replacing = document.getElementById("replacing").value;
var tobereplaced = document.getElementById("tobereplaced").value;
var replaced = "";
var originalLength = original.length;
var tobereplacedLength = tobereplaced.length;
var k = 0;
for (var i = 0; i < originalLength; i++) {
replaced.charAt(k) = original.charAt(i)
if (original.charAt(i) == replacing.charAt(0)) {
replaced = replaced + tobereplaced;
k = k + tobereplacedLength;
i++;
}
k++;
}
document.getElementById("replaced").innerHTML = replaced;
}
</script>
<h1 id="replaced"></h1>
</body>
</html>
you are trying to change the character of an empty string at line no:28 [replaced.charAt(k) = original.charAt(i)] this is the issue.
Also there are some unwanted increment in the code. please find the corrected below
I have updated the code below with // comment the code and added correct code. its working
// var k = 0; //Commented
// debugger; //Commented
for (var i = 0; i < originalLength; i++) {
if (original.charAt(i) == replacing.charAt(0)) {
replaced = replaced + tobereplaced;
// k = k + tobereplacedLength; //Commented
// i++; //Commented
} else{
replaced = replaced + original.charAt(i);
}
// k++; //Commented
}
Here is a more simplistic approach to the problem. It takes advantage of the .split() & .join() functions rather than using a for loop.
function replace() {
// set original string
var original = document.getElementById("original").value, // << use commas so you don't have to keep typing var
// set replacing string
replacing = document.getElementById("replacing").value,
// initialize newval
newValue,
// set replace position - this could also be called index
replacePosition = document.getElementById("tobereplaced").value; // << end variable declarations with semicolon
// split original string into array of characters
var splitOriginal = original.split("");
// use replacePosition as index value of character to replace
// & replace that character with replacing value
splitOriginal[replacePosition] = replacing;
// join array to form new string value
newValue = splitOriginal.join("");
document.getElementById("replaced").innerHTML = newValue;
}
<html>
<head>
<title>HI there</title>
<meta lang="english">
</head>
<body>
<div>
Enter the original string
<input id="original" value="" type="text">
<br>Enter the replacing string
<input id="replacing" value="" type="text">
<br>Enter the location to be replaced
<input id="tobereplaced" value="" type="text">
<br>
</div>
<br>
<button type="submit" onclick="replace()">Submit</button>
<br>Here you go the replaced string is:
<h1 id="replaced"></h1>
</body>
</html>
Is there an easy way to convert HTML code, that is structured in a certain way, to a single string (that can then be used in a Javascript variable). The new lines and tabs in the html code need to be converted to \n and \t so that the formatting can stay in tact.
example HTML:
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h1>Title</h1>
<h2>Subtitle</h2>
<p>Some text goes here</p>
</body>
</html>
I've converted this manually to this:
<html>\n\n\t<head>\n\t\t <title>Hello World</title>\n \t</head>\n\n \t<body>\n \t\t<h1>Title</h1>\n \t\t\t<h2>Subtitle</h2>\n \t\t\t\t<p>Some text goes here</p>\n \t</body>\n\n </html>\n
Is there an easy way to do this automatically? Because I need to convert larger chunks of HTML to this format. Thanks.
function format(data) {
var returnStr = "";
var lines = data.split("\n");
var block = [];
for (var i = 0; i < lines.length; i++) {
block = lines[i].split('\t');
for (var j = 0; j < block.length; j++) {
returnStr += block[j];
if (block.length>1) {
returnStr += "\\t";
}
};
returnStr += "\\n";
};
return returnStr;
}
If you are doing this to show new line and return carriage in html, then you don't need to do it explicitly. You can do it in css by setting the white-space attribute pre-line value.
<span style="white-space: pre-line">CommentText</span>
I'm really newbie at Web Development and I'm trying to change the text of some inputs, with Javascript. Here is a example of what my code have to do
<!DOCTYPE html>
<html>
<body>
<p>Click the button to replace "R$" with "" in the field below:</p>
<input id="demo" value="R$ 1223,43"></input>
<input id="demo1" value="R$ 134523,67"></input>
<input id="demo2" value="R$ 12453,41"></input>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var x=document.getElementByTagName("input")
for(var i = 0; i < x.length; i++) {
var str=x[i].innerHTML;
var n=str.replace(",",".");
var n1 = n.replace("R$ ","");
document.getElementById("demo").innerHTML=n1;
}
}
</script>
</body>
</html>
So, I want to withdraw the "R$" and replace "," to "." for some math operations. And I have to do this with all inputs in my code.
You were nearly there, replacing a few things to make it look similar to this:
function myFunction() {
var x = document.getElementsByTagName("input"); // ; was missing and you used getElementByTagName instead of getElementsByTagName
for (var i = 0; i < x.length; i++) {
var str = x[i].value; // use .value
var n = str.replace(",", ".");
var n1 = n.replace("R$ ", "");
//document.getElementById("demo").innerHTML=n1; // use x[i] again instead
x[i].value = n1; // and again use .value
}
}
DEMO - Running updated code
These are the needed steps - at least step 1 through 3
moved the script to the head where it belongs
changed getElementByTagName to getElementsByTagName, plural
get and change x[i].value
chained the replace
DEMO
<!DOCTYPE html>
<html>
<head>
<title>Replace example</title>
<script>
function myFunction() {
var x=document.getElementsByTagName("input"); // plural
for(var i = 0; i < x.length; i++) {
var str=x[i].value;
x[i].value=str.replace(",",".").replace("R$ ","");
}
}
</script>
</head>
<body>
<p>Click the button to replace "R$" with "" in the field below:</p>
<input id="demo" value="R$ 1223,43"></input>
<input id="demo1" value="R$ 134523,67"></input>
<input id="demo2" value="R$ 12453,41"></input>
<button onclick="myFunction()">Try it</button>
</body>
</html>
First of all, use .value instead of .innerHTML. .innerHTML referes to text within the opening and closing of the tag.
Secondly, correct the spellings at var x=document.getElementByTagName("input")
it should be getElementsByTagName
this function should do what you want:
function myFunction()
{
var eles=document.getElementsByTagName("input");
for(var i = 0; i < eles.length; i++)
{
if(eles[i].type != 'text') continue; // inputs that aren't of type text dont make sense here
var str = eles[i].value;
str=str.replace(",",".");
str=str.replace("R$ ","");
eles[i].value=str;
}
}
I have an array with 8 elements defined within a script.
I'd like to know how I can pass all the values of this array to a single hidden element.
Pls help.
<script ='text/javascript'>
function abc(){
var arr= new Array(8);
for (var i=0; i<8;i++)
{
arr[i]= ...;
}
</script>
<input type="hidden" id="arrs" name="arrs" value= ? >
you can join them with comma ','
$('#arrs').val(arr.join(','));
From the comments on the question itself
I will have to access this input
hidden element in another js later on
using document.forms.element(''). so
thought it would be easier using a
single element.
It would be easiest to not use any form element at all. Not sure why you want to take such a detour. You have a JavaScript variable, you can use that directly in "another script later on":
<script type="text/javascript" id="firstScript">
function abc(){
var arr = [];
for (var i=0; i<8; i++) {
arr.push(...);
}
return arr;
}
var myArray = abc();
</script>
<!-- time passes, but we're still on the same page... -->
<script type="text/javascript" id="anotherScript">
doSomethingWith(myArray);
</script>
You can try like this:
<script>
function a(){
var arr= new Array(8);
for (var i=0; i<8;i++)
{
arr[i]= i;
}
document.getElementById('d').value = arr;
alert(document.getElementById('d').value);
}
</script>
<input id="d" type="hidden" />
<input type="button" onclick="javascript:a();" value="A" />
Hope this helps.
If the values are only strings or integers, you can try joining them with a seperator not present in your input:
document.getElementById("arrs").value = arr.join("###");
And you can do
myArr = document.getElementById("arrs").value.split("###");
To retreive that array back.