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.
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.
DISCLAIMER: i'm legit a newbie
I have a 2nd parameter in the getInput function, I should use it for the 9 zeros that I should input. But I don't know how to loop it to become 9 zeros instead of putting it in a variable.
How do I loop and store 9 zero's into my "digit" parameter without declaring it as var zr = "000000000"
here's my code:
<html>
<head>
<title>Search</title>
<script>
//This method does the processing
function getInput(input, digit){
var str=input.substring(0,input.length);
var padd0=9-str.length;
var zr="000000000";
var zrsub=zr.substring(0,padd0);
var output="A"+zrsub+""+str;
//can also be var output=input[0]+zrsub+""+str;
return output;
}
//Displays output
function showOutput(){
var input=document.getElementById("search-input").value;
var dislay=document.getElementById("search-output");
dislay.value=getInput(input);
}
</script>
</head>
<body>
<div class="wrapper">
<input type="text" id="search-input">
<input type="button" id="btn" value="ENTER" onclick="showOutput()"> <br><br>
<input type="text" id="search-output">
</div>
</body>
</html>
Sorry just a newbie in this whole programming thing. Just a little confused.
with for loop join string
function joinString(input,digit) {
var inputArr = input.split("");
// var n = 9; // the length of the ouput string;
for (var i = 0; i < digit; i++) {
inputArr.unshift(0);
if (inputArr.length === digit) {
return inputArr.join("");
}
}
}
console.log(joinString("123456"));
You can use padStart
function getInput(input, digit){
return 'A'+ input.toString().padStart(digit, '0');
}
document.getElementById('target').innerHTML = getInput(132,9)
<p id="target"></p>
IE may not support it though.
I have an assignment in school but I'm totally stuck.
My assignment:
Make a program that ask for a text and then write out the text several times. First with just one letter, then with two and so on. For example, if the user write "Thomas", your program should write out "T", "Th, "Tho, "Thom", and so on.
My hopeless attempt
I been trying to use "Substring" and a loop to make it work but I'm not sure I'm on the right path or not. Right now my code look like this:
<head>
<meta charset= "UTF-8"/>
<title> assignment14 - Johan </title>
<script type="text/javascript">
var text= test.length;
for (i=0;i< test.length;i++)
function printit()
{
var str = test;
var res = str.substring (i, 2);
document.getElementById("test").innerHTML = res;
}
</script>
</head>
<body>
<h1>Assignment 14</h1>
<form name="f1">
<input type="text" id="test" value="" />
<input type="button" value="Hämta" onclick="printit(document.getElementById('test'))" />
</form>
</body>
Just need some kind of hint If I'm going in the right direction or not, should I use some other functions? Very thankful for help.
You have to rewrite a script.When you want to extract one by one you can use substring(); function.
How to Call : StringObject.substring (StartPoint,endPoint);
Solution:
<script type="text/javascript">
function printit(){
var test=document.getElementById("test").value;
var text= test.length;
for (i=0;i<= text;i++)
{
var res = test.substring (i, 0);
document.write(res);
document.write("<br/>");
}
}
</script>
You are on the right way. substring(start,end) in javascript gives you the consecutive part of the string letters from start index to end. You just use it in a wrong way for your case. You have to call it like this:
substring(0,i)
You need to make few changes to your code:
1) use document.getElementById('test').value in printit function call at onclick as you have to send the value of the textbox instead of innerHTML.
2) Modify the printif function-
function printit(test)
{
document.getElementById('test').value=''; /*remove existing text from textbox*/
for (i=0;i< test.length;i++) {
var res = str.substring (0, i+1);
document.getElementById("test").value += ' '+res;
}
}
In printit function empty the text box and then append each substring to the existing text to get "T Th Tho Thom.." and so on
Hope this helps.
I don't use for-loop for this (whenever possible, I prefer functional style). Instead, I write a function that returns an array of substrings:
const substrings = string =>
Array.from(string).map((_, i) => string.slice(0, i + 1))
And here's a working codepen
Output several time using substring() method can be done as below, create a function which performs this task of extracting the user inputted string on button click using forloop and substring() method.
var intp = document.querySelector("input");
var btn = document.querySelector("button");
var dv = document.querySelector("div");
btn.onclick = function() {
var b = intp.value;
for (var i = 1; i <= b.length; i++) {
var c = b.substring(0, i);
dv.innerHTML += c + "<br/>";
}
}
div{
width:400px;
background:#111;
color:yellow;
}
<input type="text">
<button>Click</button>
<br/><br/>
<div></div>
You have used a correct way for doing this, but as one of user suggest the start and end value of substring() was not correct.
I need some help because my callback function, parseMovie() is only being called once! Despite being in a for loop which iterates it twice. I am using a free Rottentomatoes API
The output only returns one ID, and not two ID's!
And runs parseMovie() only once and returns the movie ID with the last movie.
Does anyone have a fix for this script running problem?
HTML CODE
<!doctype html>
<html class="no-js">
<head>
<title>Movies</title>
<link rel="stylesheet" href="css/main.css">
<script src="js/main.js"></script>
</head>
<body>
<form name="input">
<p> Actor/Actress Name: <input type="text" name="fullName"> </p>
<p> Movie 1 <input type="text" name="movie"> </p>
<p> Movie 2 <input type="text" name="movie"> </p>
<p><input type="button" value="Search movies" onclick="getMovies()"></p>
<p><textarea name="output" readonly> </textarea> </p>
</form>
</body>
</html>
JAVASCRIPT
//api key
var APIKEY = "qf54ubt95fea9n7jytr5xh6h";
var movieID = new Array();
var actor = new Array();
var actorName = "Jennifer Lawrence";
var movieTitle;
var output;
function callScript(call) {
var script = document.createElement('script');
script.setAttribute("src", call);
document.body.appendChild(script);
}
function getMovies() {
for (var x=0; x<2; x++) {
movieTitle = document.getElementsByName('movie')[x].value;
movieTitle= cleanMovieTitle(movieTitle);
var movieURL = "http://api.rottentomatoes.com/api/public/v1.0/movies.json?q=";
callScript(movieURL + movieTitle + "&page_limit=10&page=1&apikey=" + APIKEY + "&callback=parseMovie");
}
}
function cleanMovieTitle(movie) {
movie = movie.trim();
movie = movie.replace(/ /g, "+");
return movie;
}
function parseMovie(data) {
var titleData = data.movies;
for (var t=0; t<titleData.length; t++) {
movieID[movieID.length] = titleData[t].id;
aCast = titleData[t].abridged_cast;
sample = [];
for (var person = 0; person < aCast.length; person++) {
sample[sample.length] = aCast[person].name;
}
actor[actor.length] = sample;
}
for (var arry = 0; arry < actor.length; arry++) {
if (actor[arry].indexOf(actorName) >= 0) {
output = movieID[arry];
break;
} else {
alert("spelling error of some sort! Error 404");
}
}
document.input.output.value = output;
}
Your statement var titleData = data.movies; is wrong, because the data returned by the API contains an array of movies.
You have to iterate through data.movies to get the data for the other movies (and not only the first one).
See the raw JS code and JSON data returned by the API: api.rottentomatoes.com
Three things that strike me as odd that might be causing the problem.
Using for…in for an array is considered bad practice, especially when there's a native forEach method and a polyfill for ie8-
cleanMovieTitle isn't doing anything because it doesn't return a value. If you were passing it an array or object, it would pass by reference and it would be altered, but that is considered bad practice for the exact reason that it's not working. You're passing a value, the function modifies that value within the function's scope, then does nothing with it. You need to return the string and set movieTitle = cleanMovieTitle(movieTitle); So maybe the API isn't returning for one of the titles because it hasn't been cleaned. See Passing by Reference or by Value.
The callback may be is getting called again before it finishes running. Not sure on this one, but you could check by flooding the loop with console.logs and seeing whether it's the case.
Edit
So I just ran your script on this page and I'm getting an error on document.input.output.value = output; As expected, parseMovies runs twice when I remove this line. What's document.input?
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>