jquery - dynamically changing the option text is not working - javascript

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

Related

JQuery Selector not working, where looping does. Why?

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

Using jquery append to add option values into a select element not working

I'm looking to dynamically populate a select element with names of items that are stored into an array.
For some reason it's not working and I'm not sure why.
HTML:
<div class="col-md-4 col-md-offset-4">
<select class="select1">
</select>
and
<select class="select2">
</select>
</div>
Note that I'm using bootstrap for layout.
Here's the jquery I'm using to try and populate ".select1"
JQUERY:
select: function() {
$.each(state.greens, function(index, value) {
$(".select1").append("<option value =' " + index + " '>" + state.greens[index].name + "</option>");
});
}
Note that the function 'select' is stored within an object called 'display'.
state.greens is the name of the array I'm trying to access.
So at the end of my html page I call display.select(); to call the function.
No error messages are showing up in the console.
Also, I saw this question: Appending options to select using jQuery doesn't work
but was looking for a jquery centric answer and this seems like it ought to work.
You can do in that way:
$.each(state.greens, function(index, value) {
$('.select1').append($('<option>', {
value: index ,
text: state.greens[index].name
}));
});
When you append you are basically adding to the .innerHTML value of a container. This works for most elements except for <select>. You'll have to add elements properly for the DOM to pick it up:
var select=document.getElementById('select1');
var option=document.createElement('option');
option.setAttribute('value','option1');
option.innerHTML='Option 1';
select.appendChild(option);

Build child menu based on values selected in parent multiple select list in Jquery

I need to construct a second select list based on options selected in my first select list (which is a multiple). However my append is adding multples. My alert returns
1st alert 1
2nd alert 1,5
3rd alert 1.5,7
I need the append to happen for the very last option selected.
$('#firstselect').change(function(){
alert('id ' + $(this).val());
$('#secondselect').append('<option value=' + $(this).find(':selected:last').val() +'>' + $(this).find(':selected:last').text()) + '</option>';
});
You were close, but you don't need to append the options indivdually or construct them manually, just clone them and exchange the html of your second <select>
$('#firstselect').change(function(){
var cloned = $(this).find(':selected').clone();
$('#secondselect').html(cloned);
});
This will add all selected options in the original order. Of course, you might want them inserted in the order they were selected. That's a bit more tricky, since you have to keep track of what was selected when and also what was actually deselected, but here is a solution for that too:
var last_selected;
$('#altfirstselect').change(function() {
var selected = $(this).find(':selected');
var cloned = selected.not(last_selected).clone();
if(last_selected) {
var to_remove = last_selected.not(selected);
to_remove.each(function(){
$('#altsecondselect').find('[value='+$(this).val()+']').remove();
});
}
$('#altsecondselect').append(cloned);
last_selected = selected;
});
I created a fiddle, where you can see both solutions in action and see how they work differently based on the order of your selection: http://jsfiddle.net/xu333zxs/2/
Or, you could just remove them all then add them all again each time. No big deal
$('#firstselect').change(function(){
$('#secondselect option').remove();
$('#secondselect').append('<option value=' + $(this).(':selected').val() +'>' + $(this).find(':selected').text()) + '</option>';
});

jQuery - On Select Option Event

