Selecting Chosen options through javascript functions - javascript

I've been trying to implement a solution proposed in How do you select a particular option in a SELECT element in jQuery? to no avail. Either the addition of Chosen to the mix makes the solution invalid, or I've made some coding error that is beyond my compiler and me to find.
My html:
<select name="superType" class="chosen-select chosen-select-creation-allowed" id="superType" style="width: 300px; display: none;" onchange="loadInheritance()" multiple="">
<option style="padding-left:20px;" value=""></option><option style="padding-left:0px" value="28">concept</option>
<option style="padding-left:20px" value="30">human</option>
</select>
When I place the following after this, I expect one of them will add to the value="30" option above a 'selected' attribute:
//$('#superType option[value="30"]').prop('selected', true);
$('#superType option[value="30"]').attr('selected', 'selected');
$('.chosen-select').trigger("chosen:updated");
Instead, nothing happens as according to the DOM model inspector and visual presentation.
What I want is to have this selection happen inside a function, but when I try to build the reference to the option above I get the error:
Syntax error, unrecognized expression: '#superType option[value="30"]'
Here is the javascript generating that (procs on 'cid'):
//now go back through and select the ones this CommonNoun already had from before
$.ajax({
url: '/BackToTech/server?function=getExistingSuperTypes',
type: 'POST',
success: function (response){
// var target = $("#superType");
var target = "#superType";
selectOptions(response, target, 0);
$('.chosen-select').trigger("chosen:updated");
}
});
...
function selectOptions(obj, target) {
var concepts = obj;
$.each(concepts, function(concept, value) {
alert(concept, value);
if (concept == "cid") {
optionValue = obj[concept].oid;
$("'" + target + " option[value=\"" + optionValue + "\"]'").attr('selected', 'selected');
} else {
selectOptions(value, target);
}
});
}

You don't need the single quotes around the css selector.
$(`${target} option[value="${optionValue}"]`).attr('selected', 'selected');

Related

Get value from dynamically created droplist

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

Build URL link from Custom Options using JS logic

