Select element returning value only when disabled - javascript

I have a select box as follows:
<select id="selectbox" class='info-entry-select' name="country">
<option value="1" selected="selected">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
This select box is in a hidden div that, when appearing, refreshes the select box options using ajax and a separate php file. Here's the javascript that updates the select box:
$("#changeselectoptions").on('click', function() {
$.ajax({
type: "GET",
url: "includes/selectoptions.php",
dataType: 'json',
success: function(result){
// Replace options of select box
var $el = $("#selectbox");
var newOptions = result['catsOrderList'];
// newOptions correctly returns an array in the form of {1: "One", 2: "Two", 3: "Three", 4: "Four"}
$el.empty(); // remove existing options
$.each(newOptions, function(key,value) {
$el.append($("<option></option>").attr("value", key).text(value));
});
}
});
return false;
});
If I now call: $('#selectbox').val(); I get undefined and I'm not sure why? To make matters more confusing, if I disable #selectbox (using a toggle switch that adds .attr('disabled', 'disabled'); to #selectbox, then try $('#selectbox').val(); I get the expected val of 1, 2, 3, etc.
How can I get this value without disabling the box, or what have I overlooked?
Edit:
I've been asked where my $('#selectbox').val(); call is. It's not any more involved than I mentioned above, but to be thorough, it's called from a submit button in the same div as the select element as follows:
$("#submitbutton").on('click', function() {
var selectBoxVal = $('#selectbox').val();
console.log('value is: ' + selectBoxVal);
return false;
});
My only idea so far is that it may be a dom issue? I say that ignorantly as my knowledge doesn't quite know the full ins and outs but I've seen issues where elements are altered live by javascript and not retrieved correctly by later javascript calls - whereas they work fine if the elements being retrieved existed when the page loaded.
I don't assign a selected property to any of the options but I don't believe this should cause undefined to be returned. For example, if I disable the select box, the value is returned correctly from the same query (as mentioned above) yet it still doesn't have a selected property added manually. I digress, but is it required to add a selected property when creating a series of options in javascript? Which option is initially presented as selected is irrelevant to me from a usage point of view but I'd be happy to follow best procedures. I assumed that the browser interpreted the displayed option as selected if none were marked as such.

I believe that the "value" of the select will be the <option> that has the attribute "selected" within that selectbox. Otherwise, there is no indicated value for that input.

Related

Form not reading the select attribute when added option via ajax

I am prepending an <option> via ajax like this:
success: function(data) {
jQuery('#usp-cat-combo-1').prepend('<option selected="selected" value="'+data.cat_id+'">'+data.cat_name+'</option>');
}
The thing is when I submit the form, that option says not selected and I need to manually select it, even tho I have given the attribute selectedwhen I added it
Try setting value of the <select> instead of setting selected attribute on the option
jQuery('#usp-cat-combo-1')
.prepend('<option value="'+data.cat_id+'">'+data.cat_name+'</option>');
.val(data.cat_id)
Note this assumes the <select> is not a multiple. If it is a multiple can set prop('selected',true) on the new first child
What you have to do:
Defined the option which you want to select by default like:
var selected;
success: function(data) {
data.cat_id=='1' ? selected = 'selected="selected"' : selected = '';
jQuery('#usp-cat-combo-1').prepend('<option '+selected+' value="'+data.cat_id+'">'+data.cat_name+'</option>');
}
Now it just add Selected Attribute at one option that you defined not every option.
Note :
Assume that you have data as an array.
You can use data.cat_name or other as you want instead of cat_id to defined your Selected Option.
Feel free to comment for more help or other simplification :)

Removing duplicates from a dropdownlist

I have a dropdown that is returning duplicates. I don't know why it is returning duplicates.
Here is the control for my dropdown.
#Html.DropDownList("procDateId", Model.GetEmpHoursDateRange.EmphoursdateSelectList, Model.GetEmpHoursDateRange.selectedEmplhoursdate, new { id = "procDateId" })
I want to be able to remove the duplicates once the page load.
I tested the code below with an alert and am able to get to the document.ready
$(document).ready(function () {
alert("here you go !!!");
[].slice.call($('#procDateId').option)
.map(function (a) {
if (this[a.innerText]) {
$('#procDateId'.option).removeChild(a);
} else {
this[a.innerText] = 1;
}
}, {});
});
Here is the html that my dropdown is rendering.
<select id="procDateId" name="procDateId">
<option value>1/11/2017</option>
<option value>1/11/2017</option>
<option value>1/10/2017</option>
<option value>1/9/2017</option>
</select>
The duplicates are not been removed with my code above. No luck. Kindly assist.
Your jQuery selector for the option appears incorrect: $('#procDateId').option --> ('#procDateId option')
Additionally, you can call remove on the option directly
jsfiddle: https://jsfiddle.net/db9zczr0/
The reason for the double up is you're using an overload with the defaultOption = Model.GetEmpHoursDateRange.EmphoursdateSelectList. The value returned is the duplicate.
The default option appears at the start of the list and its value is
empty. A default option is used to communicate that no option is being
chosen from the list, such as when the drop-down control represents an
optional parameter.
From https://msdn.microsoft.com/en-us/library/gg548012(v=vs.111).aspx
So you will want to use a different overload, e.g.
HtmlHelper.DropDownList Method (String, IEnumerable,
Object)
Then to tell the View to show the selected option using the saved session value, in the controller loop over the IEnumerable<SelectListItem> and set Selected = true for the matching item.

How to separate by pipe for multiple select in hidden field

