javascript and <option> - javascript

I do have the following JavaScript.
<form>
<select id="sel">
<option value="1">item_1</option>
<option value="2">item_2</option>
<option value="3">item_3</option>
</select>
<div id="show"></div>
</form>
<script type="text/javascript">
var sel = document.getElementById('sel');
sel.onchange = function() {
var show = document.getElementById('show');
show.innerHTML = this.value;
};
</script>
If I click onchange a new value (here: 1,2, or 3) is shown in the div "show". This is working fine. But my problem is that I want a different value to be shown but the value (1,2, or 3) should be submitted. The item has a unit like kg, pound, m, m², ....
I want something like that:
<option value="1" value2="kg">item_1</option>
I changed value to value2 in <script> but it didn't help.
show.innerHTML = this.value2;
How can I get it to work?

if you apply what #Simon said, you can try the following:
sel.onchange = function() {
var show = document.getElementById('show');
show.innerHTML = this.options[this.selectedIndex].getAttribute('value2');
}

Revised HTML:
<form>
<select id="sel">
<option value="1" data-unit="kg">item_1</option>
<option value="2" data-unit="kph">item_2</option>
<option value="3" data-unit="m2">item_3</option>
</select>
</form>
<div id="show"></div>
The revised HTML uses the custom, and in HTML5 valid, data-* attribute to store the units. I've also moved the div out of the form, but that's an entirely personal inclination, and one that you don't have to maintain (obviously...).
Amended JavaScript:
var sel = document.getElementById('sel');
sel.onchange = function() {
var show = document.getElementById('show');
show.innerHTML = this.value + this.options[this.selectedIndex].getAttribute('data-unit');
};
JS Fiddle demo.
The JavaScript looks for the option within the this node with the selectedIndex, and then uses getAttribute() to find the string contained within the data-unit attribute and concatenates that to the this.value string.

That should probably be:
show.innerHTML = this.options[this.selectedIndex].value;

If the list is not a dynamically generated one, why don't you use an "if else" construct or a "switch" construct on the populated values and display whatever you like?

Use the value attribute for the value you want submitted to the server since value is meant to contain a string that is meant to be interpreted by a computer as part of a form.
Use a different attribute to associate human readable text with the <option>. title and longdesc would be good choices.

I would recommend using jQuery if you can. If you're expecting to be able to use html5 compliant browsers, you can use the data attributes on your <option> elements. This way you'd be able to store whatever attributes you found useful.
jQuery data attributes usage

You can use .innerHTML instead of .value if you want to display the text from the drop down. If you want something completely different to be displayed, you'll need a lookup table or something similar - might be easier to use jQuery.

Related

Increasing data attribute on click

What I'm attempting seems simple enough, but I'm obviously missing something. I have a simple select menu. After selecting a country, the value is passed into a variable, prepended with a hash to change it modify it to the respected id. Using this id I'm attempting to increase the data-size by 1. The only issue is that nothing happens with the data-size.
Here's a FIDDLE.
Things should flow like this:
Select country
Select value turned into id tag
data-size of said id is increased by 1 in the HTML
EDIT/UPDATE
I need the actual data-size value to be updated in the HTML because I have specific CSS that deals with different values.
HTML
<select name="countryList" id="countryList" class="selectBox">
<option value="" disabled selected>SELECT</option>
<option value="austria">Austria</option>
<option value="brazil">Brazil</option>
<option value="canada">Canada</option>
</select>
<button class="cancel">cancel</button>
<button class="confirm">confirm</button>
<div class="dot" data-size="0" id="austria"></div>
<div class="dot" data-size="0" id="brazil"></div>
<div class="dot" data-size="0" id="canada"></div>
jQuery
var countryPicked = "";
$('.confirm').on(touchClick, function(){
countryPicked = $('#countryList').val();
countryPicked = ($('#' + countryPicked));
var i = countryPicked.data('size');
countryPicked.data('size', i + 1);
});
Try changing touchClick to "click"
The DOM will not be changed visibly, because it is stored internally.
use attr('data-size',i + 1) if you want the DOM to be updated
Demo
Try doing
countryPicked.attr('data-size', i+1);
There seems to be something wrong with .data(), it can only READ the property, not SET it.
First of all please modify the handler to:
$('.confirm').on(`click`, function(){
//code here
});
For multiple events, give comma separated value as event.
Also note that changes will not be reflected in console. However you can check them using alert or console.log
Working Demo
jQuery stores the data internally if they don't exist the first time you set them. If you really want to force it:
countryPicked.attr('data-size', i + 1);
This works for me:
Fiddle: http://jsfiddle.net/GtT3Q/13/
$('.confirm').click(function(){
var countryPicked = $('#countryList').val();
countryPicked = $('#' + countryPicked);
var i = parseInt(countryPicked.attr('data-size'));
countryPicked.attr('data-size', i + 1);
});

