JS function with two arguments, referencing different objects - javascript

I'm pretty much brand new to JS, and working on a small web page to teach myself a little bit. I feel like this would have been answered before, but I don't know how to word it better to find it.. sorry!
basically, I have two templates set up in HTML, for two select boxes, which will be re-used quite a few times across the form. then I have a function that is called Onchange for select 1, and will change what is visible in select 2, I managed to reference select 1 with (this), but I'm completely at a loss as to how to reference the second one.
function myFunction(selectObject)
{
if (selectObject.value == 'option1')
{
//code to reference Select2 here
option3.disabled = true;
option3.style.display = "none";
}
}
<template id="Select1">
<select name="Select1" onchange="myFunction(this)">
<option value="option">option</option>
<option value="option1">option1</option>
<option value="option2">option2</option>
</select>
</template>
<template id="Select2">
<select name="Select2" >
<option value="option3">option</option>
<option value="option4">option1</option>
<option value="option5">option2</option>
</select>
</template>
thanks for any help!

Something like this? I am not sure why are you using template tags.
function myFunction()
{
var select1 = document.querySelector("#Select1>select");
var select2 = document.querySelector("#Select2>select");
var option3Visible = select1.value != 'option1';
var option3 = select2.querySelector("option[value='option3']");
option3.disabled = !option3Visible;
option3.style.display = option3Visible ? "inline" : "none";
}
<div id="Select1">
<select name="Select1" onchange="myFunction()">
<option value="option0">option0</option>
<option value="option1">option1</option>
<option value="option2">option2</option>
</select>
</div>
<div id="Select2">
<select name="Select2" >
<option value="option3">option3</option>
<option value="option4">option4</option>
<option value="option5">option5</option>
</select>
</div>

Basically you need to get familiar with events, dom query API and possibly CSS selectors.
If you're using templates, you need to search inside content property of the corresponding template:
let t1 = document.querySelector('#Select1');
let t2 = document.querySelector('#Select2');
// there are many ways how to select an element, here simple element selector is used
let select1 = t1.content.querySelector('select');
let select2 = t2.content.querySelector('select');
let option3 = t1.content.querySelector('[value=option3]');
// add event listener is preferred to your `onchange` attribute binding
select1.addEventListener('change', function() {
// modify select2 here
option3.disabled = true;
option3.style.display = "none";
});

Related

How to use getElementByID in JavaScript to connect to my HTML drop down box?

I have a drop-down box in HTML showing three options. I am also using javaScript and want to use the getElementById tool to connect the two. However, I only have one ID for the drop-down box. How does javascript recognize that I have three different options?
There's actually a demo on w3schools.com showing exactly what you're asking. To get the number of options, you could do something like
document.getElementById("mySelect").options.length
Here is an example of how to retrieve the value of a dropdown: https://jsfiddle.net/ykcwgnm8/
You use getElementBy* functions to get the element, however value attribute denotes which item is currently selected.
HTML:
<select id="dropdown">
<option value="1">First option</option>
<option value="2">Second option</option>
<option value="3">Third option</option>
</select>
JS:
function onChangeHandler(e)
{
alert("you have selected item with value "+this.value);
}
document.getElementById("dropdown").addEventListener("change", onChangeHandler);
You can listen for change like this
var list = document.getElementById("mySelect")
list.addEventListener('change', function(e){
console.log(e.target.selectedIndex)
console.log(e.target.options[e.target.selectedIndex].text)
})
<select id="mySelect">
<option>Apple</option>
<option>Orange</option>
<option>Pineapple</option>
<option>Banana</option>
</select>
You can do something like this, here is an example:-
html
<select id="selectBox">
<option value="1">option 1</option>
<option value="2" selected="selected">option 2</option>
<option value="3">option 3</option>
</select>
js
var e = document.getElementById("selectBox");
var selectedValue = e.options[e.selectedIndex].value;
// this will give selectedValue as 2
Hope you find this useful!!

How to send a value from a select to an input text in html using javascript?