I have a form that has 3 drop downs to make selections, the first drop down allows the user to select a specific Type, the second box, the user must select a date which will then present users with the filtered options on the 3rd drop down which is done in Jquery. I had it working where the user only selects one option in the 3rd drop down.
Now I would like the user to select multiple options. The code below is what I used to get the single selection to update the hidden field and pass via form submission.
The below code minus the ".join('|')" outputs the values into the hidden field then it gets passed into a data storage via POST.
This is my code:
$('#TopicID').on('change',function()
{ TIDval.val( $(this).find(':selected').text().join('|') );
});
I tried several versions to get it to work if I remove the ".join('|')" the output gives me all of the values concatenated.
Value 1: tree
Value 2: boat
Value 3: car
The output is as follows: treeboatcar
but I need: tree|boat|car
I have updated my new code to reflect the solution suggested by Loading... in this thread to the following.
$('#TopicID').change(function(){
var selectedText = $(this).find(':selected').map(function(){
return $(this).text(); //$(this).val()
}).get().join('|');
$("#TopicID_value").text(selectedText);
});
Which now updates the hidden field value correctly with the pipe separated values but the value is no longer passed in the POST call when submitted in the form.
The hidden field
In firebug I see the value being updated properly when I select one or multiple options but for some reason the value gets lost in the submission process. I don't see much of a different where that could happen.
Use map()
$('#TopicID').change(function(){
var selectedText = $(this).find(':selected').map(function(){
return $(this).text(); //$(this).val()
}).get().join('|');
console.log(selectedText);
});
$('#TopicID').change(function(){
var selectedText = $(this).find(':selected').map(function(){
return $(this).text(); //$(this).val()
}).get().join('|');
console.log(selectedText);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="TopicID" multiple="true">
<option id="1">ABC</option>
<option id="2">XYZ</option>
<option id="3">PQR</option>
</select>

Hide select option not reflecting

I am trying to hide some options from a select. The solution used is this:
this.selectBox.children(".myOption_"+optionValue).wrap("<span></span>");
this.selectBox is a jQuery object of the mentioned select.
In Firefox it works just fine, but in IE8 the changes are not reflected: if one should look at the select, it will seem unchanged. But if the user selects an option, the value respects the removed element.
Here is an example:
<option value="val1">Test1</option>
<option value="val2">Test2</option>
<option value="val3">Test3</option>
<option value="val4">Test4</option>
Now, when I select "Test1", a function is called and the above code is executed.
From the user's perspective, the options will remain the same. BUT if he now tries to select "Test1" again, the provided value will actually be "val2" and the option should be removed. Again, nothing happens, so he selects "Test1" again and the value will be "val3" and so on.
In order to display the occured changes, I have to hide and then show the select.
this.selectBox.children(".myOption_"+optionValue).wrap("<span></span>");
this.selectBox.hide().show();
The code above will make the changes visible(hide the clicked options).
What is more curious is that this fiddle:
http://fiddle.jshell.net/FAkEK/25/show/
works as it should on the same browser.
I do not understand why is this all of a sudden happening.
Why is this happening? Where should I look for the issue?
I am not sure why you would want to hide the option instead of removing it, but here's an example on how you can do it. It's based on this solution for hiding options.
Fiddle here -> http://jsfiddle.net/kAp42/2/
JSBin here (should work in IE8) -> http://jsbin.com/uyuram/1
var $select = $('select');
$select.prop('selectedIndex', -1); //ensure we can hide the first option
$select.change(function () {
//not sure why you would not want to remove the option instead of hiding it byt, if you want to hide...
$select.children('option:selected').wrap('<span class="hide-option"></span>');
//remove it
//$select.children('option:selected').remove();
this.selectedIndex = -1; //ensure we can hide the last option
});

Is there a way to set `selected` flag instead of val() for dropdowns?

The select values are confusing me. When the user edits a row in my app I clone a tag with jquery (called empty-X) and put it on a modal window so that the user can edit the values. At the same time I get a json object (data) from server and fill in the current fields on the modal window as it stands in the database :
empty_X.find('#id_deals-1-currency').val(data[0].fields['currency']);
Now when the modal shows, the user can see how the correct currency is selected in the dropdown.
Yet when I check the HTML for this element with Firebug, I get a different picture, nothing seems selected.
<select id="id_deals-1-currency" name="deals-1-currency">
<option selected="selected" value="">---------</option>
<option value="1">USD - $</option>
<option value="2">EUR - €</option>
<option value="3">GBP - £</option>
</select>
And yet when I send the form to the server, there are no validation errors and the currency is the same value as it was previously set through val(). Life is good.
While this works by itself, there is a problem. What if the user wants to get back to the edit mode and verify the currency once more before saving it?
In this case I can't load the values from the database any more. His previous local changes matter now. I have to clone the current record with currency inside back in the modal window, so the user can see what he had changed previously and verify it. The problem is now the user doesn't see the currency he had changed in the previous step. In fact he would see an empty dropdown instead.
What are my options here? Is there a way to set the selected flag to the actual selection rather than using val()?
When cloning a <select>, the option with the 'selected' attribute becomes the current option in the cloned object - instead of the actual current object (as per value attribute).
To counter this, you can find the currently selected option from the value returned by val() and then apply the selected attribute to it prior to cloning it. This way you wont need to set the value after cloning.
Demo: http://jsfiddle.net/DqADq/
Code: (.x1 is the <select>)
// simple cloning
$('.x1:first').clone().appendTo('.out');
// setting selected attr before cloning
var v = $('.x1:first').val();
$('.x1:first option').removeAttr('selected'); // remove 'selected' from all options
$('.x1:first option').each(function() {
if($(this).attr('value') == v) {
$(this).attr('selected', true); // apply 'selected' to current option
}
});
$('.x1:first').clone().appendTo('.out');

Categories

Resources