"defaultValue" property for <select>? - javascript

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;
});

Related

Javascript change id from form input

I am working on a new project and I ran into one issue
I want to have a form where the user can enter their username so a 3d image is generated.
The code for the image generator is:
<span class="mc-skin" data-minecraft-username="UsernameHere"></span>
and what I need is a input field that changed the data-minecraft-username to the input of the form.
Thanks for any help!
you can try this:
var user="Zane";
document.getElementsByClassName("mc-skin")[0].setAttribute('data-minecraft-username',user);
But it will be better if you will use id for that particular span and set it like this:
add id="spanId" then use
document.getElementById('spanId').setAttribute('data-minecraft-username', user);
You can use HTML 5
Example:
variable.setAttribute('data-minecraft-username','randomUserName');
variable beeing your span element
More reference here: http://html5doctor.com/html5-custom-data-attributes/
Probably the most robust way to deal with data-* attributes is to use setAttribute and getAttribute. If the span has an id of Skin, then you might use:
var span = document.getElementById('Skin');
span.setAttribute('data-minecraft-username', newValue);
You can also use the element.dataset property:
span.dataset['minecraft-username'] = newValue;
Which will add a data-minecraft-unsername attribute with a value of whatever is in newValue. However, support may be lacking in older browsers (see MDN HTMLElement.dataset, which indicates fairly recent browsers such as IE 11, Safari 6, etc. are required).
Also see MDN Using data attributes.
To use the above script in a document, you might do something like:
<script>
function setDataAttribute(elID, attName, value) {
var el = document.getElementById(elID);
if (el) {
el.setAttribute('data-' + attName, value);
}
}
function setContent(elID, value) {
var el = document.getElementById(elID);
if (el) {
el.innerHTML = value;
}
}
</script>
<span id="Skin"></span>
<br>
<input type="text" onblur="
setDataAttribute('Skin', 'minecraft-username', this.value);
setContent('Skin', this.value);
">

jquery clone an input doesn't see changes to the value

I have a form with hidden inputs.
I .clone() them and show them to the user in a .dialog().
The user makes some changes and i use .val() to change the hidden fields.
However the next time i clone the form(without reloading the page) i have the initial values again, and never the updates ones.
There seems to be this weird bug/result? see http://jsfiddle.net/YvBfP/ (broken for visible input too)
$(this).closest('td').find('button').click( function ()
{
var d = $('#pagamento_anticipato').html();
$(d).dialog({
modal: true,
width: 400,
height: 300,
close: function( event, ui ) {
var importo = $(this).find('input[type="text"]').val();
var descrizione = $(this).find('textarea').val();
var select = $(this).find('select').val();
$(this).remove();
$('#pagamento_anticipato').find('input[id="importo"]').val( importo );
$('#pagamento_anticipato').find('#descrizione').val( descrizione );
$('#pagamento_anticipato').find('#tipo').find('option[value="' + select + '"]').attr('selected', true);
}
});
return false;
});
using .val() sets/gets the current value and not the attribute for the element.
$(element).val(value) // sets current value
$(element).val() // <-- will always return the current value
to change the attribute you have to use .attr()
$(element).attr('value',value)
Then you will see the change in the HTML
http://jsfiddle.net/wirey00/bJjjw/
EDIT:
Just found out this doesn't work with jQuery 1.5.x and lower.. tested it with jQuery 1.6.0+ and it worked fine
You are setting the value property of the input but checking to see if the value attribute has changed. To see the elements value use .val() don't check its html. However if you need to change the elements value attribute use setAttribute
$('#money')[0].setAttribute('value', 3000);
http://jsfiddle.net/YvBfP/4/

javascript setting select element options using getElementsById

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

How to add "selected" in option attribute using Javascript or jQuery?