I am trying to send a value to an based on a selection from a dropdown list such as . I want to fetch the value of possiblePhone.id and send it to .
<script>
function copyTextValue() {
var text1 = document.getElementById("source").value;
document.getElementById("destination").value = text1;
}
</script>
<div>
<select th:field="${possiblePhones}">
<option value="0">select phone</option>
<option id="source" onselect="copyTextValue()"
th:each="possiblePhone : ${possiblePhones}"
th:value="${possiblePhone.id}"
th:text="${possiblePhone.model}"></option>
</select>
</div>
<td><input type="text" id="destination"> </td>
For example, if "Samsung" is selected then "1" should be send to the input field and so on. Actually, i do not get any output.
<select id="source" onchange="copyTextValue()">
<option value="0">select phone</option>
<option value="1">samsung</option>
<option value="2">something</option>
</select>
The id="source" attribute should be in <select> element, also change onselect to onchange and move it to <select> element too.
Codepen: https://codepen.io/anon/pen/WVxLpz
You can achieve this by setting the listener to the select element and then query the selected option value.
I made a minimal example with two brands:
<script>
function copyTextValue() {
var e = document.getElementById("select");
var val = e.options[e.selectedIndex].value;
document.getElementById("destination").value = val;
}
</script>
<div>
<select onchange="copyTextValue()" id="select">
<option value="0">select phone</option>
<option value="1">Brand 1</option>
<option value="2">Brand 2</option>
</select>
</div>
<td><input type="text" id="destination"> </td>
one of the simple thing you have to observe here is that you have to capture the event when the dropdown is selected, and pass the current dropdown reference to your method.
<script>
function copyTextValue(selectedOption) {
if(selectedOption.selectedIndex <= 0){
document.getElementById("destination").value = '';
return;
}
var selectedOptionValue = selectedOption.value;
document.getElementById("destination").value = selectedOptionValue;
}
</script>
<div>
<select onChange="copyTextValue(this);">
<option value="0">select phone</option>
<option value="1">select first phone</option>
<option value="2">select second phone</option>
<option value="3">select third phone</option>
<option value="4">select fourth phone</option>
</select>
</div>
<td><input type="text" id="destination"> </td>
here you are also trying to avoid to pass any value to the textbox when the first element is selected. #kryptur's answer is also correct, but this is simpler.
You're using Thymeleaf. For these you to create a form to send you data to the server.
Follow this link for documentation for your exact problems.
https://www.thymeleaf.org/doc/tutorials/2.1/thymeleafspring.html#creating-a-form
As Frameworks like Thymeleaf usually store state on the server which means you update server first - and then your UI gets updated.
what value return is the value of the select field what you need to do is get the text of selected option i.e
function copyTextValue() {
var selectNode = document.getElementById("source");
enter code here
document.getElementById("destination").value =
selectNode .options[selectNode .selectedIndex].textContent;
}

Get a select box by name and set another select box by same name?

I am building a fairly complex form-- I need to copy some data between one and another and I am using jQuery to do this. The only road block I am running into is setting the state.
I have two drop downs, one us using the full state name as the value and the other is using the state abbreviation as the value. The names are the same-
so on form 1 it looks like
<option value="Illinois">Illinois</option>
and form 2 it looks like
<option value="IL">Illinois</option>
Each form has its own unique css selector. How can I set the selected value of form 2 to match what is in form 1 using jQuery?
I do not have any control over the forms, just need to manipulate the input. Have tried using a name selector in jQuery, but I'm not having any luck.
Thank you.
You can do something like this
<select id="fullName">
<option value="Maryland" data-abbr="MD">Maryland</option>
<option value="Illinois" data-abbr="IL">Illinois</option>
<option value="Delaware" data-abbr="DE">Delaware</option>
</select>
<select id="abbr">
<option value="MD">Maryland</option>
<option value="IL">Illinois</option>
<option value="DE">Delaware</option>
</select>
And your jQuery
$('body').on('change', '#fullName', function(){
var abbr = $(this).find('option:selected').data('abbr');
$('#abbr').val(abbr);
});
Try this
<form id="form1" name="form1">
<select name="states" onchange="changeselect(this)">
<option value="option1">option1</option>
<option value="option2">option2</option>
<option value="option3">option3</option>
<option value="option4">option4</option>
<option value="option5">option5</option>
</select>
</form>
<form id="form2" name="form2">
<select name="states">
<option value="opt1">option1</option>
<option value="opt2">option2</option>
<option value="opt3">option3</option>
<option value="opt4">option4</option>
<option value="opt5">option5</option>
</select>
</form>
function changeselect(elem)
{
var value1 = $(elem).val();
$('#form2 select option').removeAttr('selected');
$('#form2').find('select option').each(function(){
var value2 = $(this).html();
if(value1 == value2)
{
var selected = $(this).attr('value');
$('#form2 select').val(selected);
}
});
}
If you create 2 arrays which exactly correspond with one another:
var StateNames = ['Alabama','Alaska','Arizona','Arkansas','California','Colorado','Connecticut','Delaware','Florida','Georgia','Hawaii','Idaho','Illinois','Indiana','Iowa','Kansas','Kentucky','Louisiana','Maine','Maryland','Massachusetts','Michigan','Minnesota','Mississippi','Missouri','Montana','Nebraska','Nevada','New Hampshire','New Jersey','New Mexico','New York','North Carolina','North Dakota','Ohio','Oklahoma','Oregon','Pennsylvania','Rhode Island','South Carolina','South Dakota','Tennessee','Texas','Utah','Vermont','Virginia','Washington','West Virginia','Wisconsin','Wyoming'];
var StateAbbreviations = ['AL','AK','AZ','AR','CA','CO','CT','DE','FL','GA','HI','ID','IL','IN','IA','KS','KY','LA','ME','MD','MA','MI','MN','MS','MO','MT','NE','NV','NH','NJ','NM','NY','NC','ND','OH','OK','OR','PA','RI','SC','SD','TN','TX','UT','VT','VA','WA','WV','WI','WY'];
You can:
get the value from the first option list;
find that value's index in the first array; (hint: use indexOf)
use the same index to find out what the corresponding abbreviation is in the second array;
use the returned abbreviation to locate the correct option in the second option list