Need function to run on selecting an option in dropdown box

Hi I know this has probably been asked before.
I have this code so far:
<select name="cashfunction" type="text" id="cashfunction" title="Select Function"
class="required">
<option id="cashfloat">Cash Float</option>
<option id="cashvari">Cash Variance</option>
<option id="expenditure" value="1">Expenditure</option>
<option id="cashbanked" value="2">Cash Banked</option>
</select>
<script>
function bankCategory()
{
document.getElementById('bankcat').style.visibility='visible';
$('.dynamicreq').addClass("required");
}
function expendCategory()
{
document.getElementById('expend').style.visibility='visible';
$('.dynamicreq').addClass("required");
}
$('#cashfunction').on("change", function() {
if($(this).val() === 1)
{bankCategory();
}
if($(this).val() === 2)
{expendCategory();
}
}
);
</script>
I need the divs by id to remain hidden until selected.
At the moment both divs are hidden but remain hidden when I select from the menu.
I believe the reason your current code doesn't work is that you are using === to compare the string returned from .val() with numeric values 1 and 2. The === operator checks that the operands have the same value and type, so won't return true. Either use == instead, which does some implicit type conversion, or, better, compare strings with strings rather than relying on type conversion:
if($(this).val() === "1")
If it were my code I would not define separate functions for each value though, I'd try to make my code a bit more generic by having the option elements somehow specify the related divs:
<select name="cashfunction" type="text" id="cashfunction" title="Select Function" class="required">
<option id="cashfloat">Cash Float</option>
<option id="cashvari">Cash Variance</option>
<option id="expenditure" data-assoc="bankcat" value="1">Expenditure</option>
<option id="cashbanked" data-assoc="expend" value="2">Cash Banked</option>
</select>
<div id="bankcat" class="optional">Bank Category div</div>
<div id="expend" class="optional">Expenditure Category div</div>
...and then use JS something like this:
$('#cashfunction').on("change", function () {
$("div.optional").hide();
var associatedDivId = $(this).find("option").filter(":selected").attr("data-assoc");
if (associatedDivId) {
$("#" + associatedDivId).show();
}
});
Demo: http://jsfiddle.net/b372b/
Note that in my demo I used display:none instead of visibility:hidden because then I was able to just use .hide() and .show(), but if you want to keep using visibility it would be:
$("#" + associatedDivId).css("visibility", "visible");
You didn't actually include the markup for your divs in the question, but if you give them all a common class it makes it easy to hide them again if the selection is changed. (Your question never specifically says that you want to hide them again, so if not obviously you can just remove the .hide() statement.)
If using data- attributes seems too complicated you could just put the id of the associated divs in the value property, and then the JS would be:
var associatedDivId = $(this).val();
Regarding where you've coded $('.dynamicreq').addClass("required"); - I assume those .dynamicreq elements are within the divs that are being hidden or shown, but note that .addClass() will add the new class to all of them including the hidden ones.

jQuery .on not firing

I have the following code (reproduced in this jsFiddle) that is not working. There are three options in the Type select box. If the first (True/False) is selected I need the first div to be shown, and if the second or third options are chosen then the second div needs to be shown. What is wrong with this code?
HTML:
<form name="editform">
Selector: <select class="selectors" name="1-type" id="1-type">
<option value="tf" selected="selected">True/False</option>
<option value="rd">Radio Button</option>
<option value="chk">Checkboxes</option>
</select>
<div id="seldiv-1">
Good Value: <select name="1-good_value" id="1-good_value">
<option value="true">True</option>
<option value="false">False</option>
</select>
</div>
<div id="textdiv-1" style="display:none;" disabled="disabled">
Good Value:
<textarea name="1-good_value" id="1-good_value"></textarea>
</div>
</form>
Javascript:
$(document).ready(function(){
$('.selectors').on('change',function (){
var arr = $(this).name.split("-");
var id = arr[0];
var val = $(this).val();
if(val=="tf") {
$('#textdiv-'+id).hide();
$('#seldiv'+id).show();
//Make textarea disabled
//Make selection enabled
} else {
$('#textdiv-'+id).hide();
$('#seldiv'+id).show();
//Disable selection
//Enable textarea
}
});
});
Uncaught TypeError: Cannot call method 'split' of undefined.
Change $(this).name.split("-"); to this.name.split("-");
it is not the on but the split function is giving you error, you are trying to get the name method of jquery object which is not available...either you need to use attr() to get the name from jquery object..or use this DOM object to get name
try this
var arr = $(this).attr('name').split("-");
or
var arr=this.name.split('_');
NOTE both your codes inside if/else condition is same.. so you won't notice the difference..check it out in your fiddle
working fiddle example
It 100% does fire, you have an error with $(this).name being undefined. I think what you actually wanted to do there was this.name
jQuery objects don't act just like DOMElement objects, i.e they don't have the same properties (like .name). Next time, open your web console when trying to find out why something doesn't work and you will catch most of your problems there.
This line is your problem:
var arr = $(this).name.split("-");
on is working properly but the line above is throwing an exception.
var arr = $(this).attr("name").split("-");
There are a few ways you could fix this, above is one example.
your problem is when trying to access $(this) which is undefined.
Try just this instead
this.name.split("-");
The name is not a valid property. Rather use id or change the way you access it to var arr = $(this).attr('name').split("-");.

