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
}
Related
I have dynamically generated the following dropdown list using jquery for the calculator app I am currently making:
<select type="text" id="field__left">
<option label="Please choose an unit!" text="Please choose an unit!"></option>
<option label="inch" text="Inch" value="0.0254"></option>
<option label="foot" text="Foot" value="0.3048"></option>
<option label="yard" text="Yard" value="0.9144"></option>
<option label="rod" text="Rod" value="5.0292"></option>
<option label="chain" text="Chain" value="20.1168"></option>
<option label="furlong" text="Furlong" value="201.168"></option>
<option label="mile" text="Mile" value="1609.344"></option>
<option label="cable" text="Cable" value="185.2"></option>
<option label="nautical mile" text="Nautical mile" value="1852"></option>
<option label="shipday" text="Shipday" value="185200"></option>
</select>
What now I try is to access the value attribute of every option, but I don't get far. The examiner is showing the value attribute in the elements tab, I can also find under the options when I look at the properties in the browser, but I am unable to access them via JavaScript.
I tried:
const leftVal = $('#field__left').children('option').attr('value');
also
const leftVal = $('#field__left').children('option').data('value');
but it returned undefined, while:
const leftVal = document.querySelector('#field__left').getAttribute('value');
gave me null.
Anybody has the ide where my mistake lies?
Thank you in advance.
I try is to access the value attribute of every option
You need a loop...
$("#field__left option").each(function(){
console.log($(this).val())
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select type="text" id="field__left">
<option label="Please choose an unit!" text="Please choose an unit!"></option>
<option label="inch" text="Inch" value="0.0254"></option>
<option label="foot" text="Foot" value="0.3048"></option>
<option label="yard" text="Yard" value="0.9144"></option>
<option label="rod" text="Rod" value="5.0292"></option>
<option label="chain" text="Chain" value="20.1168"></option>
<option label="furlong" text="Furlong" value="201.168"></option>
<option label="mile" text="Mile" value="1609.344"></option>
<option label="cable" text="Cable" value="185.2"></option>
<option label="nautical mile" text="Nautical mile" value="1852"></option>
<option label="shipday" text="Shipday" value="185200"></option>
</select>
$('#field__left').children('option') will return an array of all select option nodes, you have to iterate through it to get values of each option
Here is the simple solution
// get list of an options
var options = $('#field__left option');
// Then, convert that into an array of just the values
var values = $.map(options, e => $(e).val())
console.log(values)
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>
This is my select in html:
<select id="bgPosition">
<option value="left top" selected="selected">Left Top</option>
<option value="center top">Center Top</option>
..
</select>
On page load I need to update the selected value with another one, so I tried with .each .prop and this:
function setActiveOption(el,val){
$(el).find('option:selected').removeAttr('selected');
$(el).find('option[value="'+val+'"]').attr('selected','selected');
console.log('selected: '+$('#bgPosition').val())
}
All ok for other select boxes, but not for #bgPosition I think because values contains spaces.
selected attribute is in right place, but is displaying first option as selected
Any idea how can this be fixed?
I also tried with different jQuery libraries
UPDATE: This is my fiddle and how I am running functions.
Given your example fiddle, the only select element that doesn't respect the value you set is the middle one, #bgRepeat, and that's because by default you've got two option set with the selected attribute.
To fix the problem, only provide one option with the selected attribute.
That being said, a better solution would be to just use .val() as a setter on the select itself, which is a one-liner and therefore renders the setActiveOption() function redundant. Try this:
var template = [{
"mainBgImgPosition": "right bottom",
"mainBgImgRepeat": "no-repeat",
"mainBgImgSize": "cover"
}]
jQuery(function($) {
var Builder = {
initialized: false,
initialize: function() {
if (this.initialized)
return;
this.initialized = true;
$('#bgPosition').val(template[0].mainBgImgPosition);
$('#bgRepeat').val(template[0].mainBgImgRepeat);
$('#bgSize').val(template[0].mainBgImgSize);
}
}
Builder.initialize();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="bgPosition" id="bgPosition">
<option value="left top" selected="selected">Left Top</option>
<option value="left center">Left Center</option>
<option value="left bottom">Left Bottom</option>
<option value="center top">Center Top</option>
<option value="center center">Center Center</option>
<option value="center bottom">Center Bottom</option>
<option value="right top">Right Top</option>
<option value="right center">Right Center</option>
<option value="right bottom">Right Bottom</option>
</select>
<select name="bgRepeat" id="bgRepeat">
<option value="repeat" selected="selected">Repeat All</option>
<option value="repeat-x">Repeat X</option>
<option value="repeat-y">Repeat Y</option>
<option value="no-repeat">No Repeat</option>
</select>
<select name="bgSize" id="bgSize">
<option value="auto" selected="selected">Auto</option>
<option value="cover">Cover</option>
</select>
i tried your code in a fiddle and it worked for me.
https://jsfiddle.net/b8t1yavu/
What are you passing into the function setActiveOption for el. It might now be working because of that. You could call the function in two ways.
setActiveOption('#bgPosition','center top')
OR
setActiveOption(bgPosition,'center top')
If you want it call it with the second method, you have to modify your code a bit. here is a fiddle for that https://jsfiddle.net/b8t1yavu/1/
I don't know how you call your function but it seemed to work fine when I run it in JSFiddle. You need to call your function with the id of the element as the first parameter and the FULL value of the option as the second parameter as HTML does not concider words as seperate values.
setActiveOption('#bgPosition', 'center'); // Does not work
setActiveOption('#bgPosition', 'center top'); // Works fine
https://jsfiddle.net/Youmy001/uyun2soo
I am a beginner in java-script , what I am doing right here is trying to make my combo-box named "dale" to enable and disable when i select "Reasons Specific Categorized" from my combo-box named "repSelect" but i keep getting an error on my java-script.
function makeEnable(value){
if(value=="rep4"){
var x=document.getElementById("dale")
x.disabled=false
}else{
var x=document.getElementById("dale")
x.disabled=true
}
}
</script>
</script>
<select onChange="makeEnable(value)" name="repSelect">
<option value="rep1">Employee</option>
<option value="rep2">Category Reasons Overall </option>
<option value="rep3">Department Overall </option>
<option value="rep4">Reasons Specific Categorized </option>
</select>
<select name="dale">
<option value="rep1">dale</option>
</select>
<input class="button" type="submit" value="Generar Reporte" >
</form>
My modification But dosent work
function makeEnable(){
var e = document.getElementById("repSelect");
var strUser = e.options[e.selectedIndex].value;
if(strUser=="rep4"){
document.getElementById("dale").disabled=false;
}else{
document.getElementById("dale").disabled=true;
}
}
You are using the .getElementById() method, but your element doesn't have an id defined. Add an id in the html:
<select id="dale" name="dale">
You may also need to modify the call to your function in the first select's onchange handler, to pass this.value instead of just value:
<select onChange="makeEnable(this.value)" name="repSelect">
You can also substantially simplify your function as follows:
function makeEnable(value){
document.getElementById("dale").disabled = value!="rep4";
}
Demo: http://jsfiddle.net/3t16p5p9/
EDIT: I just noticed that you had the jquery tag on your question. To use jQuery, remove the inline onChange= attribute and then add this to your script:
$(document).ready(function() {
$("select[name=repSelect]").change(function() {
$("#dale").prop("disabled", this.value!="rep4");
}).change();
});
This binds a change handler to the first select, and then calls it immediately so that the second one will be appropriately enabled or disabled when the page loads (as requested in a comment).
Demo: http://jsfiddle.net/3t16p5p9/2/
Actually you are using document.getElementById but your combobox doesn't have an Id.
Thats the reason its not working.
Instead of adding onchange in the html, use as below:
<select id='repselect' onchange=makeEnable() name="repSelect">
<option value="rep1">Employee</option>
<option value="rep2">Category Reasons Overall </option>
<option value="rep3">Department Overall </option>
<option value="rep4">Reasons Specific Categorized </option>
</select>
<select id="seldale" name="dale">
<option value="rep1">dale</option>
</select>
<input class="button" type="submit" value="Generar Reporte"/>
$('#repselect').change(function(){
if(this.value=="rep4"){
var x= document.getElementById("seldale")
x.disabled=false
}else{
var x =document.getElementById("seldale")
x.disabled=true
}
});
I want to use this function to work on all my drop down lists. Problem: the first drop down works okay, but hen I try select any option in the 2nd drop down selections. It places the value from the first group in the span of the second group. I want the span to have the value from its own group. I would like to use this on multiple groups.
The code below does not work properly. the phone number display okay but when i try to select the parts, the value of the phone number is displayed, no matter what the selection is.
I want the phone number when i select phones, and parts when i select parts.
Thank you
<script>function displayResult(xspan,xselect)
{
var x=document.getElementById(xselect).selectedIndex;
alert(x);
var newTxt = document.getElementsByTagName("option")[x].value;
document.getElementById(xspan).innerHTML = newTxt;
//alert(document.getElementsByTagName("option").length);
}
</script>
<select id="myPhones" onchange="displayResult('ShowPhone','myPhones')">
<option value="">Phone Numbers</option>
<optgroup label="Shipping">
<option value=" - 800-463-3339">FedEx</option>
<option value=""></option>
</optgroup>
</select>
<span id="ShowPhone"></span>
<select id="myParts" onchange="displayResult('ShowParts','myParts')">
<option value="">Qik Parts list</option>
<optgroup label="BATT">
<option value="1">1</option>
<option value="2">1</option>
<option value="2">1</option>
<option value="2"><1/option>
</optgroup>
</select>
<span id="ShowParts"></span>
Mostly comments:
When you do:
var newTxt = document.getElementsByTagName("option")[x].value;
then document.getElementsByTagName("option") returns all the options in the document, you probably only want the ones for the select in question. But the options for a select are available as a collection, so you can do:
selectElement.options[x].value;
But that is unnecessary unless you are dealing with very old browsers or IE where there are no value attributes. Just use selectElement.value.
Where you have:
<select id="myPhones" onchange="displayResult('ShowPhone','myPhones')">
you can instead do:
<select id="myPhones" onchange="displayResult('ShowPhone', this.value)">
so that you pass the current value of the select directly to the function. Then the function can be:
function displayResult(id, value) {
document.getElementById(id).innerHTML = value;
}
This should work, though I haven't tested it.
function displayResult(spanId, selectId) {
document.getElementById(spanId).innerHTML = document.getElementById(selectId).value;
}