I have two jquery selectors that I used which did not find the desired option where the third "brute force" method did. I am at a complete loss as to why. Each looked like they should of and I validated the document was fully loaded when the selector ran. I tried each with value and text in the selector and got the same result in my page. The html is dynamically loaded using the jquery load method below (where theType is a value coming from a html select control) as well as the associated javascript:
var theType = $('#TicketType option:selected').val();
var theId = $("#Id").val();
var url = '/SystemBuildSiteConfigs/' + theType + '/' + theId;
$('#ticketDiv').html("");
$("#ticketDiv").load(url, function (response, status, xhr) {
if (status == "error") {
alert("There was an error loading the " + theType + " form");
}
else {
$.getScript("/Scripts/SiteConfig" + theType + ".js", function () {
});
}
});
The html select in question:
<select name="SupportOrganization" class="form-control" id="SupportOrganization">
<option value="">- Please Select -</option>
<option>Auxiliary IT</option>
<option>Business Intelligence</option>
<option>Change Management</option>
<option>Engineering RnD</option>
<option>Enterprise Business Solutions</option>
<option>Enterprise Solutions</option>
<option selected="selected">Hosting</option>
<option>Infrastructure and Operations</option>
<option>Manufacturing</option>
<option>Professional</option>
<option>Support</option>
</select>
First selector statement:
$("#SupportOrganization").find('option[value="' + jsonObj.SupportOrganization + '"]').attr("selected", true);
Second selector statement:
$('#SupportOrganization option[value="' + jsonObj.SupportOrganization + '"]').attr("selected", true);
What worked:
$('#SupportOrganization option').each(function (idx, ele) {
if ($(ele).val() == jsonObj.SupportOrganization)
$(ele).attr("selected", true);
});
The page segment loads correctly and all the other javascript that fires to load html controls with content are executing as expected. Another page type loads and fires correctly performing similar functions. Using jsfiddle, both selectors show they work correctly. What I found through testing was
The variable did have the expected value.
The text selector did not work correctly on my page
The value selector did select an object. However I was unable to determine what the object was and the attr() method did not set the target attribute value.
I can go with what I found that will work, just wanted to find out why this wouldn't work. Guessing it has something to do with the dynamically loaded html and javascript?
The jQuery .val() function uses a "hook" for <option> elements to return the text content of the element if the "value" attribute is missing. Your <option> elements don't have "value" attributes, so the selector does not match.
You should select option by using the select .val(string) function, it will find the option with matched string if available in options having value attribute.
So, Your options should be containing the value attribute which is missing in your case e.g:
$(function(){
$("#userEducationDegree").val('A');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select type="text" class="form-control" placeholder="Degree..." id="userEducationDegree">
<option value="-1">--Select--</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
To continue with what #Pointy said above, you should try :contains instead.
$('#SupportOrganization option:contains("' + jsonObj.SupportOrganization + '")').attr("selected", true);
Related
Please find the jsfiddle
https://jsfiddle.net/qs008so7/
I have an option box in html and I am trying to set the option using jquery.
But its not working . Please find the code below.
If I call the code in console and I am able to see the expected html is getting returned. Means , the changes are properly affected int he DOM but it is not getting reflected in UI. . You can see my jfiddle .
HTML:
<select class="form-control" name="test" id="test">
<option value="0">Disabled</option>
<option value="1">Enabled</option>
</select>
JS:
setGivenOption(test,"Enabled");
setGivenOption(test,"Disabled");
function setGivenOption(elementId, option) {
//Make all the old selections to null
$(elementId).each(function () {
$('option', this).each(function () {
$(this).attr('selected', null);
});
});
//set the given option
$(elementId).find(">option:contains('" + option + "')").attr("selected", "selected");
}
Thanks.
You where almost there: Try like this https://jsfiddle.net/q5886d5o/1/
Update after #Chips_100 comment
setGivenOption("test","Disabled");
setGivenOption("test","Enabled");
function setGivenOption(elementId, option) {
//Make all the old selections to null
$('#' + elementId).children('option').each(function () {
$(this).attr('selected', null);
});
//set the given option
$('#' + elementId).children("option:contains('" + option + "')").attr("selected", "selected");
}
Simply
$(elementId).find('option:contains(' + option + ')').attr('selected', true);
That will diselect whatever that was selected and select the new option
I am using a select box to pull some data that is built into the site. However there are a few modules that run a script , and using the select option , that script is not firing when its selected. Do i have to run the full script within my option function , or can it be called to execute again when its selected.
Here is my script and html. Option Value "MESSAGE12" - needs a script to run when selected.
if(unescape(location.href).indexOf("http://football")!=-1||unescape(location.href).indexOf("http://6")!=-1) {
var currentServer=baseURLDynamic;
xmlBaseURL = baseURLDynamic + '/fflnetdynamic' + year + '/';
} else {
var currentServer=baseURLStatic;
}
function getHomePageModule(thisSelection) {
if(thisSelection=="")
document.getElementById("homePageModule").innerHTML = "Your selected module will appear here!";
else {
var url = currentServer + "/" + year + "/home/" + league_id + "?MODULE=" + thisSelection.toUpperCase();
$.get(url, function(data){
document.getElementById("homePageModule").innerHTML = $(data).find('#pageContent').html();
});
}
}
<select onchange="getHomePageModule(this.value)">
<option value="default">Select A Module</option>
<option value="MESSAGE12" >Get HPM#12</option>
<option value="LIVESCORING" >Link To Live Scoring</option>
<option value="LIVESCORING_SUMMARY" >Live Scoring Summary</option>
</select>
<div id="homePageModule">Your selected module will appear here!</div>
Here is a link to my demo select box - http://football29.myfantasyleague.com/2015/home/72758?MODULE=MESSAGE11
And a link to the MESSAGE12 content i'm wanting to fire up in the select box
http://football29.myfantasyleague.com/2015/home/72758?MODULE=MESSAGE12
Any advice appreciated
Instead of using innerHTML (which doesn't evaluate <scripts>), you could try using jQuery's .append() method.
Change:
document.getElementById("homePageModule").innerHTML = $(data).find('#pageContent').html();
to:
$("#homePageModule").append($(data).find('#pageContent').html());
(This also replaces the call to getElementById with a jQuery selector.)
If that doesn't work, you might need to take a look at the content returned by the call to $(data).find('#pageContent').html() and make sure your scripts are there, and/or move the scripts into a function that can be called after the .append() finishes.
I have an html select element, which includes three option elements. I have written a jquery code, which gives me the value of the title attribut from the current selected option element and saves that value in a variable (on the fly!).
But I would like to read a title attribute from an option value, which was not selected on the fly and which was already shown as selected value in my xhtml page, if the page was loaded as first.
This is my jQuery code and the second coderow doesn´t work correct:
$(document).ready(function(){
var optionElements = jQuery(jQuerySelektorHTMLSelectElement).children();
var OptionField = optionElements.find("[value=" + selectedValue + "]");
var OptionFieldTitleAttribut = OptionFeld.attr("title");
}
How can I find an option element, which was not selected on the fly but is selected, if the xhtml page was loaded?
If your variable jQuerySelektorHTMLSelectElement is well-named, you don't have to call children :
var selectElement = $(jQuerySelektorHTMLSelectElement); // <- remove children here
var OptionField = selectElement.find("[value=" + selectedValue + "]");
var OptionFieldTitleAttribut = OptionField.attr("title");
The find method already look for the selector in the children...
See this fiddle.
Try this:
html
<select id="test">
<option customAttr="a">test1</option>
<option customAttr="b">test2</option>
<option customAttr="c" selected="selected">test3</option>
<option customAttr="d">test4</option>
</select>
js
$(function(){
console.log($("#test").find("option:selected").attr("customAttr"));
});
fiddle
I actually have some questions but I will start with the main one. I want to set the value of Select box on the basis of JSON.
Here's the HTML in question,
<label class="lbl">Office: </label>
<select tab-index="6" class="required" name="office" class="off">
<option value="">---------</option>
<option value="U">London</option>
<option selected="selected" value="R">Delhi</option>
<option value="W">Lisbon</option>
</select>
JSON sends it like this, I can't show the full JSON since it's too big, but I will show a part, Location: "U".
Here's the JS part:
if (data.Office === "R") {
$('select option[value="Delhi"]').prop('selected', true);
}
if (data.Office === "U") {
console.log('here');
$('.off option[value="London"]').attr('selected', 'selected');
}
if (data.Office === "W") {
$('select option[value="Lisbon"]').prop('selected', true);
}
But it's not working? Can any one point out why?
Moreover, I have a list of managers say and I am also getting that in JSON. So I am doing this,
for (var i = 0; i < data.Managers.length; i++) {
find_input = $('input[name="project_manager[]"').length;
if (find_input != data.Managers.length) {
$('<input type="text" name="project_manager[]" class="" value="" />').appendTo('#managers');
}
console.log(data.Managers[i].Manager);
$('input[name="project_manager[]"').each(function() {
$(this).val(data.Managers[i].Manager);
});
}
No of textboxes depend on the number of managers, but it only sets the value of last item from the array of managers in text boxes that are appended. Why?
Moreover I am not able to set value of textarea in Firefox like this:
$('textarea#some_id').val(data.Description);
It works in Chrome though.
First you need to add the character "<" in the beginning of the 3rd option of the select box:
<option selected="selected" value="R">Delhi</option>
Now, in the JS code, your problem is that you're using the wrong value. Instead of:
$('select option[value="Lisbon"]').prop('selected', true);
You must use:
$('select option[value="W"]').prop('selected', true);
I hope it help.
I think your selectors should be of the form:
$('select option[value="R"]').prop('selected', true);
Note the value is the same as the value in the HTML, not the displayed string (i.e. 'R' instead of 'Delhi').
Also, you should be using prop() consistently for selected flag, as described here by John Resig.
So I am writing an app that requires an address input and I have a select element for the user to select the state/province. It needs to support the US and Canada so it has nested optgroups to separate those out and a single, first level option as it's default value. Here is a basic example:
<select name="state" id="state">
<option class="co" value="" data-placeholder="true" disabled selected>Choose your state...</option>
<optgroup label="United States">
<option class="co" value="AL">Alabama</option>
<option class="co" value="AK">Alaska</option>
<option class="co" value="AZ">Arizona</option>
</optgroup>
<optgroup label="Canada">
<option class="co" value="AB">Alberta</option>
<option class="co" value="BC">British Columbia</option>
<option class="co" value="MB">Manitoba</option>
</optgroup>
Now I need to programmatically select the option that matches input from an external source and I want to check for a match based on both the value of the option element or its text. Whichever option is a match would then be set as the selected option. I know you can set the selected option by value using
$("#state").val(myValue)
and I know you can set an option based on text in this way
var myText = "The state I want.";
$("#state").children().filter(function() {
return $(this).text() == myText;
}).prop('selected', true);
Is there a clean way to do this without having to run through each child and checking if it's an optgroup and then running through all its children to check for a match? Is there an easy way through jQuery to combine the value and text methods of setting the selected option?
One other complication, I am going to be doing this within an external jQuery plugin. Within the function I need to modify I have the select element as a variable
$element
so I need a way to do it kind of like this if possible:
$element.descendents(":option").filter(function() {
//do the selecting here
}).prop('selected', true);
If you want to select by the option value, use the value selector:
var myText = "AZ";
$('#state option[value="' + myText + '"]').prop('selected', true);
If you want to search by the option's label, use a filter:
var myText = "Arizona";
$('#state option').filter(function () { return $(this).html() == myText; }).prop('selected', true)
Solved. Since I already had my element passed to a function as a jQuery variable, $element, I couldn't just use the standard selector in the form of:
$("#state option").filter(
// filter function
).prop('selected', true);
After a lot of trying, I got this and it works:
function functionIHadToChange($element, value) {
// other code
$element.find("option").filter(function(){
return ( ($(this).val() == value) || ($(this).text() == value) )
}).prop('selected', true);
}
I am not sure I understood completely your question but I am attempting to answer it in this fiddle
The trick being that you can select it by setting the value of the select box directly
$("#state").val( a_value );
You can set it by $("#select_id").prop("selectedIndex", 3); // Select index starts from zero.
Read here for example this.
$element = $('select#state');
$options = $element.find('option');
$wanted_element = $options.filter(function () {
return $(this).val() == "Alabama" || $(this).text() == "Alabama"
});
$wanted_element.prop('selected', true);
Would be one way to do it.
But i would guess, without knowing the exact internas of the .find() method, in the end jQuery will use at least two loops itself to perform this...
I'm late here but for future visitor, easiest way to do that is :
html
<select name="dept">
<option value="">This doctor belongs to which department?</option>
<option value="1">Orthopaedics</option>
<option value="2">Pathology</option>
<option value="3">ENT</option>
</select>
jQuery
$('select[name="dept"]').val('3');
Output: This will active ENT.