Below is code for select option and generate using php from database and i try to add selected="selected" to value="4" using jQuery or any javascript:
<select id="countryselect" name="country">
<option value="1">Afghanistan</option>
<option value="2">Albania</option>
<option value="3">Algeria</option>
<option value="4">Malaysia</option>
<option value="5">Maldives</option>
</select>
i try to refer this post but still can't .. below is my current script :
<script>
localStorage.setItem("Select1", "Malaysia");
$('#countryselect').find('option').each(function(i,e){
if($(e).val() == localStorage.getItem("Select1")){
$('#countryselect').prop('selectedIndex',i);
}
});
</script>
thanks.
The selected attribute is a boolean attribute, its presence sets the value of the related DOM property to true. If the attribute is absent, the value of the selected property is false.
If an option has the selected attribute, then when the page is first loaded, or the form the control is in is reset, that option will be the selected option.
If the option's selected property is set to true, then that option will be selected. However, if the form is reset, the default selected option will be selected (i.e. the one with the selected attribute, or the first option, or none).
To set the selected attribute (i.e. make the option the default selected option):
var select = document.getElementById('countryselect');
var option;
for (var i=0; i<select.options.length; i++) {
option = select.options[i];
if (option.value == '4') {
// or
// if (option.text == 'Malaysia') {
option.setAttribute('selected', true);
// For a single select, the job's done
return;
}
}
Note that this may not make the option the currently selected option, it will just add the selected attribute. To make sure it's selected (if that is what is required), the also set the selected property to true (see below).
Note that the second argument to setAttribute is supposed to be a string that is used to set the attribute's value. However, the selected attribute doesn't have a "setable" value, so the second argument is ignored (e.g. even false will still set the attribute and make the option the default selected option). That causes some confusion. :-)
To set the selected property (i.e. just make the option the current selected option):
var select = document.getElementById('countryselect');
var option;
for (var i=0; i<select.options.length; i++) {
option = select.options[i];
if (option.value == '4') {
// or
// if (option.text == 'Malaysia') {
option.selected = true;
return;
}
}
This should work simple, $("#countryselect").val('4')​
It will automatically set selected=selected
Demo: http://jsfiddle.net/muthkum/zYRkC/
localStorage.getItem("Select1") will return Malaysia and $(e).val() will return 1,2...5 in each loop. So your condition will never be true. Instead use
<script>
localStorage.setItem("Select1", "4");
$('#countryselect').find('option').each(function(i,e){
if($(e).val() == localStorage.getItem("Select1")){
$('#countryselect').prop('selectedIndex',i);
}
});
</script>
As of jQuery 1.6 "To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method."
$("#countryselect option[value=4]").prop("selected", "selected")
Just try
$("#countryselect").val('4')
//OR
$("#countryselect option").val('4')​.attr("selected", true)​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
Check this FIDDLE
$('#countryselect > option[value *= "4"] ').attr('selected',true);
this will work

Change a variable or activate a JS-linked <select> dropdown with Greasemonkey

I'm looking to change a javascript variable on page load with Greasemonkey.
The variable I'm looking to change is iDisplayLength the default value is 25, I want to change it to -1 on page load.
This is the script I tried; it did not work:
function changeTheDefaultViewVarLol() {
location.href = "javascript:void(windows.iDisplayLength = -1)";
};
changeTheDefaultViewVarLol();
Edit: From a comment below, the target page is tf2spreadsheet.blogspot.com.
The OP is actually trying to change the number of rows displayed on the page -- a function that is triggered by the "Show {x} entries" <select> dropdown.
You would just use:
unsafeWindow.iDisplayLength = -1;
No need for any of that changeTheDefaultViewVarLol() stuff.
However, this will not have the effect that you want if iDisplayLength is used by the page just after the page sets it to 25.
You will probably have to call a JS function to apply the new value. Link to the target page if this is the case.
Update for additional page information:
What you are actually trying to do is to invoke the "Show All entries" functionality of that page.
So, don't think in terms of poking JS variables, think in terms of activating whatever JS is tied to that <select>.
For a normal page similar to the one you specified, code like this would do it:
var showAllOpt = document.querySelector ('#main_table_length select option[value="-1"]');
var changeEvent = document.createEvent ("HTMLEvents");
if (showAllOpt) {
showAllOpt.parentNode.selectedIndex = showAllOpt.index;
changeEvent.initEvent ("change", true, true);
showAllOpt.parentNode.dispatchEvent (changeEvent);
}
BUT, that page AJAXes-in the desired table long after the page "loads". So, an additional step is needed, like so:
var showAllEntriesSelect = setInterval ( function() {
setSelectValueWhenitLoads (
"#main_table_length select option",
"-1",
showAllEntriesSelect
);
}
, 200
);
function setSelectValueWhenitLoads (cssSelector, targetValue, timerVar) {
var showAllOpt = document.querySelector (
cssSelector + '[value="' + targetValue + '"]'
);
if (showAllOpt) {
clearInterval (timerVar);
showAllOpt.parentNode.selectedIndex = showAllOpt.index;
var changeEvent = document.createEvent ("HTMLEvents");
changeEvent.initEvent ("change", true, true);
showAllOpt.parentNode.dispatchEvent (changeEvent);
}
}

Categories

Resources