Keeping key value pairs together in HTML <select/> with jQuery? - javascript

Given a select with multiple option's in jQuery.
$select = $("<select></select>");
$select.append("<option>Jason</option>") //Key = 1
.append("<option>John</option>") //Key = 32
.append("<option>Paul</option>") //Key = 423
How should the key be stored and retrieved?
The ID may be an OK place but would not be guaranteed unique if I had multiple select's sharing values (and other scenarios).
Thanks
and in the spirit of TMTOWTDI.
$option = $("<option></option>");
$select = $("<select></select>");
$select.addOption = function(value,text){
$(this).append($("<option/>").val(value).text(text));
};
$select.append($option.val(1).text("Jason").clone())
.append("<option value=32>John</option>")
.append($("<option/>").val(423).text("Paul"))
.addOption("321","Lenny");

Like lucas said the value attribute is what you need. Using your code it would look something like this ( I added an id attribute to the select to make it fit ):
$select = $('<select id="mySelect"></select>');
$select.append('<option value="1">Jason</option>') //Key = 1
.append('<option value="32">John</option>') //Key = 32
.append('<option value="423">Paul</option>') //Key = 423
jQuery lets you get the value using the val() method. Using it on the select tag you get the current selected option's value.
$( '#mySelect' ).val(); //Gets the value for the current selected option
$( '#mySelect > option' ).each( function( index, option ) {
option.val(); //The value for each individual option
} );
Just in case, the .each method loops throught every element the query matched.

The HTML <option> tag has an attribute called "value", where you can store your key.
e.g.:
<option value=1>Jason</option>
I don't know how this will play with jQuery (I don't use it), but I hope this is helpful nonetheless.

If you are using HTML5, you can use a custom data attribute. It would look like this:
$select = $("<select></select>");
$select.append("<option data-key=\"1\">Jason</option>") //Key = 1
.append("<option data-key=\"32\">John</option>") //Key = 32
.append("<option data-key=\"423\">Paul</option>") //Key = 423
Then to get the selected key you could do:
var key = $('select option:selected').attr('data-key');
Or if you are using XHTML, then you can create a custom namespace.
Since you say the keys can repeat, using the value attribute is probably not an option since then you wouldn't be able to tell which of the different options with the same value was selected on the form post.

Related

datalist get selected value and custom attribute (without events)

