javascript change div based on dropdown - javascript

I have a dropdown list with 2 options:
<select name="list" size="1">
<option value=1>Option 1</option>
<option value=2>Option 2</option>
</select>
And i want to set <span id=tag></span> to display different text depending on which option is highlighted in the dropdown. How can I do this?

Well, the question is pretty vague but in general you would do something like this:
Html:
<select id="mySelect" name="list" size="1">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
<span id="tag"></span>
Javascript:
//cache the select and span elements
var mySelect = document.getElementById("mySelect"),
tag = document.getElementById("tag");
//when it changes
mySelect.onchange = function() {
//change the tag innerHTML checking the selected value of the select
tag.innerHTML = mySelect.value === "1" ? "some text" : "some other text";
}
You could change the ternary operator (? :) for a few if statements, if you need more conditions.
Notice that I've added an Id to the <select>. You can avoid the caching part if you want to get the span each time the select changes for some reason

You can do it with an onchange event handler on your <select>:
<select name="list" id="list">
<option value="1">Option 1</option>
<option value="1">Option 1</option>
</select>
<span id="tag"></span>
<script>
// Get references to the objects you need (<select> and <span>)
var list = document.getElementById('list');
var tag = document.getElementById('tag');
// When the list value changes, set the innerHTML of the <span>
list.onchange = function() {
tag.innerHTML = this.value;
};
</script>
Notice in the above that I've added id attributes to both your select and span elements. This allows me to easily get a reference to them in Javascript.
It's also important for my example that the script is executed after the elements are rendered, otherwise the document.getElementById call won't return a reference to them. You could get around this limitation by moving the script into a window.onload handler.
Here's a simple example of it working.

Related

How to Hide the Certain Text Value of Selected Option using jQuery

