Print counter and value of selected options inside textbox using jquery
I wanted to make a script to parse the number of selected options from a dropdown. I tried my code for jsfiddle but it doesn't work, even if I don't get the error.did syntax, did I do something wrong?
$(document).ready(function(){
var count=$("#jform_params_foreignmanuf:selected").length;
$("#jform_params_manucounter").val(count);
});
http://jsfiddle.net/aewsduwo/22/ .
Also if I wanted to create a text area and print the dropdown value?
$(document).ready(function(){
var $val= $("#jform_params_foreignmanuf:selected").val;
$("#jform_params_manucounter").val($val);
});
http://jsfiddle.net/pvpqd286/6/ I think for the first option in my example
<option selected="selected" value="127">1</option>
would come out "127" instead of "1" which I want to print correctly?
source to share
A couple of things:
1) You need to escape the special character present in the id tag.
2) You need to find the parameter by the selected attribute and not select the selected element
$("#\\#jform_params_foreignmanuf :selected").length
Demo for the selected number of options
and to get the value of the selected items in the textbox as a semicolon string:
var count=$("#\\#jform_params_foreignmanuf").val().join(",");
$("#jform_params_manucounter").val(count);
Update: to get the first selected option text:
var firstselectedtext=$("#\\#jform_params_foreignmanuf :Selected:first").text();
$("#jform_params_manucounter").val(firstselectedtext);
Demo for the first selected option text
to get all selected text options:
var selectedtext=$.map( $('#\\#jform_params_foreignmanuf :Selected'), function (element) {
return $(element).text()
});
$("#jform_params_manucounter").val(selectedtext.join(','));
source to share
- If I wanted to create a text area and print the dropdown value ?
Then you can do this:
$(document).ready(function () {
var $val = $('select[id="#jform_params_foreignmanuf"] :selected').text();
$("#jform_params_manucounter").val($val);
});
Because your select element contains a special character #
, so you can avoid it with \\
or you can make an attribute selector like above.
- will come out "127" instead of "1" which I want to print correctly?
To do this, you just need to use .text()
instead .val()
.
source to share
You can try this:
$("#jform_params_foreignmanuf").on('click', function(){
var count = $("#jform_params_foreignmanuf option:selected").length; //count selected options
$("#jform_params_manucounter").val(count);
var val= [];
$("#jform_params_foreignmanuf option:selected").each(function(){
val.push($(this).text()); //save each selected text in array
});
$("#jform_params_manuvalue").text(val.join(',')); //write selected text to textarea (comma-seperated)
});
source to share