Hide and display HTML elements based on what was chosen in a dropdown

My website is created in ASP classic - VBScript (not my choice and is a language I've not had experience with before this). I'm trying to create a webpage where in it: A dropdown menu reveals an additional dropdown based on what was selected in the first one. I'm trying to use a javascript function to achieve this.
Example:
In the first dropdown the user chooses ice cream or crisps.
Based on what the user selects another dropdown gives the choice of flavour.
Ice cream: vanilla, chocolate, mint.
Crisps: ready salted, cheese & onion, salt & vinegar.
This is what my code currently looks like:
HTML
<select id="food" onchange="fctCheck(this.value)">
<option value="">Choose an item</option>
<option value="icecream">Ice cream</option>
<option value="crisps">Crisps</option>
</select>
<select id="icecream" style="display:none">
<option value="vanilla">Vanilla</option>
<option value="chocolate">Chocolate</option>
<option value="mint">Mint</option>
</select>
<select id="crisps" style="display:none">
<option value="readysalted">Ready Salted</option>
<option value="cheeseandonion">Cheese and Onion</option>
<option value="saltandvinegar">Salt and Vinegar</option>
</select>
.
javascript
function fctCheck(food)
{
if (food == "")
{document.getElementById(food).style.display = "none";}
else
{document.getElementById(food).style.display = "block";}
}
as mentioned by st3inn this.value is absolutely fine - there is just the typo by document.getElement==>B<==yId.
But your code has the disadvantage, that a user could select both options and so both sub-selections would be visible.
You could avoid this by first hiding all sub-selections before showing the one for the selected item. This could be done that way (via the addiotional name-attribute, or, if you choose to work with jQuery you could do something more sophisticated instead):
Example (with comments) on JSFiddle
Javascript:
function fctCheck(food) {
var elems = document.getElementsByName("subselector");
for (var i = 0; i < elems.length; i++) {
elems.item(i).style.display = "none";
}
document.getElementById(food).style.display = "block";
}
HTML:
<select id="food"onchange="fctCheck(this.value);">
<option value="">Choose an item</option>
<option value="icecream">Ice cream</option>
<option value="crisps">Crisps</option>
</select>
<select id="icecream" name="subselector" style="display:none">
<option value="vanilla">Vanilla</option>
<option value="chocolate">Chocolate</option>
<option value="mint">Mint</option>
</select>
<select id="crisps" name="subselector" style="display:none">
<option value="readysalted">Ready Salted</option>
<option value="cheeseandonion">Cheese and Onion</option>
<option value="saltandvinegar">Salt and Vinegar</option>
</select>
Cheers,
Florian
You need to check for option value instead:
fctCheck(this.options[ this.options.selectedIndex ].value)
this.options is collection of <option> elements inside your current <select>, and this.options.selectedIndex is integer value that show what option currently selected.
BTW you have an typo in your code:
document.getElementbyId
should be
document.getElementById
See jsFiddle demo
You just have a typo.
function fctCheck(food)
{
if (food == "") {
document.getElementById(food).style.display = "none";}
} else {
document.getElementById(food).style.display = "block";
}
}
should work.
this.value
is equivalent to
this.options[this.options.selectedIndex].value

How to get selected value from select tag using javascript and go to another page using that value

I have a select tag where it contains some values, as shown below:
<select id="menu" SIZE=6 onChange="go()">
<option value="">Select city</option>
<option value="delhi" >delhi</option>
<option value="kolkata" >kolkata</option>
<option value="mumbai" >mumbai</option>
</select>
Now i am using below script for this, where it get the selected value from the drop down,
<script>
function go(){
var sel = document.getElementById('menu');
var sv = sel.options[sel.selectedIndex].value;
// here i need to make a specific link using this selected drop down value
}
</script>
I just need to know how can i make use of this selected value and go to specific link like
window.location.href='getCityDetails.jsp?c=sv'; // this is not working properly
Can anyone suggest me best solution for this.
<script>
function go(){
var sel = document.getElementById('menu');
var sv = sel.options[sel.selectedIndex].value;
window.location.href='getCityDetails.jsp?c=' + sv;
}
</script>
Hope it helps you
HTML :
<select id="menu" SIZE=6 onChange="go(this.value)">
<option value="">Select city</option>
<option value="delhi" >delhi</option>
<option value="kolkata" >kolkata</option>
<option value="mumbai" >mumbai</option>
</select>
Javascript :
function go(desination){
if (destination != ''){
window.location.href='getCityDetails.jsp?c=' + desination;
}
}
you need to concatenate the string properly. try this:
window.location.href='getCityDetails.jsp?c=' + sv;
-- You can use--
var TaskType = document.form1.SelTaskType.value;
-- TaskType will display selected option from below
<select id="SelTaskType" name="SelTaskType" >
<option selected>-- select --</option>
<option>B</option>
<option>C</option>
<option>D</option>
</select>

Categories

Resources