I have a form in which i use javascript to set the select element options depending on type of property (house, flat, etc). it is working now when I am accessing the list using the document.myForm.priceSelect.options.
I want to access it by id rather than name. Because I want to set the name also along with the options so that when the form is submitted, the name of the list will determine which function to execute. Some code to illustrate:
if(prop_type == 'flat') {
document.getElementById('priceRange').setAttribute('name', 'flatRange');
.....
Now here I am changing the name of the select list called priceRange. How can I also change the options using the id instead of the name like shown below:
document.searchForm.priceRange.options[1]=new Option("10000 - 20000", "10000 - 20000");
Thank you in advance...
UPDATE:
After change: (not working)
if(prop_type == 'flat') {
document.getElementById('priceRange').setAttribute('name', 'flatRange');
document.getElementById('priceRange').options.length=0;
document.getElementById('priceRange').options[0]=new Option("", "");
document.getElementById('priceRange').options[1]=new Option("10000 - 20000", "10000 - 20000");
Simply use
document.getElementById(yourId).options[1]=new Option("10000 - 20000", "10000 - 20000");
dystroy's method should work - see this fiddle here
An alternative is to create a wrapper method for option creation, such as this:
function createOption(objSelect, optText, optValue){
var objOption = document.createElement("option");
objOption.text = optText;
objOption.value = optValue;
if(document.all && !window.opera){
objSelect.add(objOption);
}
else
{
objSelect.add(objOption, null);
};
}
Then you can add options to the select:
var priceRange=document.getElementById('priceRange');
createOption(priceRange, "10000 - 20000", "lowball");
Fiddle for the wrapper method here
Related
So I have an object in my code and I use js to add the properties of the object to an array named rec based on users interaction. then I use a function named unRec to get unique elements of the array. Then I add the values returned by unRec to the HTML. Then I use jquery to wrap each of the values in anchor tags. So the code is basically like this
obj= {
0: "<span>module1</span>",
1: "<span>module1</span>",
2:"<span>module1</span>",
3:"<span>module2</span>",
4:"<span>module2</span>",
5:"<span>module3</span>",
6:"<span>module3</span>",
7:"<span>module3</span>",
8:"<span>module3</span>",
9:"<span>module4</span>"
}
function unRec(arr){
preRec = [];
for (j of arr){
if (preRec.indexOf(j)=== -1) {
preRec.push(j);
}
}
return (preRec);
}
Recom.innerHTML = unRec(rec);
$('#congrat #recom span').wrap('')
Now am unable to select the created anchors. Hence this function doesn't work
$('#congrat #recom .disp').click(function(e) {
var url = $(this).attr('href') + '#' + $(this).text();
$('#module').html('loading...).load(url); e.preventDefault();
});
I have tried to use find to select the anchors but it still doesn't work. This is the test
var t = $('#congrat #recom').find ('a').length;
console.log(t);
The HTML is basically like this:
<div id="congrat">
<span id="recom"></span>
</div>
<div id="module">click on one of the modules above<div>
Please provide a solution to select the created anchors. Thanks in advance
When using Chosen.js on a multiple select field, if there are over 500 options that the user has selected, the list just becomes ridiculously long.
Is there any way I could limit the number of show elements? For example when chosing over 3 options, the user will have (4) options are selected..., instead of them being listed.
I wonder why there's no such option in their documentation.
Thanks in advance.
You can use something like this:
$('.element').chosen().change(function() {
var totalSelected = $(this).find('option:selected').size();
var placeholder = $(this).find('option:first-child').text();
if(totalSelected > 3) {
$(this).next().find('.chosen-choices').find('li.search-choice').hide(),
$(this).next().find('.chosen-choices').find('.literal-multiple').show();
$(this).next().find('.chosen-choices').find('span.literal-multiple').text(placeholder + " ("+totalSelected+")");
}
});
The class literal-multiple is a custom element to show the totalSelected elements. You need to add it in the prototype of the chosen plugin:
file chosen.jquery.js
Chosen.prototype.set_up_html = function() {
//stuff
if(this.is_multiple) {
var selVal = this.default_text;
this.container.html('<ul class="chosen-choices"><span class="literal-multiple"></span></ul>');
}
};
SOrry I am unable to comment since I don't have enough reputation.
But to add to the previous answer, instead of adding a separate container,
why don't we just append the n users selected as a <li> item.
Something like this -
$('.element').chosen().change(function() {
var totalSelected = $(this).find('option:selected').size();
var placeholder = $(this).find('option:first-child').text();
if(totalSelected > 3) {
$(this).next().find('.chosen-choices').find('li.search-choice').hide(),
$(this).next().find('.chosen-choices')append('<li class="search-choice" <span>'+totalSelected+' users selected. </li>');
}
});
This seems to work for me.
I have a selectize.js dropdown and I have to clear the selected value .
I have tried this (as suggested in another question):
var selectize = $("#optionNetFlow")[0].selectize;
selectize.clear();
But it gives the following error:
When I change it to this:
var selectize = $("#optionNetFlow").selectize;
selectize.clear();
I gives this error:
What I am doing wrong here?
I finally found the answer here Selectize.js Demos
What works for me is:
var $select = $('#optionNetFlow').selectize();
var control = $select[0].selectize;
control.clear();
what I was missing var $select = $('#optionNetFlow').selectize(); before applying the solution provided in above question's answer.
Now I am to get all the functions in console like :
Try this,
$("#optionNetFlow")[0].selectize.clear();
Try this out:- http://jsfiddle.net/adiioo7/2gnq1ruv/204/
JS:-
jQuery(function ($) {
var $select = $('#input-tags').selectize({
persist: false,
create: true
});
$("#btnClear").on("click", function () {
var selectize = $select[0].selectize;
selectize.clear();
});
});
All other answers either clear a single selectize or need a specific reference to the selectize in the moment of it's creation.
The solution below, on the other hand, works for any number of selectize elements you have inside any form; you just need to specify the desired form:
$('form').find('.selectized').each(function(index, element) { element.selectize && element.selectize.clear() })
The rationale is that Selectize keeps the original element in the DOM (hiding it), adds a reference to the selectize on the .selectize property of the DOM element and adds a CSS class selectized to it.
So the solution finds all the elements that have the CSS class selectized, loops through them and calls element.selectize.clear().
$(document).on('click', 'div.selectize-input div.item', function(e) {
var select = $('#services').selectize();
var selectSizeControl = select[0].selectize;
// 1. Get the value
var selectedValue = $(this).attr("data-value");
// 2. Remove the option
select[0].selectize.removeItem(selectedValue);
// 3. Refresh the select
select[0].selectize.refreshItems();
select[0].selectize.refreshOptions();
});
This do not remove the item from the select, just remove it from the selected options.
Or if you have multi select, and do want to restore selected items in the drop-down list (hide selected set to true).
var selectize = $("#select-item").selectize;
//clone array
var items = selectize.items.slice(0);
for (var i in items) {
selectize.removeItem(items[i]);
}
selectize.refreshOptions();
I'm using the chosen plugin to build multiple select input fields. See an example here: http://harvesthq.github.io/chosen/#multiple-select
The default behavior disables an option if it has already been selected. In the example above, if you were to select "Afghanistan", it would be greyed out in the drop-down menu, thus disallowing you from selecting it a second time.
I need to be able to select the same option more than once. Is there any setting in the plugin or manual override I can add that will allow for this?
I created a version of chosen that allows you to select the same item multiple times, and even sends those multiple entries to the server as POST variables. Here's how you can do it (fairly easily, I think):
(Tip: Use a search function in chosen.jquery.js to find these lines)
Change:
this.is_multiple = this.form_field.multiple;
To:
this.is_multiple = this.form_field.multiple;
this.allows_duplicates = this.options.allow_duplicates;
Change:
classes.push("result-selected");
To:
if (this.allows_duplicates) {
classes.push("active-result");
} else {
classes.push("result-selected");
}
Change:
this.form_field.options[item.options_index].selected = true;
To:
if (this.allows_duplicates && this.form_field.options[item.options_index].selected == true) {
$('<input>').attr({type:'hidden',name:this.form_field.name,value:this.form_field.options[item.options_index].value}).appendTo($(this.form_field).parent());
} else {
this.form_field.options[item.options_index].selected = true;
}
Then, when calling chosen(), make sure to include the allows_duplicates option:
$("mySelect").chosen({allow_duplicates: true})
For a workaround, use the below code on each selection (in select event) or while popup opened:
$(".chosen-results .result-selected").addClass("active-result").removeClass("result-selected");
The above code removes the result-selected class and added the active-result class on the li items. So each selected item is considered as the active result, now you can select that item again.
#adam's Answer is working very well but doesn't cover the situation that someone wants to delete some options.
So to have this functionality, alongside with Adam's tweaks you need to add this code too at:
Chosen.prototype.result_deselect = function (pos) {
var result_data;
result_data = this.results_data[pos];
// If config duplicates is enabled
if (this.allows_duplicates) {
//find fields name
var $nameField = $(this.form_field).attr('name');
// search for hidden input with same name and value of the one we are trying to delete
var $duplicateVals = $('input[type="hidden"][name="' + $nameField + '"][value="' + this.form_field.options[result_data.options_index].value + '"]');
//if we find one. we delete it and stop the rest of the function
if ($duplicateVals.length > 0) {
$duplicateVals[0].remove();
return true;
}
}
....
Javascript has textObject.defaultValue=somevalue for retrieving the default value (stored value from page load) of an input even if you wipe the input and replace the contents, you can still get the default back. Like this:
// in the html page
<input id="addr1" type="text" value="21 Oak St." />
// the jquery
myInput = $("#addr1"); // the input, default value on page load = 21 Oak St.
$(myInput).val('51 New St'); // wipe default and set new
// alerts 21 Oak St
alert($(myInput).val($(myInput)[0].defaultValue));
How do you accomplish this on a select?
selectedIndex is boolean, not the value, so that does not work.
Thanks!
You probably want to look at the "defaultSelected" attribute of "option" elements.
Initially, "defaultSelected" will be true if the original HTML of the option tag had an explicit "selected" attribute. You can change that by setting the attribute on option tags with Javascript after the page has loaded, in response to whatever conditions you like.
This is the jquery that works for me:
$('select[name="name_of_select"] option[selected]').val()
with Jquery we can do sth like this :
$('select[name="type_id"] option').map(function()
{
if($(this).attr('defaultSelected')==true) return this
}).get(0).value;
This will return the default Selected option value
:)
I used the following to loop through a forum, check their default values and their current values.
if the script comes a cross a single selectbox it will loop through the children on the selectbox.
oFormObject = document.forms[0];
for(i=0; i<oFormObject.elements.length; i++)
{
oValue = oFormObject.elements[i].value;
oType = oFormObject.elements[i].type;
if(oType=='select-one') {
for(k=0; k<oFormObject.elements[i].children.length; k++)
{
if(oFormObject.elements[i].children[k].defaultSelected==true){
oformElement = oFormObject.elements[i].children[k].value;
}
}
}else{
oformElement = oFormObject.elements[i].defaultValue;
}
console.log(oformElement);
console.log(oValue);
console.log(oType);
}
there may be multiple "selected" option elements, in that case pick the first if no other requirements are set. #Pointy tip is correct but be aware that the "defaultValue" property can be overwritten by other code in the same page. If it were read-only it would be more useful :-)
I found a shortest way to do this :
$('select#myselect').find('option[defaultSelected]');
I run this on page load to manually set the defaultValue for Select boxes.
// Set a default value property on selectboxes (for reverting)
$('select').each(function(index,ele) {
var origvalue = $(this).val(),
defaultvalue = $(this).prop('defaultValue');
// If the default value hasn't already been set for this selectbox
if(!defaultvalue) {
$(this).prop('defaultValue', origvalue);
}
});
The simplest way to do this is:
$('#selectbox option').prop('selected', function() {
return this.defaultSelected;
});