I am trying to fill an html select box programmatically using javascript. I have found that although my code is working, jquery mobile is interfering with what displays in the select box. I am setting the selected option, which is working, but the value displayed in the select box is the wrong value. It isn't changing from what I had it originally filled as from the html.
I am linking in: "http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.css". Is there anyway to get around the jquery? I can't just remove the jquery css. That would break everything on my site, and I don't have time to redo it all.
Here is a jsfiddle of the problem: http://jsfiddle.net/RjXRB/1/
Here is the my code for reference:
Here is my javascript function that fills the select box:
function printCartList(newCart){
// newCart is an optional parameter. Check to see if it is given.
newCart = newCart ? newCart : "a_new_cart_was_not_provided_12345abcde";
// Create a cart list from the stored cookie if it exists, otherwise create a new one.
if($.cookie("carts") != null){
carts = JSON.parse($.cookie("carts"));
}
else{
selectOption = new Object();
selectOption.value = "newuniquecartid12345abcde";
selectOption.html = "***New Cart***";
carts = new Object();
carts.size = 1;
carts.option = new Array();
carts.option[0] = selectOption;
}
// Get the select box
var select = document.getElementById("select_cart");
// Get the number of options in the select box.
var length = select.options.length;
// Remove all of the options in the select box.
while(select.options.length > 0){
select.remove(0);
}
// If there is a new cart, add it to the cart.
if(newCart != "a_new_cart_was_not_provided_12345abcde"){
selectOption = new Object();
selectOption.value = newCart;
selectOption.html = newCart;
carts.option[carts.size] = selectOption;
carts.size++;
}
// Save the cart in a cookie
$.cookie("carts",JSON.stringify(carts));
// Populate the select box
for(var i = 0; i < carts.size; i++){
var opt = document.createElement('option');
opt.value = carts.option[i].value;
opt.innerHTML = carts.option[i].html;
if($.cookie("activeCart") == carts.option[i].value && newCart != "a_new_cart_was_not_provided_12345abcde"){
// Set the selected value
alert(carts.option[i].value);
opt.selected = true;
// I tried changing the value of a p tag inside the default option, but that didn't work
document.getElementById("selectHTML").innerHTML = carts.option[i].html;
}
if(opt.value == "dd"){alert("hi");};
select.appendChild(opt);
}
}
Here is my html:
<form method="POST" name="cartSelectForm" action="home.php">
<select name="cartList" id="select_cart" data-mini="true" onchange="submitCartForm()" data-icon="false">
<option value="newuniquecartid1234567890"><p id="selectHTML">*** New Cart ***</p></option>
</select>
</form>
Any help would be greatly appreciated.
I know this question is about a month old, but I stumbled upon it because I was having the exact same issue. I eventually fixed it by doing this:
After programmatically setting the value, I manually fired the change event on that select box. I guess it forced jQuery mobile to update all of it's enhanced markup related to that element. Slightly annoying, but fortunately very easy to work around.
$("#country").val("US");
$("#country").change();
Hope that helps somebody.
Related
I need to dynamically set the select options based on the one value which is getting from the controller while loading the page.
<script>
validate selectOptions();
function selectOptions(){
var healthWorkerQuestions1 = "${healthWorkerQuestions}";
if(healthWorkerQuestions1 == "6" || healthWorkerQuestions1 == "7" || healthWorkerQuestions1 == "8"){
alert("six to eight");
$('#questionOptions').empty();
var sel = document.getElementById('questionOptions');
for(var i = 0; i < drinker.length; i++) {
var opt = document.createElement('option');
opt.innerHTML = drinker[i];
opt.value = drinker[i];
$('questionOptions').append(opt).selectmenu('refresh');
//sel.appendChild(opt).selectmenu('refresh');
}
}
}
</script>
Here the loop is executing and able to see the alert box. And the select box options are not updating in the select box. I tried in two ways as follows,
$('questionOptions').append(opt).selectmenu('refresh');
sel.appendChild(opt).selectmenu('refresh');
But the options are not updating while loading the page.
The code for select box is:
<select name="questionOptions" id="questionOptions">
<option>Select</option>
</select>
After loading the page I am able to see only select option but not the dynamically appended values. How can I update the select option on page loading.
Any suggestions please..
Code is looks fine. To update the select option call the method form jQuery document ready function as mentioned below,
<script>
$(function(){
selectOptions();
});
function selectOptions(){
// Your code here....
}
</script>
Hope this will help you.
I have a select drop down menu, every time I refresh my page I have to re populate that select drop down. Which is resulting in a memory leak. This is the code any help would be great in refactoring the code. Also I have tried to make another method and calling it before this one, the other method would empty the options array and make it null. That did not help me.
var option = $(document.createElement("option"));
option.attr("value", List.id);
option.text(List.name);
if(List.name.length > maxSize) {
maxSize = List.name.length;
}
this.options.push(option);
//Mark the currently displayed list as the selected option
if (activeListId > 0) {
if (activeListId == List.id) {
option.attr("selected", true);
}
}
}
Toolbar.ListSelect.append(this.options);
It would be very helpful if you included more of the surrounding code so that we could know what is what, but here's my best shot at it given the current situation.
// Reference box
var $box = $('#id-of-select-box');
// Clear select box
$box.empty();
// START LOOP
// Create new option
var $option = $('<option value="'+List.id+'">"'+List.name+'"</option>');
// Append option to select box
$box.append($option);
// END LOOP
//Mark the currently displayed list as the selected option
if (activeListId > 0) {
$box.val(activeListId);
}
I whould suggest to create a new Element, then cut the provided name if exceeds thet maxSize using slice). Later we add the parameter "selected" if there is a match on activeListId and List.id. Latter we append the new option to Toolbar.ListSelect (I suposse it to be the element
var option = jQuery("<option />").attr('value', List.id);
var optionName = List.name.slice(maxSize);
option.text(optionName);
if ( activeListId && activeListId == List.id)
option.attr("selected", true);
option.appendTo(Toolbar.ListSelect)
I am using javascript to populate a select box in my page but its not working, the select box displays but its completely empty.
I also get no error in my console.
My script is this:
var select = document.createElement("select");
for(var i in resource){
if(i !== id && select.hasOwnProperty(i)){
select.setAttribute(i, resource[i].name);
}
}
d.appendChild(select);
Example data for resource:
{
"1":{"name":"Test"},
"2":{"name":"Test2"},
"3":{"name":"Test3"}
}
Any ideas on why it won't populate?
There are quite few mistakes in your script, many are mentioned in the comments as you can see.
What you are looking for might be something like this
var select = document.createElement("select");
for(var i in resource){
if(resource.hasOwnProperty(i)){ //removed the i !== id condition, you may put it back
var opt = new Option(resource[i].name, i);
select.options[select.options.length] = opt;
}
}
document.body.appendChild(select);
Demo: Fiddle
You need to create child elements of the select, that are option tags.
Here's a sample JSFiddle.
I am not sure if I confused everyone with the above title. My problem is as follows.
I am using standard javascript (no jQuery) and HTML for my code. The requirement is that for the <select>...</select> menu, I have a dynamic list of varying length.
Now if the length of the option[selectedIndex].text > 43 characters, I want to change the option[selectecIndex] to a new text.
I am able to do this by calling
this.options[this.selectedIndex].text = "changed text";
in the onChange event which works fine. The issue here is once the user decides to change the selection, the dropdownlist is showing the pervious-selected-text with changed text. This needs to show the original list.
I am stumped! is there a simpler way to do this?
Any help would be great.
Thanks
You can store previous text value in some data attribute and use it to reset text back when necessary:
document.getElementById('test').onchange = function() {
var option = this.options[this.selectedIndex];
option.setAttribute('data-text', option.text);
option.text = "changed text";
// Reset texts for all other options but current
for (var i = this.options.length; i--; ) {
if (i == this.selectedIndex) continue;
var text = this.options[i].getAttribute('data-text');
if (text) this.options[i].text = text;
}
};
http://jsfiddle.net/kb7CW/
You can do it pretty simply with jquery. Here is a working fiddle: http://jsfiddle.net/kb7CW/1/
Here is the script for it also:
//check if the changed text option exists, if so, hide it
$("select").on('click', function(){
if($('option#changed').length > 0)
{
$("#changed").hide()
}
});
//bind on change
$("select").on('change', function(){
var val = $(":selected").val(); //get the value of the selected item
var text = $(':selected').html(); //get the text inside the option tag
$(":selected").removeAttr('selected'); //remove the selected item from the selectedIndex
if($("#changed").length <1) //if the changed option doesn't exist, create a new option with the text you want it to have (perhaps substring 43 would be right
$(this).append('<option id="changed" value =' + val + ' selected="selected">Changed Text</option>');
else
$('#changed').val(val) //if it already exists, change its value
$(this).prop('selectedIndex', $("#changed").prop('index')); //set the changed text option to selected;
});
I have two multi lists. In first multi list, i got all the attributes of table by using query then now by selecting one attribute from this list, when i click on "ADD" button i want that copy of this attribute should go into another list.
What i have done is i added javascript onclick function for ADD button in that i got the selected value from first multilist. But now I am not getting how to put that value in to second multi list?
What i have done in java script function is:
var index=document.getElementById("List1").selectedIndex;
var fieldval=document.getElementById("List1").options[index].value;
document.getElementById("List2").options[0].value=fieldvalue;
But this is not working. Temporarily I am adding value at first position.
Thanks in advance.
From here:
If you want to move an element from the first list to the second:
var index=document.getElementById("List1").selectedIndex;
var elOpt = document.getElementById('List1').options[index];
var elSel = document.getElementById('List2');
try {
elSel.add(elOpt, null); // standards compliant; doesn't work in IE
}
catch(ex) {
elSel.add(elOpt); // IE only
}
If you want to add one:
var index=document.getElementById("List1").selectedIndex;
var elOpt = document.getElementById('List1').options[index];
var elSel = document.getElementById('List2');
var elOptNew = document.createElement('option');
elOptNew.text = elOpt.text;
elOptNew.value = elOpt.value;
try {
elSel.add(elOptNew, null); // standards compliant; doesn't work in IE
}
catch(ex) {
elSel.add(elOptNew); // IE only
}