Getting an option text/value with JavaScript - javascript

I am trying to build a form that fills in a person's order.
<form name="food_select">
<select name="maincourse" onchange="firstStep(this)">
<option>- select -</option>
<option text="breakfast">breakfast</option>
<option text="lunch">lunch</option>
<option text="dinner">dinner</option>
</select>
</form>
What I'm trying to do is send in the select object, pull the name and the text/value from the option menu AND the data in the option tag.
function firstStep(element) {
//Grab information from input element object
/and place them in local variables
var select_name = element.name;
var option_value = element.value;
}
I can get the name and the option value, but I can't seem to get the text="" or the value="" from the select object. I only need the text/value from the option menu the user selected. I know I can place them in an array, but that doesn't help
var option_user_selection = element.options[ whatever they select ].text
I also need to use the passed in select reference as that is how it's set up in the rest of my code.
Later on, that text/value is going to be used to pull the XML document that will populate the next select form dynamically.

You can use:
var option_user_selection = element.options[ element.selectedIndex ].text

In jquery you could try this $("#select_id>option:selected").text()

var option_user_selection = document.getElementById("maincourse").options[document.getElementById("maincourse").selectedIndex ].text

form.MySelect.options[form.MySelect.selectedIndex].value

Related

Hide text before dollar sign character in options without removing completely