Data and HTML Dropdown

So I'm trying to populate a HTML dropdown using Javascript/Jquery. I'd like each <option> tag to have some data associated with it, stuff like searchPurpose, searchTime, startDate, endDate. I then have two questions-
How should I associate that data - through data tags, or through something else?
How do I access that data once my user has clicked on a certain option?
Thanks
With HTML5, data-* attributes are definitely the way to go. Suppose you have the following:
<select id="ddl">
<option data-start-date="25-08-2012" value="1">A</option>
<option data-start-date="25-08-2013" value="1">B</option>
</select>
To access their value with plain JavaScript use:
selectedOption.getAttribute("data-start-date");
With jQuery use data():
$("#ddl").on('change', function () {
var selectedOption = this.options[this.selectedIndex];
alert($(selectedOption).data("start-date"));
});
DEMO.
DEMO (jQuery).
Are you using jQuery? If so, you may want to use the built-in data module.
If not, use data tags. I suggest putting all the data in one data tag.
i.e.
data="searchPurpose: thing, searchTime: sometime"
and separating it like this:
function data(elem) {
var data = {};
var a = elem.getAttribute('data').split(',');
var i = 0;
while(i < a.length){
data[a[i].split(':')[0]] = a[i].split(':')[1];
i++;
}
return data;
}
So:
data() returns an object literal like this: { searchPurpose: 'thing', searchTime: 'sometime' }
There's a lot of ways to associate data with the option tags. Some ideas off of the top of my head:
Use hidden inputs: <option id="option1">Option 1</option><input type="hidden" id="option1data" value="option1 data here" />
Use data- attributes (not supported by all browsers): <option id="option1" data-searchPurpose="searchPurpose">Option 1</option>
If you're using jQuery, you can use its .data() method: $('#option1').data('searchPurpose', 'data...');
As far as accessing the data, it depends on what you're doing with your dropdowns. If they're being submitted in a form, you could use some onSubmit JavaScript to a) return false and then b) submit the form using post or get with the extra data appended.
(In the case of the hidden input solution, this JavaScript intervention would not be necessary.)
Otherwise it should be very simple using Javascript to access/modify the data.

How to capture the text of an Select option?

So I have this:
<select id="list">
<option value="1">This is Me</option>
<option value="2">This is You</option>
<option value="3">And this is Mr. Nukem</option>
</select>
How would I go about grabbing the 'text' of the options here? The problem is, it needs to be 'dynamic', in the sense I need the text for the currently selected option...
I know a manual, static way of getting the text...
document.getElementById('list').options[1].text
That will grab "This is You"... But how do I get it for the currently selected option? Since I can't simply use:
document.getElementById('list').value
As that will grab the number... :-(
var list = document.getElementById('list');
var text = list.options[list.selectedIndex].text;
See (for example) here https://developer.mozilla.org/en/DOM/HTMLSelectElement
If you can use jQuery, you can try something like this:
$("#list").change(function() {
alert($(this).find("option[value=" + $(this).val() + "]").text());
});
See http://jsfiddle.net/MWu9f/ for a working example.
$("#list option[value='2']").text()
You can use this jQuery line and it will solve your problem.
In this an element with id list which has a property value equal to 2. What you want is the option child of the list.
The jQuery solution is like this:
$("#list option:selected").text()

Categories

Resources