jquery get whole option selected in html - javascript

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>

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');

Change a options value when selected from options

i have a drop-down that has values which are exceeding the current div's width. i want to show only a part of the text when that option is selected. i tried extending the width but the form structure is getting messed up.
<div class="calci-input">
<select id="g-suite-pac-id" name="g-suite-package">
<option value="2.40">$2.40/month</option>
<option value="4.00">$4.00/month</option>
<option value="2.00">$2.00/month(12 months)</option>
<option value="3.33">$3.33/month (12 months)</option>
</select>
</div>
how can i achieve this using jQuery ?
the expected output is that when the option $2.00/month(12 months) is selected it shows as $2.00/month in the drop-down.
The solution comes with the onchange and onmousedown event. Using jQuery's selectors we can get the selected option and change its display HTML.
//you really don't need jQuery, but we can wrap it in there.
//wrap in ready function to make sure page is loaded
$(document).ready(function() {
$("select#g-suite-pac-id").on("change", function() {
var text = $(this).children("option").filter(":selected").text()
var edited = text.match(/^.+?\/month/); //use regex | ^ start, .+? lazy search for everything until /month
//save
$(this).children("option").filter(":selected").data("save", text);
//change
$(this).children("option").filter(":selected").text(edited);
});
$("select#g-suite-pac-id").on("mousedown", function(e) {
//restore a saved value
var selected = $(this).children("option").filter(":selected");
if (selected.length > 0)
{
if (selected.data("save"))
{
selected.text(selected.data("save"));
selected.removeData("save");
}
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="calci-input">
<select id="g-suite-pac-id" name="g-suite-package">
<option value="2.40">$2.40/month</option>
<option value="4.00">$4.00/month</option>
<option value="2.00">$2.00/month(12 months)</option>
<option value="3.33">$3.33/month (12 months)</option>
</select>
</div>
Set width of select component to any fixed width like below:
<div class="calci-input">
<select id="g-suite-pac-id" name="g-suite-package" style="width:96px">
<option value="2.40">$2.40/month</option>
<option value="4.00">$4.00/month</option>
<option value="2.00">$2.00/month(12 months)dffsdfsdfdsfsdfdsfdsfsd</option>
<option value="3.33">$3.33/month (12 months)</option>
</select>
</div>
try above code, it shows text that can fit in 96px width.

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
}

Add/Removing Options with JQuery

I'd like to add and remove options from one drop down menu using JQuery given a selected option in another.
HTML:
<form action='quickLook.py' method = 'post'>
First DropDown Menu
Specify Channel:
<select id='bolometer'>
<option selected id='Dual' value = 'Dual' >Dual
<option id='Top' value = 'Top' >Top
<option id='Bottom' value = 'Bottom' >Bottom
</select>
Second DropDown Menu
<br>Specify Data to Display:
<select id='target'>
<option selected id='Spectrum' value = 'Spectrum'>Spectrum
<option id='Interferogram' value = 'Interferogram'>Interferogram
<option id='SNR' value = 'SNR'>SNR
<option id='Diff_Band' value = 'Diff_Band'> Diff_Band
</select>
<input type='submit' value= 'Query Images'>
</form>
I'd like to do something like this is JQuery:
$("#Dual").click(function() {
$("#target").append("#Diff_Band");
$("#target").remove("#Interferogram");
$("#target").remove("#SNR");
});
$("#Top").click(function() {
$("#target").append("#Interferogram");
$("#target").append("#SNR");
$("#Diff_Band").remove();
});
I want to append or remove the already written html.
What is the best way to do this?
Thank you for your time!
This is a similar problem I've encountered before working with Safari. A solution is to use .detach() instead of remove() as it keeps all jQuery data associated with the removed elements. Check this jsfiddle: http://jsfiddle.net/Ueu62/

How to use document.getElementsByTagName(

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;
}

Categories