I am trying to make it so when somebody selects a certain option from my list it will trigger an event. I know you are supposed to use the .change event but that isn't working for me.
Checkout the code below.
Select:
$co1 = array("English", "Math", "Science", "History");
for($c=1;$c<5;$c++){
echo '<select name="c'.$c.'" id="course'.$c.'" class="selectpicker"><option selected="selected" id="course'.$c.'" value="course'.$c.'" name="'.$c.'">Course '.$c.'</option>';
foreach ($co1 as &$cl1){
echo '<option value="'.$cl1.'" name="'.$cl1.'">'.$cl1.'</option>';
}
echo '</select>';
}
jQuery:
<script>
$('#course1').change(function(){
$("#course2 option[value='Math']").each(function() {
$(this).remove();
});
})
</script>
I basically used PHP to make it so there are four different select options with the same options but different values for a grading system. I want to use this script to make it so when you select Math for the first course it will remove it from the list in the other 3 courses.
Any ideas how this would work? I'm up for suggestions on other ways to do this.
Use delegation
$('body').delegate('#course1','change',function(){
$("#course2 option[value='Math']").each(function() {
$(this).remove();
});
})
Try:
$("body").on("change","#course1",function () {
$("#course2").find("option[value='Math']").remove();
});
Fiddle here.
Attribute name and id just for only select tag. Open this link to see standard select option html tag.
If you do that, you have two same id there. <select>, and your first <option>.
try to change your PHP become :
$co1 = array("English", "Math", "Science", "History");
for($c=1;$c<5;$c++){
echo '<select name="c'.$c.'" id="course'.$c.'" class="selectpicker">
<option selected="selected" value="course'.$c.'">Course '.$c.'</option>';
foreach ($co1 as &$cl1){
echo '<option value="'.$cl1.'">'.$cl1.'</option>';
}
echo '</select>';
}
This is the shortest I could come up with:
$('#course1').change(function () {
$('#course2').find('option:gt(0)').remove().end().append($(this).find('option:gt(0)[value!=' + $(this).val() + ']').clone())
})
jsFiddle example
this will hide the option from course2 if same is selected as course1 and show if user selects another one in course1
$('#course1').change(function () {
var val = $(this).val()
if($('#course2').val()==val)
$('#course2').val($('#course2').children('option:first').val())
$("#course2 option").each(function () {
if ($(this).val() == val)
$(this).hide(); //change this line to $(this).remove() to remove permanently
//and remove the else part below
else
$(this).show()
});
})
DEMO
Note that after removing completely you will not be able to show it again hence i will recommend using show and hide on change of course1
I hope I got right what you want to do. Try this fiddle
You could just .hide() the option which matches the current selected and to show the before hidden again just .show() the current :hidden elements?
$('#course1').change(function(){
var sel = $(this).val();
$("#course2 option:hidden").show();
$("#course2 option[value='"+sel+"']").each(function() {
$(this).hide();
});
});

How to select option value from select tag using jquery

sorry guys, previously I didn't mention the my dropdown list is made with bootstrap. based on #rps suggestion I asked to my colleague(who is made template) he said it's made with bootstrap.
I am putting basic html dropdown code,so I think you guys can understand How bootstrap code will be.
html code:
<select name="primary" class="select-block" id="select_alert">
<option "selected">Choose Alert T</option>
<option value="T1">T1</option>
<option value="T2">T2</option>
<option value="T3">T3</option>
<option value="T4">T4</option>
</select>
Initially i am getting the select menu in the following way.
for my conformation,I am finding the menu value in the following way.
i/p: document.getElementById('select_alert').value
o/p: "choose Alert T"
Now using javascript or jquery, I want to change select option in the follwoing way.For this I tried the below it's not working
document.getElementById('select_alert').value="T1";
Again If I check the value of select menu,it should be "T1".
Thanks
you can try this
// Get the value from a dropdown select
$( "#select_alert option:selected").val();
$( "#select_alert option:selected" ).text();
My reading of the question is ambiguous, but if you're trying to set the value, or set the selected-option, to T1:
$('#select_alert option[value="T1"]').prop('selected',true);
JS Fiddle demo.
If you're trying to retrieve the value of the selected option:
$('#select_alert option:selected').val();
Using jQuery you can just do this:
$('#select_alert').val('T1');
Demo : Fiddle
use as follows :
$('#select_alert').val('T1'); // in jquery
also your javascript code is correct, there must be some other error on the page.
without jquery you can use
document.getElementById('select_alert').selectedIndex = 1
http://jsfiddle.net/uzqZA/1/
if you want to find out the option index by given value try this
var sel = document.getElementById('select_alert'),
selopt = sel.options,
searchidx;
//alert(selopt[sel.selectedIndex].value);
//sel.selectedIndex = 1;
//alert(selopt[sel.selectedIndex].value);
//alert(sel.value)
// search for the index
searchidx = getoptidx(selopt, "T3");
if (searchidx !== false) {
sel.selectedIndex = searchidx;
alert(selopt[sel.selectedIndex].value);
} else {
alert("index not found")
}
/**
* returns the index of a value
* #todo optimize search?
*/
function getoptidx(opts, searchterm) {
for (var i in opts) {
if (opts[i].text === searchterm) return i;
}
return false;
}
the fiddle: http://jsfiddle.net/uzqZA/6/
Try to do it this way :
$('#select_alert').val("T3");
$("#select_alert").selectmenu();
$("#select_alert").selectmenu("refresh");

Categories

Resources