I have a select box that contains certain elements (see below):
<select id="test" name="test">
<option value="12345">12345 - Test</option>
<option value="67890">67890 - Test 2</option>
<option value="53453">53453 - Test 3</option>
</select>
Here is what I'm trying to accomplish When the user selects a certain element, I want certain elements of the text to hide. For example, if I select 12345, I want the - Test to hide.
How can I do it in jQuery?
Thank you,
Kevin
A brute force-y way to do it would be to keep track of the internal text and values of the currently-selected option, then replace the text with the desired text when the option changes. This part's easy in your case, since the desired output text is the same as the option's value.
I opted to add a blank option at the beginning, since by default the text will not have changed, but you can get around this by adding a trigger to go off when the page is finished loading.
var selectedTextOrig = "";
var selectedValue = 0;
$("#test").change(function() {
// Reset the inner html text for the previously-selected option
$("#test option").each(function() {
if ($(this).val() == selectedValue) {
$(this).text(selectedTextOrig);
return false; // break out of $.each()
}
});
// Store the viewable text and value of the currently selected
selectedValue = $("#test option:selected").val();
selectedTextOrig = $("#test option:selected").text();
// Replace the current inner html
$("#test option:selected").text(selectedValue);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="test" name="test">
<option disabled="disabled" selected></option>
<option value="12345">12345 - Test</option>
<option value="67890">67890 - Test 2</option>
<option value="53453">53453 - Test 3</option>
</select>
I have found a solution:
Here is how I achieved it:
$('select[name="test"]').find('option').remove().end();
$('select[name="test"]').append(new Option(selectId, selectId));
$('select[name="test"]').trigger('change');

jquery get whole option selected in html

Is there possibility to get all html option from selected dropdown.
While i have
<select class="myselect">
<option data-one="11" data-two="11" data-three="111" value="1">Some text here</option>
<option data-one="22" data-two="22" data-three="222" value="2">Some text here2</option>
</select>
I would like to get whole option which is:
<option data-one="22" data-two="22" data-three="222" value="2">Some text here2</option>
As far i as tried i can get all options in html by:
$('.myselect').html()
Or just one data by :
$('.myselect').find(':selected').data('one')
Or just one value
$('.myselect').find(':selected').val()
So is there simple way to get selected whole html option from < option >... to < /option>
Like this - it is not clear if you want the tag or the data attributes so here are either
$(".myselect").on("change",function() {
console.log(this.options[this.selectedIndex]); // complete tag
console.log(this.options[this.selectedIndex].dataset); // array of data attribute values
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="myselect">
<option value="">Please select</option>
<option data-one="11" data-two="11" data-three="111" value="1">Some text here</option>
<option data-one="22" data-two="22" data-three="222" value="2">Some text here2</option>
</select>
I wasn't quite clear precisely what result you wanted, so here are a couple of ideas to get things you may be interested in:
1) To get the names and values of all the data-attributes you can just call .data() without any arguments and it will return all the data-attributes and their values in an object. There's also an example in the documentation.
2) To get the whole HTML of the selected item you can use outerHTML on the DOM element found by jQuery.
Demo of each below:
//to get the data-attributes
var selectedData = $('.myselect').find(':selected').data();
console.log(selectedData);
//to get the HTML of the selected item:
var selected = $('.myselect').find(':selected')[0].outerHTML;
console.log(selected);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="myselect">
<option data-one="11" data-two="11" data-three="111" value="1">Some text here</option>
<option data-one="22" data-two="22" data-three="222" value="2">Some text here2</option>
</select>

select onchange get option name attribute value

I have a html page:
function getName(val)
{
alert(val.value);
alert(val.getAttribute('name'));
}
<select onchange="getName(this)">
<option name="1" value="data1">Data 1</option>
<option name="2" value="data2">Data 2</option>
<option name="3" value="data3">Data 3</option>
</select>
I want that option name and value data. It returns value data as expected ,but it return name data as null.
What should I do?
Any help is appreciated. Thank You
Here in the function getName the argument select refers to the select element, but not the selected option. Use selectedIndex to get the selected option then use getAttribute
function getName(select) {
// You can get the value like you did
var value = select.value;
console.log(value);
// And here we get the name
var selectedOption = select.options[select.selectedIndex];
var name = selectedOption.getAttribute('name');
console.log(name);
}
<select onchange="getName(this)">
<option name="1" value="data1">Data 1</option>
<option name="2" value="data2">Data 2</option>
<option name="3" value="data3">Data 3</option>
</select>
You could also do the following (which is more clear)
function getName(select) {
var selectedOption = select.options[select.selectedIndex];
var value = selectedOption.getAttribute('value');
var name = selectedOption.getAttribute('name');
console.log(value, name);
}
function getName()
{
alert(event.target.value);
alert(event.target.selectedOptions[0].getAttribute('name'));
}
<select onchange="getName()">
<option name="1" value="data1">Data 1</option>
<option name="2" value="data2">Data 2</option>
<option name="3" value="data3">Data 3</option>
</select>
I would also like to suggest a different answer that, I think, highlights better web programming practices.
In my opinion, you shouldn't use something like onchange="getName(**this**)" in your HTML. You should attach the function to the select element via Javascript.
For demonstration purpose, we will add an id to our select element so we can find it in the DOM quickly.
<select id="mySelect">
<option name="1" value="data1">Data 1</option>
<option name="2" value="data2">Data 2</option>
<option name="3" value="data3">Data 3</option>
</select>
Next we write our Javascript
// When the page is loaded...
document.addEventListener("DOMContentLoaded", function(event) {
// Find your select...
var mySelect = document.getElementById("mySelect");
// Attach the function to the "onChange" event.
mySelect.addEventListener("change", function(event) {
// Retrieve the select element from the event.
var select = event.target;
var selectedOption = select.options[select.selectedIndex];
var value = selectedOption.getAttribute('value');
var name = selectedOption.getAttribute('name');
console.log(value, name);
});
});
It is a more structured and clean way of solving the problem.
Hope you learned something new!

Select option from selectbox

How can I select an option with javascript (/console in google chrome)?
This is a part of the html code:
<nobr>
Element<br>
<span class="absatz">
<br>
</span>
<select name="element" class="selectbox" style="width:114" size="12" onchange="doDisplayTimetable(NavBar, topDir);">
<option value="0">- All -</option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">X</option>
<option value="4">C</option>
<option value="5">D</option>
<option value="6">E</option>
<option value="7">F</option>
<option value="8">G</option>
<option value="9">H</option>
<option value="10">I</option>
<option value="11">J</option>
<option value="12">K</option>
<option value="13">L</option>
<option value="14">M</option>
<option value="15">N</option>
<option value="16">O</option>
<option value="17">P</option>
<option value="18">Q</option>
<option value="19">R</option>
</select>
</nobr>
Or http://pastebin.com/JSaKg4HB
I already tried this:
document.getElementsByName("element")[0].value = 1;
But it gives me this error:
Uncaught TypeError: Cannot set property 'value' of undefined
at :2:48
at Object.InjectedScript._evaluateOn (:875:140)
at Object.InjectedScript._evaluateAndWrap (:808:34)
at Object.InjectedScript.evaluate (:664:21)
EDIT:
I I tried it but it don't works on for the full website. Maybe because there is another html tag inside the first html tag(if I download the website, there is another html file called welcome.html where the selectbox is.) I thinks it's in an iFrame, because chrome gives me the Option "show Frame".
EDIT 2:
I can access the frame where the selectbox is but I still won't find the selectbox. Here is the code of the frame(not the full code): pastebin.com/iVUeDbYV
Try this:
document.querySelectorAll('[name="element"]')[0].value;
Although it is very weird that getElementsByName is not working for you. Are you sure the element is in the same document, and not in an iFrame?
The simple answer:
document.getElementById("select_element").selectedIndex = "option index";
Where option index is the index of the option in the dropdown that you'd like to activate.
You can get the index of an option by using this:
var selected = document.querySelector( '#'+div+' > option[value="'+val+'"]' );
Where div is the ID of the <select> tag.
how this helps!
This will do what you want.
document.querySelector('[name="element"]').value = 4 // The value you want to select
and this will retrieve the value
var value = document.querySelector('[name="element"]').value; // 4
this explains what's going on
var option = document.querySelector('[name="element"]');//option element
option.value; // 4
option.selectedIndex; // 4
option.selectedOptions; // [<option value="4">C</option>]
option.selectedOptions[0].innerText; // C
option.selectedOptions[0].value; // 4
Remember that selectedOptions is an array because more than one option may be selected, in those cases, you will have to loop through the array to get each value. As per Hanlet Escaño's comment, make sure your code is set to execute after the DOM has loaded.
window.onload = function() {
document.querySelector('[name="element"]').value = 0; // sets a default value
}

jQuery: Get value from multiple fields and show in text field

I have 6 different select boxes and a text field which I need to fetch the value from and combine in to one text field using jQuery.
I understand essentially I will build the value for the targetTextField with a string like this: $('#targetTextField').val(opt1+opt2+opt3+opt4+opt5+opt6+textField);
What do I use to fetch the value of select#options1 and transform that in to opt1?
Would it be along the lines of opt1 = $('select#options1').val(); or am I heading in completely the wrong direction?
I've created a basic jsfiddle with just two options at:
http://jsfiddle.net/e2ScF/2/
jQuery
$(function() {
$("#options").change(function(){
var opt1 = $('select#options').val()
}$('#targetTextField').val(opt1+opt2);
});
$("#options2").change(function(){
var opt2 = $('select#options2').val()
}$('#targetTextField').val(opt1+opt2);
});
});​
HTML
<select id="options">
<option value="" selected>Choose...</option>
<option value="opt1Value1" >Option 1</option>
<option value="opt1Value2" >Option 2</option>
</select>
<select id="options2">
<option value="" selected>Choose...</option>
<option value="opt2Value1" >Option 1</option>
<option value="opt2Value2" >Option 2</option>
</select>
<input type="text" id="targetTextField" name="targetTextField" size="31" tabindex="0" maxlength="99">​
...but it doesn't appear to be working, so I've obviously misunderstood or missed something.
I made this demo for you, hope it helps
http://jsfiddle.net/e2ScF/5/
$(function() {
$("#options").change(function(){
setTarget() ; // Something has changed so lets rebuild the target
});
$("#options2").change(function(){
setTarget();// Something has changed so lets rebuild the target
});
});
// Just get the values you want and update the target
function setTarget(){
var tmp = $("#options").val();
tmp += $("#options2").val();
$('#targetTextField').val(tmp);
}
​
for dropdown try following
$('select option:selected').text()
have a look at this it should hopefully give you a pointer in what you need to do.
you can change the name to be a class and then just provide your format you want to display in the input. but from your question in presume it should be about that.
If you have different id for select box
var toalopt=$('select option1:selected').text();
toalopt+=$('select option2:selected').text();
toalopt+=$('select option3:selected').text();
toalopt+=$('select option4:selected').text();
toalopt+=$('select option5:selected').text();
toalopt+=$('select option6:selected').text();
document.getElementById('id where you want to club data').innerHTML=toalopt;
If you have same id
$(document).ready(function(){
$('#optionvalue).click(function(){
var values ='';
$('select[name="sameid"]').each(function(index,item){
values +=$(item).val() +' ';
});
$('id where you want to club data').val(values);
});
});
HTml will be normal select tag with id.
First of all, add a class to each of your select elements to better identify them as a group:
<select id="options" class="auto-updater">
<option value="" selected>Choose...</option>
<option value="opt1Value1" >Option 1</option>
<option value="opt1Value2" >Option 2</option>
</select>
<select id="options2" class="auto-updater">
<option value="" selected>Choose...</option>
<option value="opt2Value1" >Option 1</option>
<option value="opt2Value2" >Option 2</option>
</select>
<input type="text" id="targetTextField" name="targetTextField" size="31" tabindex="0" maxlength="99">
Then in jQuery, you can use map() to create an array of the values and display them:
$(".auto-updater").change(function() {
var values = $(".auto-updater").map(function() {
return ($(this).val() == "") ? null : $(this).val(); // ignore default option select
// return $(this).val(); // include all values
}).get();
$("#targetTextField").val(values.join(','));
});
Example fiddle
You can see that I've set this up to ignore select elements which are left on their default value. If you uncomment the line beneath it will include all selects, regardless of value chosen.
Minimal code required for you as below:
$(function() {
$("select").change(function(){
var opts=$('option:selected').val();
var oldVal=$('#targetTextField').val();
$('#targetTextField').val(oldVal+opts);
});
});​
Find the jsfiddle demo here.

Categories