Thank you in advance.
I am still learning JavaScript and as a project approached, really need some help/insight.
The logic that I am working on is this:
1. HTML structure:
<input title="Type Here" class="search" type="text" placeholder="Type Here">
<select id="device_select">
<option id=one value='a'>a</option>
<option id=two value='b'>b</option>
<option id=three value='c'>c</option>
<option id=many value='many'>many</option>
</select>
<span class="content-btn-1" type="button"></span>
2. JS structure:
$(function(){
var one = {title:"titletext", description:"descrtext", keyword:"text",
subject:"533,567,457", provider:"c9drlt-sdgtrzz", training:"true"};
var two = {title:"titletext", description:"descrtext", keyword:"textthis",
subject:"537", provider:"c9drlt-sdgtrjt", training:"false"};
});
3. JS logic structure:
function search_class() {
if (training == true) {training = "&tr=0";} else {training = "";}
return training;
}
function search_custom() {
// NOT SURE HOW TO PULL IT UP
// if subject has more than 1 variable like subject:"533,567,457"
// then construct the logic to separate them:
// &s=533&s=2&567&s=3&457
return subject;
}
var url = "www.website.com";
var text_area = $('.search');
var btn_click = $('.content-btn-1');
btn_click.click (function () {
var value = text_area.val();
var ty = "#s=";
if ($.trim($(text_area).val())) {
window.location.href = url+ty+search_class()+search_custom();
}
});
4. The outcome:
www.website.com#s=titletext&d=descrtext&t=text&p=c9drlt-sdgtrzz&tr=0&s=533&s=2&567&s=3&457
5. The hard part:
How can we do the logic so it takes that array in #2, attaches to the option id one, two ... etc in #1 and then constructs the link in #3 on click?
In nutshell: This is a search function with options that has unique variables.
Appreciate any help!
First off, I think you want to clean up your select box a bit, and give it values you can actually use in javascript.
<input title="Type Here" id="search_text" type="text" placeholder="Type Here" />
<select id="device_select">
<option value='1'>a</option>
<option value='2'>b</option>
<option value='3'>c</option>
<option value='0'>many</option>
</select>
<input id="submit_button" type="button" />
Then we need to clean up your object a bit so it's a) more readable, and b) it links to your select box nicely. If we nest it into one object, referencing it later will be easier.
// we would like an array that corresponds with our values in the select box.
var options = [
false,
{
title: "titletext",
description: "descrtext",
keyword: "text",
subject: "533,567,457",
provider: "c9drlt-sdgtrzz",
// a boolean like "false" or "true" should not be surrounded by braces, is easier to manipulate.
training: true
},{
title: "titletext",
description: "descrtext",
keyword: "textthis",
subject: "537",
provider: "c9drlt-sdgtrjt",
training: false
}
];
The final bit is in the logic. I've tried to streamline it a bit but the most important change is the for-loop in this case, as it will list every key/value pair and then we can add it to our search string. I Have also included some error dodging here, like checking if theres empty values and if the selected values actually exist (for example, if you select 3 in device_options, we don't have that index in our options array above, so we can't actually construct that - but it won't actually error out.)
$("#submit_button").on("click", function(event){
// now for the hard part, converting your select item into a string and appending the text
// 1. get the search string from the input
var searchstring = "#searchText=" + $("#search_text").val().trim();
// 2. get the select box value of the selected option
var selected = $("#device_select").val();
// 3. Get the corresponding value.
// If the corresponding value is false (remember the first item in the array above?), then we do nothing.
// We also do nothing if we are looking for an undefined number in the array (say, item #238)
selected = typeof options[selected] != "undefined" && options[selected] !== false
? options[selected]
: false;
// if selected was not set to false, then it exists in our options and we can use it.
if(selected){
for(key in selected){
// if you set a value in options to false, we'll ignore it here using a 'continue'
// continue will move on to the next iteration of the for loop immediately
if(!selected[key]) continue;
searchstring += "&" + key + "=" + selected[key];
}
window.location.href = "http://www.mysite.tld/" + searchstring;
} else {
// log an error here.
if(console) console.log("Could not find device!");
}
});
Does this make sense/help? I have not tested this myself, but it should all work.

Adding options to a select box dynamically

I am trying to add options to select element using javascript dynamically for a university assignment.
We are creating a class booking system for a gym so users can book into a class. I wanted to use drop down boxes, so you select the class, then the time using the next drop down box, so it has to change depending on the class selected. Finally, the user would select the personal trainer in the last box, once again created depending on what timeslot is selected.
This is what I have so far (javascript side):
<script type="text/javascript">
function getTimes()
{
var index=document.getElementById("classes").selectedIndex;
var x=document.getElementById("schedule");
if(index==0)
{
document.getElementById("schedule").value=" ";
}
else if(index==1)
{
var option=document.createElement("option");
option.text="Monday 8:00pm";
try
{
// for IE earlier than version 8- from w3 schools
x.add(option,x.options[null]);
}
catch (e)
{
x.add(option,null);
}
}
}
and html:
<div>
<span class="label">Class:</span>
<select class="dropdown" id="classes" name="classes" onChange="getTimes();">
<option value="none"> </option>
<option value="pilates">Pilates</option>
<option value="crossfit">Cross Fit</option>
</select>
</div>
<div>
<span class="label">Time:</span>
<select class="dropdown" id="schedule"></select>
</div>
<div>
<span class="label">Trainer:</span>
<select class="dropdown" id="trainer"></select>
</div>
To the code seems like it should work, but for whatever reason when I select the first class, in this case "Pilates" the "Time" drop down box is still blank.
Can anyone tell me where I am going wrong?
The error is in the first line of the function
function getTimes();
^------ You have a semi colon here
which is not supposed to be there
Also is a better idea to cache your selectors if you are referencing the same element again.
Bind the events using Javascript instead of binding them inline.
// Store you selectors so that you can use later
// This will improve your performance
var classDropdown = document.getElementById("classes"),
scheduleDropdown = document.getElementById("schedule");
// Abbd events using javascript
classDropdown.addEventListener('change', getTimes);
function getTimes() {
var index = classDropdown.selectedIndex;
if (index == 0) {
scheduleDropdown.value = " ";
} else if(index == 1) {
var option = document.createElement("option");
option.text = "Monday 8:00pm";
try {
// for IE earlier than version 8- from w3 schools
scheduleDropdown.add(option, x.options[null]);
} catch (e) {
scheduleDropdown.add(option, null);
}
}
}
Check Demo

