Exist any way to replace option display value?
I mean, here i need to replace "one"->"first option", "two"->"second", there are also already values also available.
HTML
<select id="selecttool">
<option value="7">one</option>
<option value="3">two</option>
<option value="375">three</option>
</select>
JavaScript
$(document).ready(function() {
$("#selecttool").children().val("-79");
if($("#selecttool").val('7')) {
}
});
Here is my JSfiddle, so i tried to replace, but don't know how to insert value:
JSFiddle
You can pass a function to the text() method for each option:
$('#selecttool option').text(function(){
return this.value;
});
JSFiddle
EDIT
If you want 'custom text' you'll need to get it from somewhere, so create an array:
var vals = ['first option', 'second option', 'third option']
$('#selecttool option').text(function(i){
return vals[i];
});
JSFiddle
ANOTHER
If you wanted to select on the text within the option:
$('#selecttool option:contains(one)').text('first option');
You can pass your text to the text() function as follows
$("#selecttool option[value='79']").text("label");
your way of selecting the element is wrong. you should select OPTION, not SELECT.
like:
$('#selecttool option').eq(0).text("First Item"),
But, this will be very much mannual work, because you need to it one-by-one for all the options. So, if you have all the text, store it in an array as suggested oGeez, and then do a loop. like :
var labels = ["First Item", "Second Item", "last Item"];
$('#selecttool option').each(function(c, obj){
$(obj).text(labels[c]);
});
yes you can easily replace value with jquery like this
var value = $("#text").val(); // value = one use $("#text").text() if you are not on select box...
value = value.replace("1", "one");
Related
Just wondering if someone can help me on a problem, I don't fully undersand why it doesn't work.
I have this fiddle, http://jsfiddle.net/uomt99zp/
What it is doing:
When you select from the drop down box, insert that word into the textarea.
Which it DOES, when the textarea isn't "touched".
If you type something into the box, and then try to select an item, it doesn't work.
I'm not sure why this doesn't update the textarea. Perhaps someone can shed some light on this issue?
<textarea name="template" required="required" class="template form-control" rows="6"></textarea>
<select class="templatesAvailableFields">
<option>Select One</option>
<option>Test1</option>
<option>Test2</option>
<option>Test3</option>
</select>
$('.templatesAvailableFields').on('change', function() {
var text = $('.templatesAvailableFields option:selected').text();
$('.template').append(text);
});
You need to set value using .val():
$('.template').val($('.template').val()+text);
Working Demo 1
Also .val() can have callback function which can be used for setting a new value:
function
Type: Function( Integer index, String value ) => String
A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments.
$('.template').val(function(i,v){ return v+ text});
Working Demo 2
You can try val(function) with old value + new text to append,
$('.templatesAvailableFields').on('change', function() {
var text = $('.templatesAvailableFields option:selected').text();
$('.template').val(function(ind,val){
return val+text;
});
});
Live Demo
To answer to the "why" it does not work, it's because, the contents of a textarea represent its default value. So, when you append an element to the textarea, you change the default value of this textarea.
So it changes the textarea as long as you did not type in. Once you typed in, the default value is no more used, even if you remove all the text of the textarea.
By using .append you are just concatinating your output string if you want only the dropdown element it would be better to use the .text() or .val() method
$('.templatesAvailableFields').on('change', function() {
var text = $('.templatesAvailableFields option:selected').text();
var existing=$('.template').val();
$('.template').val(existing+text);
});
.append(), .html() and .text() methods do not work with form elements, for setting/getting value of a from element .val() method should be used instead:
Your code is working ...i tried it in visual studio .... Only change I had made is I kept the script under the option control... I am not sure about.for me its working fine.
<body >
<textarea name="template" required="required" class="template form-control" rows="6"></textarea>
<select class="templatesAvailableFields">
<option>Select One</option>
<option>Test1</option>
<option>Test2</option>
<option>Test3</option>
</select>
<script type="text/javascript">
$('.templatesAvailableFields').on('change', function () {
var text = $('.templatesAvailableFields option:selected').text();
$('.template').append(text);
});
</script>
</body>
You should control input value's with val() method
// cache element
var $select = $('.templatesAvailableFields');
$select.change( function() {
$('.template').val($select[0].value);
});
just replace append with text
here is the updated fiddle
$('.templatesAvailableFields').on('change', function() {
var text = $('.templatesAvailableFields option:selected').text();
$('.template').text($('.template').text() + text);
// $('.template').val(text); this won't work in IE <= 7
});
http://jsfiddle.net/rrehan/uomt99zp/2/
I fill my <select> with the response from ajax call.
Here's the JS code:
var myOptions = {val1 : project1,
val2 : project1,
val4 : project1,
val5 : project1,
};
$.each(myOptions, function(val, text) {
$('#projectid').append(
$('<option ></option>').val(val).html(text)
);
});
my html code:
<input type="hidden" name="ehidden" value="true">
<select name="project" id="projectid"></select>
The required DropDown list I get is ok, but I can't set the first <option> to default selected.
Here's some code I already tried:
$('select.projectid').find('option[value="val1"]').prop('selected', true);
I got no error, but also no result. The same with this one:
$("#projectid").val($("#projectid option:first").val());
Second Problem:
the first <option> is not available the first time I select it per mouseclick, I have to first select the second <option> and then the first again.
Your selector is wrong on this line:
$('select.projectid').find('option[value="val1"]').prop('selected', true);
That is selecting a drop-down with a class of projectid. It should be:
$('#projectid').find('option[value="val1"]').prop('selected', true);
...which will select the element with an id of projectid.
Concerning this code:
$("#projectid").val($("#projectid option:first").val());
I'm not sure what you intended it to do, but it will select the first option in the drop-down. If no other option is selected, the first one is selected by default. So, if you were to run this code when the page loads, it of course would do nothing since the first option is already selected.
Concerning your "second" problem, you need to post that as a separate question as it's unrelated to this one. But, be sure to search for an answer to it here on SO before you pose it.
There are a few improvements you can make to your code that will make it simpler and allow you to easily mark the selected option. Here is a jsfiddle to solve your problem: jsfiddle
var myOptions = [
{ name: "A", value: "val1", selected: true},
{ name: "B", value: "val2"},
{ name: "C", value: "val3"},
{ name: "D", value: "val4"}
];
var optionsHtml = "";
for(var i = 0; i < myOptions.length; i++) {
var val = myOptions[i];
optionsHtml += '<option value = "' + val.value + '"';
if(val.selected)
optionsHtml += 'selected="' + val.selected + '"';
optionsHtml += '>' + val.name + '</option>';
}
$('#projectid').append(optionsHtml).selectmenu('refresh', true);;
Explanation
You will want to just build the html for your options and then appending to all the selects once. This will improve the performance of your code because you will only be appending once, thus causing the browser to do one redraw.
Doing it this way you can build the options as a string. I don't know how you determine which option to select but you should be able to change the if clause to suit your needs.
What you tried
$('select.projectid').find('option[value="val1"]').prop('selected', true);
This will not work because your selector is wrong. You are using the id as a class here you want:
$('#projectid')
$("#projectid").val($("#projectid option:first").val());
I'm not sure why this does not work. But you would not want to do it this way because it would be hard to select the option dynamically.
EDIT
To get the select in jQuery Mobile to update its selection you must call refresh. See the documentation here.
Can't figure this out for the life of me. Using AngularJS.
I have a dropdown Select field with several options. It is a part of a form that may be completed multiple times (ie "add another" type form). Now, one of the options may only be used once. How can I remove this option from all other select fields after it has been used?
What I'm working with:
html
<select ng-model="item.itemtype">
<option ng-repeat="i in itemtype" value="{{i}}" ng-init="item.itemtype = itemtype[0]">{{i}}</option>
</select>
angularjs
$scope.Items = [
{ 'itemtype': '', 'desc': '', 'color': '' }
];
$scope.itemtype = [
'shirt',
'pants',
'hats',
'shoes',
'special'];
What I've tried (and really doesn't work)
$scope.specialremove = function() {
var exist = Items.indexOf("special")
if (exist !== 0) {
return '';
}
else {
return 'special';
}
}
I'm hoping I don't have to turn to any other framework to solve this. Feel free to point out any other problems/errors/inefficiencies in my code.
The first thing that can help is using ng-options:
ng-options="type for type in itemType".
It would be better to have objects with label and value properties, in order to write it as
ng-options="type.value as type.label for type in itemType"
and separate the displayed label from the actual value of the selection.
In your controller you should have something like:
$scope.itemType= [
...
];
$scope.selectedItem= $scope.itemType[0];
So that you can write the select as:
<select ng-Model="selectedItem" ng-options="item.value as item.label for item in itemType"></select>
To remove a selected item you can watch the value of selectedItem in the controller: when it matches the value you want, remove it from the array and update selectedItem accordingly.
Here is a basic fiddle. I simply remove the third option after selecting it, and reset the selected item to the first.
i am using a multi select box in javascript as given here:
i want to get the list of selected items in the multi select text box (the left list)
what can i do to achieve that?
my select box is as follows:
<select id="userList" class="multiselect" multiple="multiple" name="users[]" style="width: 75px;">
//List
</select>
i guess users[] stores the selected users at a point in time. but i can't figure out how to retrieve that variable.
Doing this will work:
$('[name="user[]"]').val()
PS: You need to have jQuery included in your webpage.
from the demo at http://www.quasipartikel.at/multiselect/, doing $('[name="countries[]"]').val() will give sample output:
["ARM", "AUS", "AUT"]
Get a list of values with jQuery:
var values = $select.find('option:checked').map(function() {
return this.value || this.text;
});
// or $select.val() of course, like lemarc says
// => ['ABC', 'DEF']
var prefix = encodeURIComponent($select.attr('name')) + '=';
var httpQuery = values.length ? prefix + values.map(function() {
return encodeURIComponent(this);
}).join('&' + prefix);
// => users[]=ABC&users[]=DEF
I didn't test it.
This will return array of selected values
$('#userList').val();
DEMO
You can directly target $(".multiselect") Object, by doing this:
$("input[type='submit']").click(function(e){
e.preventDefault();
_selValue = $(".multiselect").val(); //You will have variable of selected values
for(var i=0;i<_selValue.length;i++){
alert(_selValue[i]);
//You can iterate it individually in loop
}
});
if I'm passing a jquery object that I know is a select object, how can I get the text (not the value) of the option that is selected?
I'm needing something like this.
...function ($select){
var selectedText = $select.selected().text();
}
And since $select is already a jquery object, I cant really change the selector of the object to use ":selected".
$select.find(':selected').text();
should do.
You can use this:-
Suppose you have a dropdown like this:-
<select id="dropdown">
<option value="aa">a</option>
<option value="bb">b</option>
<option value="cc">c</option>
</select>
then javascript will be like this:-
$(document).ready(function() {
obj = $('#dropdown :selected')
value = obj.val()
alert(value) # will alert aa/bb/cc
text = obj.text()
alert(text) # will alert a/b/c
})