Reply output to an input - javascript

I'm new to Javascript, but I understand this is possible in Python as well (which I know a little of)
Say someone inputs ‘Hi’
How do you output a ‘reply’ back.
But a different reply if something different is entered i.e.
If Hi is inputted 'Hello there' is outputted
If How are you is inputted 'fine thanks' is outputted
etc.
I'd also like for those (Hi, how are you, what are you doing) to be selected from a dropdown menu (this will be on an HTML page)
Thank you very much!!

Well, you would have a select menu (obviously):
<select id="greeting">
<option value="0">Select a greeting</option>
<option value="1">Hi</option>
<option value="2">Hello there</option>
<option value="3">How are you</option>
</select>
Then you'd attach an event listener to do something when the value of the select menu changes:
var sel = document.getElementById("greeting");
sel.onchange = function(){
...
}
Within the event handler you can then use the value of the selected option element to look up which greeting was entered and alert an appropriate response.
var greetings = {
"1": "How are you?",
"2": "Hello back!",
"3": "Not bad"
},
sel = document.getElementById("greeting");
sel.onchange = function(){
if(this.value !== "0"){
alert(greetings[this.value]);
}
}
fiddle

Related

JaveScript Select the dropdown list by the text of options

Is it possible to select the dropdown list by using the display-text of the options in the console(JavaScript)?
In my workplace, I need to fill a web form every day. But the options are too much to load, so I hope to use the Chrome console to select the option instead of using the mouse to click.
For now, I can use Value to select the option, but when I try to use the text, it fails.
The HTML sample and the JavaScript I used are as below. Could someone help?
Success - document.querySelector("#sel").value = 123
Fails - document.querySelector("#sel").text = "Product A"
<select>
<option value="123"> Product A </option>
<option value="243"> Product B </option>
<option value="212"> Product C </option>
<option value="466"> Product D </option>
</select>
Array.from(document.querySelectorAll('option')).find(el => el.textContent === 'Product A');
Truly sorry for the confusing example.
After trying lots of solutions, the final coding as below:
var txt = prompt();
for (i = 0; i < document.querySelector("#sel").options.length; i++) {
if(document.querySelector("#sel").options[i].text == txt){
document.querySelector("#sel").options[i].selected = true;
break;
}
}
With these codes, the User can select the specific options by entering the name of the product instead of clicking the dropdown list with the mouse and crash the browser.

Redirect to a different page depending on the multiple options selected

