I'm trying to create a string variable to append on a multiselect with jquery.
This is the fiddle example: https://jsfiddle.net/o2gxgz9r/47084/
$(document).ready(function() {
var group = "<optgroup></optgroup>";
$(group).attr("value", 1);
$(group).attr("label", "test group");
var t = "<option></option>";
$(t).attr("value", 4);
$(t).text("Test option");
$(t).attr("selected", true);
$(group).append(t);
$("#a").html(group);
});
body {
padding: 5px;
}
label {
font-weight: bold;
}
input[type=text] {
width: 20em
}
p {
margin: 1em 0 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
RESULT TEST PURPOSE:
<br><br>
EXPECTED:
<br>
<textarea rows="5" cols="72">
<optgroup value="1" label="test group">
<option value="4" selected>Test option</option>
</optgroup>"
</textarea>
<br><br>
GET:
<br>
<label id="a"></label>
Next step is to append the string created dinamically in a select with
$("#select").append(group);
But the string is not created...it result empty
There's a few issues here. Firstly you're attempting to append an optgroup element to a label. This is impossible as optgroup can only be children of select elements.
Secondly, optgroup elements do not have a value attribute.
Finally, you're repeatedly creating new jQuery objects for group and t, which means that all previous amendments are lost. To fix this create the jQuery objects once and store them in variables which you can then reference whenever you want to make a change. Try this:
$(document).ready(function() {
var $group = $('<optgroup></optgroup>');
$group.prop("label", "test group");
var $t = $('<option></option>');
$t.val(4);
$t.prop("selected", true);
$t.text("Test option");
$group.append($t);
$("#a").html($group);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<select id="a"></select>
Note the use of val() to set the value attribute, and the use of prop() over attr() where possible.
There are several issues:
var group = "<optgroup></optgroup>";
$(group).attr("value", 1);
You are referring to the JQuery element incorrectly. What goes inside $() needs to be a string representing an element, a class, or an id. So if you want to change all existing optgroups, it should look like this:
var group = "optgroup";
$(group).attr("value", 1);
However, based on the rest of your code that doesn't seem to be your intention. If you are wanting to create a new optgroup, then you'll need to reference an element already in the DOM to add it to (i.e. your #select).
Second, your optgroup element cannot have a value, that is invalid HTML. An optgroup is a non-selectable "label" that helps break up options in a dropdown.
Third, you are creating your <option> element incorrectly. As mentioned before, you can't create a JQuery element with a string of an open/close for an element. You'd be better off doing something like this:
var t = "<option value='4' selected='selected'>Test option</option>";
$(group).append(t);
So your code should actually look something like this:
var group = "<optgroup label='test group'>";
group += "<option value='4' selected='selected'>Test option</option>";
group += "</optgroup>";
$("#select").append(group);
If you have at least JQuery 1.8, you can change it to this:
var group = $( "<optgroup/>", { "label" : "test group"});
var option = $( "<option/>", { text : "Test option", "value" : 4, "selected" : "selected" });
group.appendTo( "#select" );
option.appendTo(group);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<select id="select"></select>
Related
I my code I create droplists and hidden field for each of them to be able to catch selected value in code behind. I do have a problem set hidden value to the value of selected item in droplist probably because I am not able to create correct selector.
Name of my droplist are dropTypeXXY where XX stands for two alphanumeric characters and Y stands for number for example.
dropTypeU19, dropTypeBB22, dropTypeAG71
hidden fields for them are hdnY where Y stands for number
hdn9, hdn22, hdn71
In both cases these values are IDs of given html elements.
My question is how can I assign list item value to hidden field when droplist selection is changed.
My jQuery
$(document).ready(function(){
$("select[id^='dropType']").on("change",function () {
alert("HI"); //Just to test the selector itself.
});
});
Edit:
My problem is that the selector is not working and alert is not even called. Whey I try to apply similar approach to droplist that I create in code behind it works but not for droplists created by jQuery.
var list = $("<select id = dropType" + response.d[i].TypeId+ i + "/>");
var valueField = $("<input type='hidden' id = 'hdn" + i + "' name ='hdn" + i + "' value=-1 />");
...
$("#<%=grdUsers.ClientID%>").after(list, valueField);
I create them based on AJAX call. I am able to display them in console and display them to user and even give them items but I am not able to run .change() event on them.
Sorry I did not mentioned it earlier.
This doesn't work for them as well. Is there a problem with html tags that are not part of DOM from the beginning of page life?
$("select").on("change", function () {
alert("hi");
});
Edit 2
I looks like my answer lies here. It actually works and alert is raised. Thank you very much guys I'll try to implement the data-target and class trick.
With Dynamically created controls it is easier to select them by class since you cannot use ClientID. Go give them a unique CssClass in code behind when creating the Control.
DropDownList ddl = new DropDownList();
ddl.Items.Insert(0, new ListItem("Value A", "0", true));
ddl.Items.Insert(1, new ListItem("Value B", "1", true));
ddl.CssClass = "DynamicDropDown";
Panel1.Controls.Add(ddl);
Now you can select them with jQuery like this
$(document).ready(function () {
$(".DynamicDropDown").on("change", function () {
alert("HI");
});
})
You can use a class selector ("select" for example) (instead of an id) and add an attribute data-target in your html that say which hidden field is linked to this droplist.
And your js can be something like :
$(document).ready(function(){
$("select.select").on("change",function () {
var $target = $($(this).attr("data-target"));
$target.val($(this).val());
});
});
Or you can also use DOM navigation to find the hidden field without any id if you know the structure of your code and if it's always the same.
Pseudo html code :
<div>
<select>...</select>
<input type="hidden">
</div>
jQuery :
$(document).ready(function(){
$("select").on("change",function () {
var val = $(this).val();
$(this).parent().find("input").val(val);
});
});
You can do it by adding class to a name you specify.
<select id="dropTypeU19" class="cls-name">
<option value="a">a</option>
<option value="a1">a</option>
</select>
<select id="dropTypeBB22" class="cls-name">
<option value="b">a</option>
<option value="b1">a</option>
</select>
<select id="dropTypeAG71" class="cls-name">
<option value="c">a</option>
<option value="c1">a</option>
</select>
<input type="hidden" id="hdn19" />
<input type="hidden" id="hdn22" />
<input type="hidden" id="hdn71" />
<script>
$(function () {
$("select.cls-name").change(function () {
var selectId = $(this).attr("id");
var selectValue = $(this).val();
var hiddenId = "#hdn" + selectId.slice(-2);
$(hiddenId).val(selectValue);
alert($(hiddenId).val());
});
});
</script>
OR:
$("select[id^='dropType']").change(function () {
var selectId = $(this).attr("id");
var selectValue = $(this).val();
var hiddenId = "#hdn" + selectId.slice(-2);
$(hiddenId).val(selectValue);
alert($(hiddenId).val());
});
I have 2 dropdowns and one of them(the second one) is dynamic in the sense that its values change according to the option chosen in the first dropdown.
JSFiddle result: http://jsfiddle.net/pgbw56vb/10/embedded/result/
Can someone pls show me how i can make the second dropdown a multi-select? I'm really green in Jquery and html.
JSFiddle: http://jsfiddle.net/pgbw56vb/10/
<select id="kategorie_oder_seite"></select>
<select id="auswahl"></select>
var data = {
"Kategorie": ["Kraft", "Startseite", "Insurance", "Risk",],
"Seite": ["http://jsfiddle.net/tony089/pgbw56vb/2/", "https://stackoverflow.com/users/login?returnurl=%2fquestions%2fask"],
};
var $kategorien = $("#kategorie_oder_seite").on("change", function() {
var seiten = $.map(data[this.value], function(seite) {
return $("<option />").text(seite);
});
$("#auswahl").empty().append(seiten);
});
for (var kategorie in data) {
$("<option />").text(kategorie).appendTo($kategorien);
}
$kategorien.change();
Thanks in advance.
you can use the multiple attribute of select tag and set its value to multiple. also remember to set the name property in array form so that you could send multiple values via this select control.
eg.
<select multiple="multiple" id="kategorie_oder_seite" name="check[]"></select>
JsFiddle: http://jsfiddle.net/pgbw56vb/10/
just add "multiple" attribute on the "select" tag
Add multiple to your select tags.
<select id="kategorie_oder_seite" multiple></select>
<select id="auswahl" multiple></select>
This is my jspPage.
<select id="class_Teacher" name="classTeacher" style="height:25px; width: 190px;" onchange="Class(this.id)">
<option id="1">Manager</option>
<option id="2">Supervisor</option>
</select>
And here is javascript
function Class(str)
{
alert(str);
}
i want to get the id of Option on onchange Event. Thanks :)
You can do this if you are trying to get the id of the option which has been selected
function Class(str)
{
var select = document.getElementById("class_Teacher");
var option = select.options[select.selectedIndex];
alert(option.id);
}
Your onchange event will look like this. Just remove the .id as that will return the id of the select box itself not the option
onchange="myFunction(this)"
and your javascript function like this, which will alert the ID of the selected option
function myFunction(ele){
alert(ele.options[ele.selectedIndex].id);
}
Broken down ele represents the select box (a dom object). .options accesses the options within the select box. the [] brackets are a way of accessing a specific option. Like an array myArr[1] etc. and ele.selectedIndex returns a number representing the selected option i.e if the first option is chosen - ele.selectedIndex will be equivalent to 0.
HTML (you should use "value" attribute instead of "id")
<select id="class_Teacher" name="classTeacher" style="height:25px; width: 190px;" onchange="onChange()">
<option id="1" value="ID1">Manager</option>
<option id="2" value="ID2">Supervisor</option>
</select>
JS
var selectElement = document.getElementById("class_Teacher");
selectElement.onchange=function(){
alert(selectElement.options[selectElement.selectedIndex].id); // id in the html element
alert(selectElement.selectedIndex); // index starting from 0
alert(selectElement.value); // value of the selected element
};
Fiddle
Use selsectedIndex Property of GetElementByID
<script>
function val() {
d = document.getElementById("select_id").selectedIndex;
alert(d);
}
</script>
<select onchange="val()" id="select_id">
Here is the code:
$('#date').append(
'<select id="date">'+
'<option value="0">- - SELECT - -</option>');
for(var i in data){
$('#date').append(
'<option value="">'+data[i]['date_time']+'</option>');
});
$('#date').append('</select>');
</select> is always added above for loop. If i replace it with just work select for example, it is appended at the end, where it should be. Why is this happening and how can i fix it?
I believe that jQuery will generate the DOM like this:
<div id="date">
<select id="date">
<option value="0">- - SELECT - -</option>
</select>
<option value="">foo</option>
<option value="">bar</option>
etc...
</div>
Since it is automatically closing the <select> after the first .append(). What you are doing afterwards is appending the options to the <div id="#date"/> rather than the <select> that was appended. I don't think the final closing </select> will actually do anything either.
If you really want to use append the following JavaScript will add the options to the correct node:
// dummy data object for example
var data = new Array(new Array(), new Array());
data[0].date_time = 2011;
data[1].date_time = 2012;
var options = new Array();
$.each(data, function(index, option) {
options.push('<option value="' + index + '">'+ option.date_time +'</option>');
});
$('<select id="date"/>').append(options.join('')).appendTo('#date');
Assuming the existing HTML:
<div id="date"></div>
However this does incur an overhead since appending is occurring twice. The faster approach is to build up the options markup as already answered by ShankarSangoli
It is not the right way to create html dynamically. You should create the complete markup all at once by putting it into an array and then provide it to jQuery. Try this
var html = [];
html.push('<select id="date">');
html.push('<option value="0">- - SELECT - -</option>');
for(var i in data){
html.push('<option value="">'+data[i]['date_time']+'</option>');
}
html.push('</select>');
//This selector should be some container like dateContainer
//because you have already give date as id to the above select element
$('#dateContainer').html(html.join(''));
$('#date').append($("<select/>", { name: "name"+i})
.find('select')
.append($("<option/>", { value: "abc"+i}).text('cell'))
.append($("<option/>", { value: "abc"+i}).text('home'))
.append($("<option/>", { value: "abc"+i}).text('work'));
all options should wrap inside select
I imagine the base HTML you have looks something like this:
<div id="date"></div>
then after the first $('#date').append('<select id="date">... in your code, you will have this:
<div id="date"><select id="date">...</div>
which is 2 elements with the same ID attribute.
The ID attribute is like the highlanders, there must only be one of them (in each page).
The seccond $('#date').append... works unexpectedly, and the 3rd one, also unexpectedly, doesn't work. Because you can't predict to which #date they are referring.
Also, as the other answers say, it will be better if you build it to do only 1 append, because calling the selectors so many times (especially inside the loop) it's a performance hit.
If you want to do it in your way - create, for example, string variable with html code in it and than append it.
data = [1, 2, 3];
var html = '<select id="date">'+
'<option value="0">- - SELECT - -</option>';
for(var i in data){
html += '<option value="">'+data[i]+'</option>';
}
$('#date').append(html)
or look here
What is the best way to add options to a select from an array with jQuery?
ps: the first append tries to create a valid DOM structure inside of document, closing select tag automatically. that is why the second one will not insert options into the created select.
another possible way, based on the link above, is
var sel = $('<select id="date">');
$.each(data, function(key, value) {
sel.append($('<option>').text(key['date_time']));
});
$('#date').append(sel);
<td>
<select name="ad_category" id = "ad_category" onchange="select_sub_cat(this.value)" >
<option value="#"></option>
<option value="jobs" id="jobs">Jobs</option>
<option value="sales" id="for_sale">For sale</option>
<option value="services" id="services">Services</option>
<option value="real_estate" id="real_e">Real estate/housing</option>
</select>
<span id="cat_help">Help</span>
</td>
IN the above code , in <a href=""> I want to pass the id or any information of the option selected , so that clicking on help will show only the help for the particular option . But my question is is it possible to get the id of the option selected ?
You should be using a button or some other element that doesn't suggest navigation. An inline handler might be:
<... onclick="alert(document.getElementById('ad_category').value);" ...>
More generally, once you have a reference to the select element:
var select = document.getElementById('ad_category');
you can access various properties defined by the HTMLSelectElement interface:
select.selectedIndex // index of selected option
select.options // collection of all options
select.options[select.selectedIndex] // the selected option (if there is one)
and so on.
Edit
You might also want to implement a more generic help system based on class values. Give your form controls a class depending on the help that should be shown. Then the help button can just get the previous form control, grab its class and show it.
e.g.
<style type="text/css">
.helpLink {
color: #CC00FF;
cursor: pointer;
}
</style>
<script type="text/javascript">
var showHelp = (function() {
var help = {
firstName: 'Enter your first name',
lastName: 'Enter your last name'
}
return function (el) {
var helpType;
var node;
do {
el = el.previousSibling;
} while (el && el.nodeType != 1)
if (el) {
helpType = el.className.match(/(^|\s)help-\w+/);
if (helpType) {
helpType = helpType[0].replace('help-','');
// Show help
alert(help[helpType]);
}
}
}
}());
</script>
<form name="form0" action="">
first name: <input type="text" class="help-firstName" name="firstName">
<span class="helpLink" onclick="showHelp(this)">?</span>
<br>
last name: <input type="text" class="help-lastName" name="lastName">
<span class="helpLink" onclick="showHelp(this)">?</span>
<br>
</form>
The above is just a trivial demo.
Yes, you can get the selected option's id:
//Place in event handler
var element = document.getElementById("ad_category");
element.options[element.selectedIndex].id
Related SO post.
If you are using jQuery, you can use the change() function on the selector, to let you know when the selector changes, and capture the ID of the selected item.
Once you have that, you can use jQuery's attr on the anchor to change the href.
Yes it is and you even have several options how to get the job done.
Since the select has an ID, you can get the value like this:
var select = document.getElementByID('ad_category'),
value = select.value;
alert(value);
But also, since the select is a sibling to the parent of the a element, you can also find it like this:
// This example is assuming quite a lot, so it's not really the best option and is
// provided merely for entertainment or trivia.
// Namely, this code requires that it is run in context of the a-element
// (means: 'this' refers to the 'a' -element)
// and also that the markup is exactly as in the example because of traversal.
var select = this.parentNode.previousElementSibling,
value = select.value;
alert(value);