How can I get the text within the selected dropdown menu option using jQuery?
I have tried:
var title = $("#selectattribute option:selected").text();
But I don;t think it works..
What you did should work:
$("select option:selected").text()
Working example
Since it's not working for you, the error must lie somewhere else. Maybe #selectattribute is incorrect.
To clarify some of the other answers, the value of an option is different from the text inside it.
For example:
<select>
<option value="red" selected="selected">Ferrari</option>
</select>
// For the above HTML
$("select option:selected").text() === 'Ferrari'
$("select option:selected").val() === 'red'
Also, if no selected attribute is set in the HTML, the first option will be selected:
<select>
<option value="black">Porsche</option>
<option value="red" >Ferrari</option>
</select>
// For the above HTML
$("select option:selected").text() === 'Porsche'
You can get the value of the select box by simply using:
var title = $("#selectattribute").val();
To get the text of the option, instead of the value attribute:
var title = $("#selectattribute :selected").text();
Related
I have the next selectbox in HTML:
<select id="listbox-taskStatus" class="selectpicker">
<option status="0">In progress</option>
<option status="1">Not started</option>
<option status="2">Done</option>
<option status="3">Failed</option>
</select>
I want to read the attribute value from selected option.
If just to take the value, it's simple:
var value = $('#listbox-taskStatus').val();
But what should I do, if I want to get the attribute value from selected option?
I know, that .attr() must help, but when I tried to use it I've got the incorrect result.
I've tried the next:
var status = $('#listbox-taskStatus option').attr('status');
But the returned value is always 0 despite on fact I was selecting different option.
What's wrong, how to solve my problem?
Use :selected Selector
var status = $('#listbox-taskStatus option:selected').attr('status');
However, I would recommend you to use data- prefixed attribute. Then you can use .data()
var status = $('#listbox-taskStatus option:selected').data('status');
DEMO
var optionAttr1 = $('#listbox-taskStatus').find('option:selected').attr("status");
var optionAttr = $('#listbox-taskStatus option:selected').attr("status");
I have a form which sends information with post method to another page. In the form I have a select box with three options, for example:
<select name="slctstate" id="slctstate">
<option value="0">aaaaa</option>
<option value="1">bbbbb</option>
<option value="2">ccccc</option>
</select>
In another page, I read the selected item with $_POST['slctstate'], but I want to read all options (key & value) in the select tag.
Can I do this?
First use a jquery function which stores all the options in a string
$(document).ready(function()
{
var myoption = '';
$('#drop_down option').each(function()
{
myoption = myoption + ',' + ($(this).val());
});
$('#hidden_text').val(myoption);
}
);
in the html use a hidden field
<input type="hidden" id="hidden_text" name="hidden_text"/>
WHen you will submit the form, catch this value with a list of options separated by (,);
On the action page, you can split the value using php explode() function
Check the fiddle
http://jsfiddle.net/1u9x5nbq/3/
No you can't without a work-around. The only value gets passed is the selected value. If you want to know all values you can use a work-around in javascript e.g.:
<select name="slctstate" id="slctstate">
<option value="0">aaaaa</option>
<option value="1">bbbbb</option>
<option value="2">ccccc</option>
</select>
//Include JQuery
<script>
$(function()
{
$('#slctstate option').each(function()
{
$('#slctstate').after('<input type="text" value="'+$(this).text()+'" name="slctstateOptions['+$(this).val()+']" style="display:none;" />');
//Where val() is the key and text() is the value.
});
});
</script>
Then you can access the values by using $_POST['slctstateOptions'].
No, you can't do that from the form. When you do submit, you send only selected value(s).
No,
The only value that is "selected" will be POSTed on Submit.
I'm using Select2 3.4.5 for create select boxes,
I use this code for creatre a Multi-Value Select Boxe and everything is fine.
<select id="e1" name="mydata" multiple>
<option value="D1">Data1</option>
<option value="D2">Data2</option>
<option value="D3">Data3</option>
</select>
...
<script>
$("#e1").select2();
</script>
For get multiple selected values of select box in php I have to modify name="mydata" by name="mydata[]", and in PHP I get values by this code:
<?php
foreach ($_POST['mydata'] as $names) {
print "You are selected $names<br/>";
}
?>
But my question: How can I send selected values of select box to PHP as string to recover in php like this : 'D1,D2,D3' , and thanks.
Edit:
I want to send the data as string, not receive it as an array then
change it as string
Server-side with PHP
Ideally you would do this with PHP once the value is sent. To convert the selected items just want to implode the array
$names=implode(',', $_POST['mydata']);
Where $_POST['mydata'] is an array
[0]=>'D1',
[1]=>'D2',
[2]=>'D3'
implode(',', $_POST['mydata']) would be 'D1,D2,D3'
Client-side with jQuery
Your title says "send selected values of select box to PHP as string". You would do that in JS by catching the submit event of the form and using .join() to change the value of that field.
$('#formid').on('submit', function(){
$('#e1').val($('#e1').val().join(','));
});
Your form (not given) would need an id <form id="formid" ...>
If you want a client-side solution, try getting the val() and calling join():
$('#e1').val().join()
http://jsfiddle.net/gwgLV/
You can do it with javascript.
<select id="e1" name="mydata" multiple>
<option value="D1">Data1</option>
<option value="D2">Data2</option>
<option value="D3">Data3</option>
</select>
<button id="but" onclick="now()">Show selected values</button>
javascript code
function getSelectValues(select) {
var result = [];
var options = select && select.options;
var opt;
for (var i=0, iLen=options.length; i<iLen; i++) {
opt = options[i];
if (opt.selected) {
result.push(opt.value || opt.text);
}
}
return result;
}
function now(){
var el = document.getElementsByTagName('select')[0];
var x = getSelectValues(el);
alert(x);
}
Demo here
Instead of alert store in a variable and send it along with the rest of the form data. Or you can use join (as mentioned in other answers ) to send it over post to php.
I am dynamically generating a dropdown list on the page when a user loads it. I'd like to get the value of the dropdown using jquery or javascript.
The tricky part is that the dropdown will have a value as such:
"I love Rabbits ($19.95)"
I want to get the value of the dropdown and then isolate the value inside of the brackets.
Any ideas?
Cheers!
Getting the value is easy, use val(). That will be a string.
Then you just grab the value with a regex, probably with a capture group; for instance:
var value, m, innerValue;
value = $("selector for select box").val();
m = /\(([^)]+)/.exec(value);
if (m) {
innerValue = m[1];
}
That regex says: "Find a ( and then capture everything following it that isn't a )". Then we take the value of the capture group.
Could you not have your select in the following format:
<select name="opinions_price">
<option value="19.45">I love rabbits (£19.45)</option>
<option value="12.45">I hate parakeets (£12.45)</option>
<option value="3.24">I am indifferent to possums (£3.24)</option>
</select>
Then simply do:
var price = $('select option:selected').val();
If you want to use the data attributes instead (assume the select is in a loop, you know how to do that):
<select name="opinions_price">
<?php foreach($things as $thing) { ?>
<option data-price="<?php echo $thing['price']; ?>" data-id="<?php echo $thing['id']; ?>">[..]</option>
<?php } ?>
</select>
Then simply do:
var price = $('select option:selected').data('price');
var id = $('select option:selected').data('id');
Saves a (possibly) expensive Regex?
Say I have two drop downs which are populated when the my jsp loads
<select id="Group" name="group"> -- first drop down
<option value="0001">1</option>
<option value="0002">2</option>
</select>
<select id="subGroup" name="class"> -- second drop down
<option value="0001-000">A</option> -- sub group associated with option value 001
<option value="0001-010">B</option>
<option value="0001-020">C</option>
<option value="0001-030">D</option>
<option value="0001-040">E/option>
<option value="0002-000">F</option> -- sub group associated with option value 002
<option value="0002-010">G</option>
<option value="0002-020">H</option>
<option value="0002-040">I</option>
</select>
Now I need to filter the second drop down based on the selected value in first drop down. I can't use the PHP code which uses the DB callback methods. in my script I have something like this.
$("#Group").change(function() {
var groupVal = $(this).find("option:selected").val();
$('#subGroup option').filter(function( {return!$(this).val().indexOf(groupVal)!=-1);}).remove();
});
the script is working fine, it removes all the options other then the one selected. but my problem is that next time when i select other value in first drop down, second drop down goes empty. I even worked with hide/show but guess they wont work with <select> :(
is there any way by which I can repopulate the second drop down when I selected some other option in first drop down?
If you are removing elements, you aren't getting them back. Use hide() and show() as you yourself suggested:
$("#Group").change(function() {
var groupVal = $(this).find("option:selected").val();
$('#subGroup option').hide();
$('#subGroup option[value^='+groupVal+']').show();
});
In other words, every time the #Group selectbox is changed, hide all options in #subGroup and show only the ones whose value attribute starts with groupVal.
Store all the options for the second select box into a array when the page loads. Then populate the select box from that array on change.
You are removing the second "batch" of options so they don't exists any more the next time you want to use them.
In order to do that you need to store all available options somewhere and then repopulate from that data set. for example
var availableOptions = {
'groupOne': {/* options as {value: '', text: ''} */},
'groupTwo': {/* options as {value: '', text: ''} */}
};
$("#Group").change(function() {
var groupVal = $(this).find("option:selected").val();
var sub = $('#Subgroup');
$.each(availableOptions[groupVal], function(i, data){
sub.append('<option value="'+data+'">'+data.text+'</option>');
});
There's also a related select box plugin by Remy sharp that I've had success with if you want to try:
http://remysharp.com/2007/09/18/auto-populate-multiple-select-boxes/