(hopefully this problem hasn't been resolved yet) if so, I am sorry and please link me to the solution. (this is an exercise for the Java course I am attendind nowadays so I am quite novice with Javascript. )
I have a select menu with trip destinations. There are 4-5 destinations (Paris, London, Amsterdam, Berlin, New York..) For each destination there is a short description and a certain price.
So the exercise says: when someone clicks on an option from the select menu , the appropriate description has to appear in the textarea and the appropriate price in the text input. (it's some basic stuff).. I know how some html objects work, I just can't seem to find the best way to do this with select object. I did it with checkboxes via name attribute and a for loop. with radiobuttons as well.. but with select options I am stuck. I don't need the solution for my exercise, I just need a sample code but something I understand.
Ex:
Paris
etc
something like : for selected option [i], textarea.value = the description associated to each trip destination and text input.value = the price of the trip .
I don't want something like : if selectedIndex[0]---textarea.value = X
I need to do something like an Array of destinations.. trips[i] = new Array [] and fill the array of the trip array with the prices and the var's of the description strings.. (I hope I have been clear about everything I need .
Thank you all.
Define an object array where you make a key value mapping of each place and an index.
var array = [{'key': 0, 'value': 'Paris'},{'key': 1, 'value': 'London'},{'key': 2: 'value': 'Amsterdam'}...]
Loop through the array and populate your select options:
<select>
{array.map((each)=>{return (<option value= each.key></option>)})}
</select>
In your event handler, map the key to value in the array to get your text.
selectHandler(val){
let result = array.find((each)=>{return each.key === val});
var textarea = document.getElementById('textArea');
textarea.value = result.value;
}
Related
Hi Helpful Contributors,
I have a gform where user can select more than 1 answer. In response sheet, we will see the multiple answers will be printed in one cell of a column separated by comma. For that matter, I have some calculation to do on each answer. So, I was thinking to declare each input separated by comma as an array value so that I can then refer each value by it's index number in that array. Is this possible?
Below is my code that I tried but when I tried to refer back to that array on index[0], the output is still all the values in that same cell, so I think all are still kept as 1 value of array.
function mytest(){
var sheet=SpreadsheetApp.getActiveSheet();
var input=[];
var extraitem=sheet.getRange(lastorder,77).getValue(); //this cell keeps the multiple answers : "Change of address, Change of mobile no., Change of vehicle type, Change of license type"
input.push(extraitem.split(','));
Logger.log("myinput :"+input[0]); // check the value in position 0 is the first among the multiple answers
}
Please correct my code. Thank you in advance.
The issue with your code is that you push an array extraitem.split(',') into another array input=[]. As a result, input[0] is the full array extraitem.split(',').
To get the first element of the extraitem.split(',') array you can do Logger.log(input[0][0]) or (preferably) simply ignore the push part:
function mytest(){
var sheet=SpreadsheetApp.getActiveSheet();
var extraitem=sheet.getRange(lastorder,77).getValue();
var input= extraitem.split(',');
Logger.log("myinput :"+input[0]);
}
Demonstration:
const extraitem = "Change of address, Change of mobile no., Change of vehicle type, Change of license type";
const input = extraitem.split(',');
console.log("myinput :" + input[0]);
I want to copy another bot's embed and resend while only changing the image to a thumbnail instead. I've been able to replace the image with a thumbnail, get the author name and footer, as well as the description field. But I have no idea how to get the fields and values. There are a lot of fields and values in the message I'm trying to copy. Do I need to find out exactly how many there are? Here is what I have so far:
let url = e.image.url;
let desc = e.description;
let avatar = e.author.name;
//let avaimg = e.icon.url;
let field = e.fields.value;
let field2 = e.fields.name;
let foot = e.footer.text;
then
embed
.setDescription(desc)
.setThumbnail(url)
.setFooter(foot)
.addField(field2, field, true)
.setAuthor(avatar)
return message.channel.send(embed)
and this works, however the fields just say "undefined." So I need a way to get all of the fields and have it repost exactly what it says. Also I'm not sure how to get the author icon.
I hope my question makes sense and I'm sorry if this is a noob question, I am not very experienced with js.
MessageEmbed.fields is an array, so you should loop through each element and add them one by one: you can either to this with a for loop or using the Array.forEach() method.
Here's an example:
// let's say we have a receivedEmbed and yourEmbed
receivedEmbed.fields.forEach(({ name, value, inline }) => {
yourEmbed.addField(name, value, true)
})
What's happening is that you're looping through every field, grabbing the name, value and inline properties (even if you decide not to use the last one, it' since to know that it exists), and adding to your own embed those same fields.
An alternative would be using a for loop:
for (let field of receivedEmbed.fields) {
yourEmbed.addField(field.name, field.value, field.inline)
}
If you're using discord.js#v12, you can also use the addFields method:
yourEmbed.addFields(receivedEmbed.fields)
I have two separate group boxes like so:
<form id = "query" method = "post" action = "search.php">
<input type = "checkbox" name = "col_list[]" value = "cheese">cheese</input>
<input type = "checkbox" name = "col_list[]" value = "tomatoes">tomatoes</input>
<input type = "checkbox" name = "col_order[]" value = "italian">italian</input>
<input type = "checkbox" name = "col_order[]" value = "wheat">wheat</input>
<input id = "submit" name = "submit" type = "submit" value = "submit" display = "inline></input>
</form>
These group boxes will change depending upon a value selected from a drop-down menu above it (done in javascript). For example, if the value of sandwich is selected, then these two group boxes will be displayed, however, if the value of pizza was selected, there would be a group box with various toppings and another with the types of crust. I can post that code if needed
In my PHP code, I have:
$columns = $_POST["col_list"];
$order = $_POST["col_order"];
I attempt to print both of the arrays, yet I am always met with a screen that takes forever to load, followed by my "error" message that found both the arrays to be empty (I simply used the empty(var) method).
If I select any amount of top boxes, but no boxes on the separate group, then my code is fine and I have all of the selected values of the first group. However, if I compound onto that and select any amount from the second group, the problem ensues.
I have no idea as to why they would be empty. Any thoughts?
Naming two checkbox with the same name parameter is a mistake... probably if one col_list array has some elements, the other is empty... so the $_POST will return a empty array.
Try naming your checkboxes with differente names and change your javascript
try this:
if (is_array($_POST['col_list'])) {
foreach($_POST['col_list'] as $result) {
...
}
}
Edit: Duplicate name fields are permissible in PHP. Thanks to Quentin for pointing this out.
The name field of the input tag is used as the key for POST and GET queries. You need to match them exactly, like:
$columns = $_POST["col_list[]"];
$order = $_POST["col_order[]"];
Unless there is some crazy array syntax that nobody told me about...
Also, I would refrain from using the same value for the name field for multiple fields as it has to choose one of them to send and you may not like which field it sends to you. Instead, try disabling/removing the component when your form's submit method is called, or simply assign all your input fields with unique names.
I have a web form with two drop-down boxes, and I'm looking for a way to dynamically update the options of the second box based on selections from the first.
The first box represents a data type, and the second box is a list of databases associated with the selected type.
I have the basic code running smoothly here:
var TypeA_DbSuffixList = ['Test1', 'Test2', 'Test3'];
var TypeB_DbSuffixList = ['TestA', 'TestB', 'TestC'];
function fill_dbSuffixList(){
document.getElementById("dbSuffixList").options.length = 0;
var suffixMenu = document.getElementById("dbSuffixList");
var dataFormat = document.getElementById("dataFormatType");
var suffixList = dataFormat.value + "dbSuffixList";
if (suffixList == 'TypeA_dbSuffixList') {
for(index in TypeA_dbSuffixList) {
suffixMenu.options[suffixMenu.options.length] = new Option(TypeA_dbSuffixList[index], index);
}
}
if (suffixList == 'TypeB_dbSuffixList') {
for(index in TypeB_dbSuffixList) {
suffixMenu.options[suffixMenu.options.length] = new Option(TypeB_dbSuffixList[index], index);
}
}
}
That code (activated whenever a selection is made in the dataType box) clears the existing list of options and repopulates the list based on the selected value of the "dataFormatType" box.
The problem that I face is that the actual lists of database tables are not hard coded and are instead generated with the following calls to the server to avoid repetitive editing of the page every time a new database is added:
var TypeA_dbSuffixList = ${TypeA_dbSuffixList};
var TypeB_dbSuffixList = ${TypeB_dbSuffixList};
These calls return the following code:
var TypeA_dbSuffixList = [Test1, Test2, Test3];
var TypeB_dbSuffixList = [TestA, TestB, TestC];
With the above code, the initial function treats each entry in the type arrays as an undefined variable, and nothing is ever written to the drop-down list.
If I were to add
var Test1 = "Apple";
var Test2 = "Orange";
var Test3 = "Grape";
prior to the "for" loop for TypeA, then selecting TypeA from the dataType drop-down list returns "Apple", "Orange", and "Grape" as the available databases for TypeA.
Visually, I see what needs to be changed. The [Test1, Test2, Test3] returns need to be ['Test1', 'Test2', 'Test3']. I'm just unsure exactly how to go about changing it, and have exhausted every web search I can think of.
Is there a way to either change the format of the returned arrays, or use the existing format and pass variable names as drop-down selections instead of using variable values?
Any help is greatly appreciated. I will continue to search for an answer on my own as well and will post it here should I find one.
I think the cleanest solution would be to change the code on the server-side to generate a proper JavaScript array of Strings, with the values enclosed in single or double quotes.
If that's not possible for some reason, and you want a pure-JavaScript solution, then I suggest you wrap the entire JSP/ASP/PHP variable (not sure what framework you're using) in double quotes, strip the string of brackets and spaces using a regex, and then split it into a string array using the comma as a delimiter.
So in your JavaScript, this:
var TypeA_dbSuffixList = ${TypeA_dbSuffixList};
would become this:
var TypeA_dbSuffixList = "${TypeA_dbSuffixList}".replace(/[\[\]\s]/g,"").split(",");
I think the best way to convert data in a server side language into something to be used in JavaScript is to JSON encode your objects.
I'm not sure what language your using on the server, but in PHP you can do the following
var arr = <?php echo json_encode( array ('abc', 'def', 'ghi') ); ?> ;
And your output will be
var arr = ['abc', 'def', 'ghi'] ;
This will make sure that strings with embedded new lines, tabs, quotes are properly escaped.
JSP
You said you're using JSP but the code you have looks more like velocity or free marker inside JSP. In JSP you could use the following, provided you download Gson
var TypeA_dbSuffixList = <%= new Gson().toJson(TypeA_dbSuffixList) %>;
I have a an associative array in php that i parse to get json from it (json_encode) then i store the result in a javascript var
var myArray = <?php print json_encode($phpArray); ?>;
Now whene the user hit a button i should choose another element from the array dynamically, for example, i chose a random first element :
var an_element = myArray.a2.link;
-'a2' is an array in the main array
-'link' is an element in the a2 array.
So now whene the user hit my button, i want to choose a random other array id (for example a5, a9, etc.)
I tried this :
var randomnumber=Math.floor(Math.random()*101); // choose random number
var newRandomArrayID= "a"+randomnumber;
an_element = myArray.newRandomArrayID.link;
It doesn't works, it says myArray.newRandomArrayID is undefined.
Anyone can help?
Thank you
You need to use [] indexing to find properties by name:
an_element = myArray[newRandomArrayID].link;
Otherwise JS is looking for a property actually called newRandomArrayID on myArray rather than using the value of the variable to lookup the property.