I have a datalist with options and a custom attribute.
<input list="selectedItems" class="selectedItemsList"></input>
<datalist id="selectedItems">
<option value="test11" oldvalue="f1"></option>
<option value="test12" oldvalue="f2"></option>
</datalist>
It is displayed on a popup. When a popup closes the value and custom attribute value must be used in a function...
I tried:
alert($("#selectedItems option:selected").val());
alert($("#selectedItems option:selected").attr("oldvalue"));
$('.selectedItemsList option').each(function() {
if($(this).is(':selected')){
alert($(this).val());
}
});
for (var i=0; i<document.getElementById('selectedItemsList').options.length; i++)
{
if (document.getElementById('selectedItemsList').options[i].value == document.getElementsByName("selectedItems")[0].value)
{
alert(document.getElementById('selectedItemsList').options[i].value);
break;
}
}
Nothing works.
I can get the values using on-event but that is not an option for me.
$('.selectedItemsList').on('input', function() { ...
alert($(this).val());
$(function(){$("input[name=selectedItems]").on('input', function(){// selects which array raw is edited
for (var i=0; i<dList.length; i++) if(dList[i].ItemName===$(this).val()) { num = i;
$(".selectedItems option[value="+dList[num].ItemName+"]").val($(this).val());
dList[num].ItemName=$(this).val();
});
});
So, I use datalist oninput event to get the selected value. Then, I edit a raw of an array of values that represents the datalist values.
var dList=[];num=0;
dList.push({ItemName: $(this).attr('value'), ViV: vs[0], NU: vs[1], ItemKey: $(this).attr('key')});
Essentially, I believe the problem is related to your selector use. I'm making the assumption that you're trying to get the old value from the datalist. On closing your popup, you should get the value of the input first
var inputval= $(".selectedItemsList").val();
alert(inputval);
then grab the associated oldvalue based on the value of the input.
var oldval= $('datalist#selectedDevices option[value='+inputval+']').attr('oldvalue');
if (oldval)
alert(oldval);
I created a jsfiddle for you here to play around with.
http://jsfiddle.net/jornjjt6/

html select list - get text value by passing in a variable?

I have a select list that displays a list languages.
<select name="language_code" id="id_language_code">
<option value="ar">Arabic - العربية</option>
<option value="bg">Bulgarian - Български</option>
<option value="zh-CN">Chinese (Simplified) - 中文 (简体)‎</option>
<option value="en" selected="selected">English (US)</option>
<option value="fr-CA">French (Canada) - français (Canada)‎</option>
</select>
I am able to get the text value of the selected value using the following code [returns English (US) from the above select list]:
$('#id_language_code option:selected').text()
How can I get the text value if I pass the option value of 'bg' as a variable when the selected value is still English (US)?
This means that the value returned would be "Bulgarian - Български" when the selected value is still "English (US)".
I have searched Google and SO for an answer, but was unable to find one, so I am thinking that this is not as easy as I 1st thought it was!
Here is an example of how you can use CSS selectors to query the value attribute:
function getOptionTextByValue(value) {
return $('#id_language_code option[value=' + value + ']').text();
}
var bgText = getOptionTextByValue('bg');
Here is a working example
http://plnkr.co/edit/SQ48SmoQkSUgDpQ5BNAx?p=preview
You have some data, and you have the view of this data (html/dom), but it's best if you go data -> view, rather than view -> data.
For example, say you have this array:
var languages = [
{short: "ar", text: "Arabic - العربية"},
{short: "bg", text: "Bulgarian - Български"},
{short: "en", value: "English (US)"}
];
Now you can look things up, for example, "what is the text for the abbreviation 'bg'?"
languages.filter(function(x){ return x.short === 'bg' })[0].text;
Or create DOM nodes from it:
function option(x){
var el = document.createElement('option');
el.value = x.short; el.textContent = el.text;
return el;
}
function select(options){
var el = document.createElement('select');
options.forEach(function(x){ el.appendChild(x); });
return el;
}
var element = select(languages.map(option));
element.id = 'id_language_code';
Hmm, if I understand correctly, you want to retrieve the label associated with a given value of one of the options of the <select> element, which will not necessarily be the currently selected option. Using pure JavaScript approach (aka. No jQuery, since there's already a nice one provided by someone else):
function getOptionLabel(selectId, optionValue){
// Get select element and all options
var sel = document.getElementById(selectId);
var selOpts = sel.options;
// Cycle through each option to compare its value to the desired one
for(var i = 0; i < selOpts.length; i++){
if (selOpts[i].value == optionValue){
return selOpts[i].label;
}
}
// Default return value
return "Option not found.";
}
To get the Bulgarian option from a <select> of the given id, you could call it like so:
getSelectLabel("id_language_code", "bg");
Here's a JSFiddle to demonstrate. Hope this helps! Let me know if you have any questions.

jQuery get actual data-id from selector

I have a selector on webpage with data-id and value
HTML
<select id="s1">
<option data-id="01">aaaa1</option>
<option data-id="23">bbb1</option>
<option data-id="451">ccc1</option>
<option data-id="56">ddd1</option>
</select>
<p></p>
JAVASCRIPT
$('#s1').change(function() {
var val = $(this).val();
var val_id =$(this).find('option').data('id');
$("p").html("value = " + val + "<br>" +"value-data-id = "+ val_id);
});
I wanna have actual value from selected selector and his data-id. I do not understand why I have data-id from only first option. This is my code http://jsfiddle.net/s55rR/
Please help me to find a bug.
You can do $(this).find('option:selected').data('id').
You've selected multiple elements ($(this).find('option')) but .data() only returns the value from the first element if called on a jQuery with length >1:
Description: Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute.
If you only want the data-id value from the user-selected<option>, then you need to select only that element.
Because you selecting all options, and jQuery returning .data('id') of first one
var val_id =$(this).find('option:selected').data('id');
fiddle

form element index in javascript for use in jquery .change function

I need to get an index of a form element that is passed in to a .change statement.
example HTML form code
<tr><td>Question1</td><td><select class=list1 id=l[1] name=l[1]><option value=1>1<option value=2> 2 <option value=3> 3 </select></td><td><select class=hideme name=x[1] id=x[1]></select></td></tr>
<tr><td>Question2</td><td><select class=list1 id=l[1] name=l[2]><option value=1>1<option value=2> 2 <option value=3> 3 </select></td><td><select class=hideme name=x[2] id=x[2]></select></td></tr>
<tr><td>Question3</td><td><select class=list1 id=l[3] name=l[3]><option value=1>1<option value=2> 2 <option value=3> 3 </select></td><td><select class=hideme name=x[3] id=x[3]></select></td></tr>
Now the user will select 1, 2 or 3 from the first pulldown. based on that selection the second pulldown will be loaded with content.
example javascipt jquery function
$('.list1').change (function ()
{
// here is where I need to pick up the index ie: the [1] [2] or [3] as var id
var selected = $("#l[id] option:selected");
var pdata = 'subjectareaid='+selected.val();
$.ajax({
type : "POST",
cache : false,
url : "subcat.php",
data : pdata,
success: function(data) {
$('#x[id]').html(data);
$('#x[id]').removeClass('hideme');
}
});
});
This will allow me to populate the second pulldown with the options that were returned by the ajax call based on the selection from the first pulldown.
The table has 54 pulldowns that all have to have this action taken against them (this is to populate a mysql table upon form submission) the pulldowns are (l[id]) primary category (x[id]) sub-category. The subcat selection is hidden until after the main cat is picked and then the select statement is populated.
First of all add double qoutes arround your attributes ", this is best practice and will prevent errors if you use spaces in your values. Also make sure your html is valid. You didn't close the <option> tags with a </option>.
You can use a simple regex to get the index of your select element.
$('.list1').change (function () {
var id = $(this).attr('id');
var matches = id.match(/^l\[([0-9]{1,})\]/);
if (matches) {
var index = matches[1];
}
});
You can get the select element changed at the moment with $(this) instead of var selected = $("#l[id] option:selected");
You can reach the index of the changing select by reaching index of parent tr element of that select element by using closest() selector of jQuery.
Finally the code block you need, should be like that:
var selected = $(this);
var selectedIndex = selected.closest("tr").index();
var pdata = 'subjectareaid='+selected.val()+"&index="+selectedIndex;

Populate Select With OptGroup From Two Seperate JSon Objects JQuery

I have two json objects
var type = [{"Id":1,"Name":"This is a name"}];
var subType = [{"Id":2,"ParentId":1,"Name":"This is a name"},];
subType.ParentId references the type.Id
I want to be able to populate a select in jQuery having
<SELECT>
<OPTGROUP LABEL="type.Name" id="type.Id">
<OPTION LABEL="subType.Name" value="subType.Id">subType.Name</OPTION>
</OPTGROUP>
</SELECT>
The code below uses just "select" as a jquery selector, so it will affect all selectboxes on the page.
You probably want to change this.
The code below also does not handle having one of the options selected which is probably something you should watch out for.
var type = [{"Id":1,"Name":"This is a name"}];
var subType = [{"Id":2,"ParentId":1,"Name":"This is a name"}];
var output = [];
$.each(type, function(){
//for each type add an optgroup
output.push('<optgroup label="'+this.Name+'">');
var curId = this.Id;
//linear search subTypes array for matching ParentId
$.each(subType, function(k,v){
if( this.ParentId = curId ){
output.push('<option label="'+this.Name +'" value="'+ this.Id +'">'+ this.Name +'</option>');
//DELETE the element from subType array so the next search takes less time
subType.splice(k,1);
}
});
output.push('</optgroup>');
});
//change the 'select' here to the id of your selectbox
$('select').html(output.join(''));
Adding optgroups to select using javascript dynamically
You able criate dinamamicaly the combo. Access The values of json is In this question.
How to access Json Object which has space in its name?
Have some situations in posts to resolve your question.

Categories