I am trying to find a way to select part of the string before the dollar sign in the select menu. Right now I am just trying to hide it so it does not appear in the dropdown, but it will be used later so I do not want to simply strip it out because I will need to be able to use it in a variable when the option is selected.
var seminiars;
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<select>
<option>1$5,000</option>
<option>2$10,000</option>
<option>5$100,000</option>
<option>10$500,000</option>
</select>
So far I have only been able to remove it completely, but then I was unable to store it and use it when someone selects on of the option.
Side note: I am unable to edit the html directly, the code is automatically generated.
okay... I just noticed the side note.
I am unable to edit the html directly, the code is automatically generated.
The trick here, will be to set a data value for each option.
// Run that loop to set the data values for each option
$("select option").each(function() {
let optionText = $(this).text();
let textSplit = optionText.split("$")
$(this).data("before_dolard_sign", textSplit[0])
$(this).text(textSplit[1])
})
$("select").on("change", function() {
// So on change, you have access to it
console.log($(this).find("option:selected").data("before_dolard_sign"))
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<select>
<option>1$5,000</option>
<option>2$10,000</option>
<option>5$100,000</option>
<option>10$500,000</option>
</select>
You can use the value attribute to store more information not in the text visible to the user. I've added some code below to show how you can get the text or value selected by the user.
If that isn't suitable I've also created a test input and button which helps demonstrate how you can split a string in the way you need to.
The code is fully commented.
Let me know if you were hoping for something else.
// Detect when user changes select option
$("#selectTest").change(function() {
// Get the text selected by the user
console.log($("#selectTest option:selected").text());
// Get the value selected by the user
console.log($(this).val());
});
// Add click event
$("#splitButton").click(function() {
// Get input value
var test = $("#splitTest").val();
// Split around dollar sign
var els = test.split("$");
// Print values to show we did it correctly
console.log(els[0]);
console.log("$" + els[1]);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<select id="selectTest">
<option value="1$5,000">$5,000</option>
<option value="1$5,000">$10,000</option>
<option value="5$100,000">$100,000</option>
<option value="10$500,000">$500,000</option>
</select>
<input id="splitTest" value="10$500,000">
<button id="splitButton">Show Split</button>
why not place this data onto a data-meta attribute?
instead of
<option>1$5,000</option>
<option>2$10,000</option>
<option>5$100,000</option>
<option>10$500,000</option>
perhaps
<option data-meta="1">$5,000</option>
<option data-meta="2">$10,000</option>
<option data-meta="5">$100,000</option>
<option data-meta="10">$500,000</option>
then you can find the selected option and use element.getAttribute("data-meta") to retrieve the data when you need it
edit: i now see your side-note that you can't edit the html. well, replace it. loop over the html, and use .split on the textContent, and move that meta data into an attribute
Use the data attribute to store the info and then run an event listener to retrieve the dataset when selected on change?
const select = document.querySelectorAll('#money');
select.forEach((val) => {
if (val.value != 'undefined') {
val.addEventListener('change', () => {
let data = val.options[val.selectedIndex].dataset['num'];
console.log(data)
})
}
});
<select id="money">
<option style="display: none;">-->Select an option below<--</option>
<option data-num='1' class='opt' value='5000'>$5,000</option>
<option data-num='2' class='opt' value='10000'>$10,000</option>
<option data-num='5' class='opt' value='100000'>$100,000</option>
<option data-num='10' class='opt' value='500000'>$500,000</option>
</select>

pass current selected option to javascript function

I have a multiple select list. on select for an option from the list,I am calling a javascript function. I want to pass the current selected option object to this javascript function.
How can I do this? I tried following but its not working.
<select onClick="callJavascriptFun(this.option);" >
</select>
for getting the selected option, try the following code:
<select onchange="callJavascriptFun(this.options[this.selectedIndex]);" >
</select>
inside the callJavascriptFun function you will get of course the selected option.
Make it easier with event handler:
html part
<select class="list">
</select>
js part:
$('select.list').change(function(){
var selectedOption = $('option:selected', $(this)); // your selected option object(element)
var current = $(this).val(); // your selected option value
....
});

selecting proper value from attribute

I have a select Box for selecting country code :-
<div class="selectWrap">
<select name="countryCode" id="countryCode"></select>
</div>
It gets populated using javascript and gets options like follows :-
<option data-phone-code="+91">91&nbsp(India)</option>
Now I want to select the value only +91.
I was trying this
var country = document.getElementById("countryCode");
var prefix = country.options[country.selectedIndex].value;
But this returns the Full value with Country.
How can I achieve this ?
Use getAttribute, for example:
country.options[country.selectedIndex].getAttribute('data-phone-code');

Combining javascript and jquery to fill multiple hidden fields - bad idea?

I'm trying to find the best way to make my teachers' lives a little easier.
I've got a select field and list of options generated by a tlist sql query. The select field itself already has a javascript attached to it, which fleshes out other field values (credit values and credit types) elsewhere based on the id of the select option chosen. This is the javascript that works for that purpose:
<script type="text/javascript">
function changeValue(){
var option=document.getElementById('courseno').value;
if(option=="E100"){
document.getElementById('credval').value="10";
document.getElementById('credtype').value="EngFresh";
}
else if(option=="E200"){
document.getElementById('credval').value="10";
document.getElementById('credtype').value="EngSoph";
}
}
</script>
I also need to populate a hidden field that is (and must remain) outside the tlist sql tag that generates the select list.
Here is my sql code:
<select id="courseno" name="course_number" onchange="changeValue();">
<option value="">Select a Course</option>
~[tlist_sql;
SELECT cc.course_number, cc.section_number, c.COURSE_NAME
FROM cc cc
RIGHT JOIN COURSES c ON c.COURSE_NUMBER = cc.course_number
RIGHT JOIN STUDENTS s ON cc.studentid = s.id
WHERE cc.studentid = ~(curstudid)
AND TERMID = ~(curtermid)
AND c.CreditType LIKE 'English%'
AND NOT EXISTS (
SELECT * FROM storedgrades sg
WHERE sg.studentid = ~(curstudid)
AND sg.course_number = c.course_number
)
ORDER BY c.course_name;]
<option name="~(course_no)" value="~(course_no)" id="~(secno)">~(course_no).~(secno) (~(cname))</option>
[/tlist_sql]
</select></td>
</tr>
And just below that is the hidden field I would like to populate:
<td width="25%" class="bold"> </td>
<td><input type="text" id="secnum" name="section_number" value=""> </td>
I gave each of the options the section number as its ID, thinking I could use the ID element of each of those options and some clever jquery to populate the hidden field, but I'm having no luck. I just read on another question that was ably answered by the community that you shouldn't use an option ID tag that begins with a number... so now what can I do?
Could somebody please help me?
Thanks forever,
Schelly
I don't think your problem comes from the ID being a number. We haven't seen what jQuery you've tried, but you most likely don't need jQuery at all. Assuming what you have is working correctly, and the PowerSchool code is putting out elements the way you expect them to be (View Source in your browser to be sure, if this doesn't work), you should be able to grab the ID from the selected option inside your changeValue function, store it in a variable, and push that value into the "secnum" field as follows:
function changeValue(){
var courseDropdown = document.getElementById('courseno');
var selectedElement=courseDropdown.options[courseDropdown.selectedIndex];
var option=selectedElement.value;
var courseNo = selectedElement.getAttribute("id");
if(option=="E100"){
document.getElementById('credval').value="10";
document.getElementById('credtype').value="EngFresh";
}
else if(option=="E200"){
document.getElementById('credval').value="10";
document.getElementById('credtype').value="EngSoph";
}
document.getElementById('secnum').value=courseNo;
}
I changed the way that your "option" variable is being set, but it will work the same way. You might end up wanting to move the last line, where the "secnum" field is being set, or wrap it in an "if", etc.; I don't know your full requirements.
All that said, there would be nothing wrong with using jQuery in this situation, but it's not necessary in this case unless you need extreme backwards-browser compatibility.
Working Example Here
You can use multiple on change events to do whatever you want. On change add a new event and populate the hidden input. You can define custom attributes to any html element with any data that is required to populate the hidden input
<select id="myselect">
<option>Select</option>
<option data-number="1">One</option>
<option data-number="2">Two</option>
<option data-number="3">Three</option>
<option data-number="4">Four</option>
<option data-number="5">Five</option>
</select>
<input type="hidden" id="hiddenInput"/>
$(document).ready(function(){
$('#myselect').on('change', mySelectChange);
function mySelectChange(){
console.log('your standard change value here');
}
$('#myselect').on('change', mySelectChange2);
function mySelectChange2(){
var option = $("#myselect option:selected");
console.log(option.text());
console.log(option.attr('data-number'));
}});

Get each selected value using chosen jquery plugin

I'm using Chosen Multiple Select
What I want to do is that if user selects any option I want that value and then I will do some functionality depending on that value.
In chosen without multiple select i can get selected value by using foll. code
$(".selectId").chosen().change(function(){
selectedValue = $(this).find("option:selected").val();
});
But in multiple select I get the first selected value again n again
can anybody help me by finding the current selected value in multiple select element??
The Chosen documentation mentions parameters for getting the most recently changed variables.
Chosen triggers the standard DOM event whenever a selection is made
(it also sends a selected or deselected parameter that tells you
which option was changed).
So, if you just want the most recent option selected or deselected:
$(".selectId").chosen().change(function(e, params){
// params.selected and params.deselected will now contain the values of the
// or deselected elements.
});
Otherwise if you want the whole array to work with you can use:
$(".selectId").chosen().change(function(e, params){
values = $(".selectId").chosen().val();
//values is an array containing all the results.
});
Short answer:
You just do this: var myValues = $('#my-select').chosen().val();
Full example:
If you have a select-multiple like this:
<select id="my-select" class="chzn-select" multiple data-placeholder="Choose one or more values...">
<option value="value1">option1</option>
<option value="value2">option2</option>
<option value="value3">option3</option>
</select>
You can get the selected values in an array to doing the following:
// first initialize the Chosen select
$('#my-select').chosen();
// then, declare how you handle the change event
$('#my-select').chosen().change(function(){
var myValues = $('#my-select').chosen().val();
// then do stuff with the array
...
});
your code is gettin the correct selected value.. but since its multiple you need to use loop..or use map to get the selected value and push it into array..
try this
$(".selectId").chosen().change(function(){
var selectedValue = $.map( $(this).find("option:selected").val(), function(n){
return this.value;
});
console.log(selectedValue ); //this will print array in console.
alert(seletedValue.join(',')); //this will alert all values ,comma seperated
});
updated
if you are getting commaseperated values then use split()
var values= $(".selectId").val();
$.each(values.split(',').function(i,v){
alert(v); //will alert each value
//do your stuff
}
try this
$('.selectId:selected').each(function(i, selected) {
var value = $(selected).val();
var text = $(selected).text();
});
The Chosen documentation mentions parameters for getting the most recently changed variables.
$(".CSS Selector").chosen().change(function(e, parameters) {
// params.selected and params.deselected will now contain the values of the
// or deselected elements.
});
This is how I've got it to work. In my html, I've this
<select data-placeholder="Choose a Country..." class="form-control chosen-select" multiple tabindex="4">
<option value="USA">USA</option>
<option value="UK">UK</option>
<option value="CHINA">CHINA</option>
</select>
Then javascript
// apply chosen-js to the DOM, and store it in a variable.
var chosen = $(".chosen-select").chosen({
no_results_text: "Oops, nothing found!"
});
// inside the change event, we get the value by calling chosen.val()
chosen.change(function() {
console.log('selected tags are', chosen.val());
});

Categories