I'm hoping someone can help me. I'm creating a form with two questions. Question 1 is where are you located with three different options (New York, California, Maryland) then a second question "What are you eating tonight" with four different options (Lobster, Steak, Crab, Salmon). Based on what the users respond to, they get sent to a unique landing page (each URL will be different). I was able to find this code, but it only works for one dropdown question, whereas I need code that would be good for a unique combination of both dropdowns. I couldn't find this answer anywhere, and I was hoping someone could give me some insight.
<!-- Insert in Settings->Javascript->Header -->
<!-- CS:20200120-11-1 -->
<script>
document.addEventListener("DOMContentLoaded", function() {
function pageGenerator(fieldName) {
return window.__page_generator ? fieldName : base64_encode(fieldName);
}
var dropdownName = "My Dropdown"; // Field name
var options = {
"Option 1": "https://instapage.com", // Each option on a new line
"Option 2": "https://help.instapage.com/hc",
"Option 3": "https://help.instapage.com/hc/en-us/articles/214133067"
// "Option Name" : "Redirect URL if this option is chosen"
}
var selectInput = document.querySelectorAll('form select[name="' + pageGenerator(dropdownName) + '"]');
window.instapageFormSubmitSuccess = function() {
for (var i = 0; i < selectInput.length; i++) {
var selectedOption = selectInput[i].value;
document.querySelectorAll('input[name="redirect"]')[i].value = options[selectedOption];
}
}
});
</script>
<!-- End "Redirect depending on dropdown" || Help center -->```
From what I understood, THIS is a solution that came up with.
CODEPEN link (so that you can execute.)
index.html:
<select id="State">
<option disabled selected> default</option>
<option> NY</option>
<option> CA</option>
<option> MD</option>
</select>
<br><br>
<select id="food" hidden>
<option disabled selected> default</option>
<option> Lobster</option>
<option> Steak</option>
<option> Crab</option>
<option> Salmon</option>
</select>
<script>
let string = ["", ""];
document.getElementById("food").addEventListener("change", event => {
console.log(event);
string[1] = event.target.value;
// document.body.innerText += event.target.value;
window.location.href += "/" + string.join("-");
});
document.getElementById("State").addEventListener("change", event => {
// document.body.innerText += event.target.value;
console.log(event);
string[0] = event.target.value;
document.getElementById("food").hidden = false;
});
Note:
1. You can manipulate the location anyhow you wish by using "window.location.href" I
have used here to continue on the same path.
2. I have kept constant format, that is first the state then " - " and finally food. You can change it to your preference (such as "/state/food" or "/food/state, etc)
3 If you use the codepen then it will redirect to give you an 404 error

How do I get the value of a selected option an use it on an "if"?

I have this HTML:
<select id="categories">
<option value="category1">Category 1</option>
<option value="category2">Category 2</option>
</select>
<input type="search" id="search" placeholder="Search here" autofocus>
And this jquery:
var categories = $("#categories option:selected").val();
var search = $("#search");
if (categories = "category2") {
search.attr("placeholder", "Search for category 2");
} else {
search.attr("placeholder", "Search for category 1");
}
I'm trying to put a different placeholder according to the selected value, but no matter what is selected, it always show the first placeholder. This might seem silly, but further I want to be able to pick the value of the selected option to make the search in that specific category, kinda like the Amazon website.
I have used == to compare, but nothing happens, the placeholder stays with "Search here".
PS: With this code running, using the console on Chrome, if I type and execute categories it will always show in the console category2, no matter which one is selected, but if I type and execute $("#categories option:selected").val();, then it will show the selected value. I tried to put this directly inside the if in the code, but returned the same problem. I also tried to replace the else for if (categories = "category1"), but then it was the same problem, but this time the placeholder showed was always the second one.
//you should add an onChange event,like this:
$("#categories").change(function(e){
var categories = e.target.value;
if (categories == "category2") {
...
} else {
...
}
})

JS: Change select option value on being selected with prompt?

I've looked around and I don't see this being asked before.
I have a select box, like so:
<select onchange="change()">
<option value="" selected>Option 1</option>
<option value="30">Option 2</option>
<option value="90">Option 3</option>
</select>
I want to add another option...
<option value="custom">Option 4</option>
...that when chosen (clicked) an alert box will popup asking the user to type in a number (in the case 30 or 90 weren't viable options, as in the values of the option's) to replace the value of the option.
<script>
function change() {
if(value == "custom") {
value = prompt("Please enter a new number:", "60");
}
}
</script>
I wanted to know what the best way to do this is with plain old javascript - I'll use jQuery if I have to.
Any ideas? An example would be great as well.
Take a look at this code. I think this is what you're trying to do:
HTML
<select id="optionvals" onclick="change()">
<option value="" selected>Option 1</option>
<option value="30">Option 2</option>
<option value="90">Option 3</option>
<option value="custom">Option 4</option>
</select>
JS
function change() {
var oItem = document.getElementById('optionvals');
var value = oItem.options[oItem.selectedIndex].value;
if(value == "custom") {
alert("you've clicked b");
value = prompt("Please enter a new number:", "60");
oItem.options[oItem.selectedIndex].value = value;
console.log(oItem.options[oItem.selectedIndex].value)
}
}
What this does is prompt you on the change only if the selected value in the options is custom. Then after you choose a custom value, it will rewrite the value of that the custom option element to the value you just entered in the prompt. I logged the new value after assigning it to show you that it is working.
Here is a fiddle: https://jsfiddle.net/ng7xvy05/
Your onchange event is the appropriate way to handle this. This is mostly a matter of user interface (UX) design though. To do this in the prompt fashion you ought to use parseFloat:
change() {
var value = prompt('You\'ve chosen Other. Please enter a value', '60');
if(value) {
value = parseFloat(value);
// apply it to your model
} else {
// apply NULL to your model
}
}
From a UXD point of view I would use a typeahead input. It would autosearch known answers but also allow the user to input their own. This is not standard html so you would need to write this yourself or use jquery. But from a user interface design point of view, prompts suck.

Javascript multiple select boxes

I tried searching for an answer to this for a while, but to no avail.
I'm trying to do a simple online calculator (that calculates some photovoltaic panels energy), but I'm stuck in something simple (I'm new to Javascript although I worked with Flash's ActionScript 3.0 for a while).
What I need done is a html select that defines which other select group appears in the page. Something like this (obviously this doesn't work, just setting an example):
HTML
<html>
<body>
<select id="test1" onclick="checkField()">
<option>Selected A Group</option>
<option>Selected B Group</option>
</select>
<script>//insert second group here</script>
</body>
</html>
Javascript
function checkField(){
var temp = document.getElementById('test1').value;
if(temp === "Selected A Group"){
//insert code to "echo" the first optional select group
} else {
//insert code to "echo" the second optional select group
}
}
Sorry if its a bit confusing, but I cant really explain all that well.
Here is an example of what I would want, where selecting a option makes the other fields change accordingly: http://www.toshiba.eu/innovation/download_drivers_bios.jsp
you are almost there, actually javascript doesn't "echo" values directly, it does log values using console.log(your value); to a debug console, similar to AS2 trace() if my memory isn't failing.
To "output" information to the document you should have a look into document.write
When you use document.write it will directly write to the documents end.
The "correct" way would be to create a DOM element, with the elements you want inside it, and then append it to the desired element. Have a look at the comments
<!-- Be Aware to use the onchange trigger on select boxes, if you use onclick the function will run, even
if you didn't really chose any option -->
<select id="test1" onchange="checkField()">
<!-- Is good to have a first non-value option, better to trigger the onchange event, if you have
Select A Group as first option and you click on it, it didn't really "Change", you would have to
pick B Group and then A Group again to trigger the onchange event correctly. -->
<option value="">-- select an option --</option>
<!-- You can have a value attribute on the options, so it's easy to process when programming
while displaying a more detailed description to the users -->
<option value="A">Selected A Group</option>
<option value="B">Selected B Group</option>
</select>
<!-- We create an empty element where we are gonna place the new Select -->
<div id="newSelect"></div>
<!-- By Placing the Javascript on the end of <body>, we ensure that all the DOM elements loaded before running the script -->
<script>
function checkField(){
var newSelect = document.getElementById('newSelect'); //targeting container;
var temp = document.getElementById('test1').value;
//Some tasks we do always the option chose is not the first custom one, so we don't have to repeat it
//on the two If's below
if(temp !== ""){
// We remove the select if we placed one already before, so we can add the new one,
// For example if we chose B Group but changed our mind and Chose A Group later.
if(oldChild = newSelect.getElementsByTagName('select')[0]){
oldChild.remove();
}
var select = document.createElement("select");
select.setAttribute('id', 'newSelect');
}
if(temp === "A"){
//you could do JUST:
//body.innerHTML = "all the html you want in here" instead of all the code following;
//but all those code is supposed to be the "correct way" of adding elements to the HTML,
//Google a bit about that for detailed explanations
var option1 = document.createElement("option");
option1.value = 1;
option1.text = "Option 1";
var option2 = document.createElement("option");
option1.value = 2;
option2.text = "Option 2";
select.appendChild(option1);
select.appendChild(option2);
newSelect.appendChild(select);
} else {
var option1 = document.createElement("option");
option1.value = 3;
option1.text = "Option 3";
var option2 = document.createElement("option");
option1.value = 4;
option2.text = "Option 4";
select.appendChild(option1);
select.appendChild(option2);
newSelect.appendChild(select);
}
}
</script>
Of course there are ways to make this slightly shorter, using loops if your data to ouput has a pattern, but lets do it the "simple" way so you get a grasp of Javascript.
Hope all this helped you!!
Demo here:
http://jsfiddle.net/3GkrX/
Just about the same as Mevins.... changed to switch/case though
html:
<select id="test1" id="name" onchange="checkField()">
<option>----</option>
<option>Selected A Group</option>
<option>Selected B Group</option>
</select>
<div id="optional">Please select!</div>
JS:
function checkField(){
var temp = document.getElementById('test1').value;
switch(temp){
case "Selected A Group":
document.getElementById("optional").innerHTML="<select name='optionalA'><option>1</option><option>2</option></select>";
break;
case "Selected B Group":
document.getElementById("optional").innerHTML="<select name='optionalB'><option>3</option><option>4</option></select>";
break
default:
document.getElementById("optional").innerHTML="Please select!";
break;
}
}
Also added the second group as a real option, and a default as "please select". may or may not be necessary in your case
Here is the demo http://codepen.io/anon/pen/izAHo
your doing it almost right.
You should put the onclick event on the option tag to trigger changes based on the option selected.
HTML
<html>
<body>
<select id="test1">
<option onclick="checkField()">Selected A Group</option>
<option>Selected B Group</option>
</select>
<select id="test2">
<option onclick="check2Field()">Selected C Group</option>
<option>Selected D Group</option>
</select>
<script>//insert second group here</script>
</body>
</html>
JS
function checkField(){
var temp = document.getElementById('test1').value;
if(temp === "Selected A Group"){
document.getElementById('test2').innerHTML="<option>Selected halloooo Group</option>";
} else {
//insert code to "echo" the second optional select group
}
}
Check out my demo for more clarity.

Categories

Resources