get the id of the previous field in javascript

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

jquery empty() preventing select

A while ago I posted this question asking how to get JSON data into jQuery dropdowns
jquery dropdown from mysql based on previous selection
Well the people here were awesome and I got a solution. The problem I'm having now is that the suggest solution dosen't work in my production enviorment but it does in my test.
In order to prevent duplicate entrees I am using jQuery empty() the problem is that using empty() seems to also be preventing me from selecting the first option.
this is the function that is generating the optiosn from JSON
function(data){
var select = $('[name="employee_manager"]');
select.empty();
select.append(new Option(ucfirst('No Manager'),'100'));
$.each(data, function(index, array) {
select.append(new Option(ucfirst(array['first_name'])+ " "+ucfirst(array['last_name']),array['id']));
});
Is that an alternative to empty() that won't prevent selection?
EDIT This seems to only be a problem if there are fewer than two items being dynamically input
EDIT 2 Here is the HTML. It seems that I can't select the first option if empty() is present
<label for="manager">Reports To</label>
<select name="employee_manager">
<option value="1">Please Select Employee Role</option>
<option value="2">John Doe</option>
<option value="3">James Smith</option>
</select>
EDIT 3
Looks like the empty class is adding a span to my select
<div class="selector">
<span style="-moz-user-select: none;">Jane Smith</span>
<select name="employee_manager" style="opacity: 0;">
<option value="100">No Manager</option>
</select>
</div>
EDIT 4
Okay so here is a jsfiddle that shows the problem. I couldn't get the JSON data to load correctly but you can still see the problem if you attempt to click on the first item in the list. It seems that it's a problem with uniformjs as if uniform is removed it's not a problem
http://jsfiddle.net/BandonRandon/xXUfp/1/
Don't use empty() to clear the options of drop down list. It's wrong, because it should be used to remove DOM children.
Instead use such code:
$("select[name='employee_manager'] > option").remove();
Edit: when using the jQuery uniform plugin, dynamically adding options is messing things up... one way around that does not require to go and try fix the plugin is to always have enough "dummy" options in place (e.g. 20 if that's the max amount of options) then change the text/value of those options and hide all others according to your data.
The proper JS code will now look like this:
var myData = [];
myData.push( { text: "Please Select A Manager (JS)", value: "null" } );
myData.push( { text: "No Manager", value: "100" } );
myData.push( { text: ucfirst("a third choice"), value: "42" } );
$.each(data, function(index, array) {
myData.push( { text: ucfirst(array['first_name'])+ " " + ucfirst(array['last_name']), value: array['id'] } );
});
$("select[name='employee_manager'] > option").each(function(index) {
if (index < myData.length) {
$(this).text(myData[index]["text"]);
$(this).val(myData[index]["value"]);
$(this).show();
}
else {
$(this).hide();
}
});
Updated jsFiddle.
Crude, but working.... :)
Well try something like this, but no guaranteed
$('<option></option>').val(100).html('No Manager').appendTo($(select));
$.each(data, function(index, array) {
$('<option></option>').val(array['id']).html(ucfirst(array['first_name'])+ " "+ucfirst(array['last_name']).appendTo($(select));
});

Categories