Select and Deselect not working in IE9? - javascript

I have a dropdown <select> element to select states from the list of 50 states, I select the 1st value, save it, and show the value in DOM. I changed and select to the 5th value, saving it shows the value updates in DOM. Now back i am selecting the 2nd Value, and saving it. It's not saving the value in DOM and it's showing the previous selected 5th value. I Checked with different values, and found that, after selecting any higher index value, selecting back, lower values are not affecting in DOM, and hence i am not getting the correct values in POST.
This is the function i am calling on change.
function updateDOM(inputField) {
var elementId = inputField;
if (inputField.type == "select-one") {
var prev_select = inputField.selectedIndex;
$('#'+inputField.id+' option').each(
function() {
$(this).removeAttr('selected');
}
);
document.getElementById(elementId.id).selectedIndex = prev_select;
if (browserVersion == 9) {
document.getElementById(elementId.id)
.options[prev_select].setAttribute("selected","selected");
}
else {
document.getElementById(elementId.id)
.options[prev_select].setAttribute("selected","selected");
}
document.getElementById(elementId.id).value
= document.getElementById(elementId.id).options[prev_select].value;
}
The HTML
<select id="abc" name="abc" onchange="javascript:updateDOM(this);" class="required" >
<option name="" value="" title="null" selected ></option>
<option name="AK" value="Alaska" title="null" >Alaska</option>
<option name="AL" value="Alabama" title="null" >Alabama</option>
<option name="AR" value="Arkansas" title="null" >Arkansas</option>
<option name="AZ" value="Arizona" title="null" >Arizona</option>
</select>

First of all, why don't you use ":selected" selector of jQuery, which you are using anyway? Also, why are you using jQuery only once?
I would recommend doing it in jQuery-style (sorry, I'm not quite sure what you are trying to do exactly in your code):
http://jsfiddle.net/msLXt/1/
P.S. What is the difference between these conditions?
if (browserVersion == 9) {
document.getElementById(elementId.id)
.options[prev_select].setAttribute("selected","selected");
}
else {
document.getElementById(elementId.id)
.options[prev_select].setAttribute("selected","selected");
}

Related

How do you populate an option value using jQuery?

I am trying to populate a form option value if it's attribute quantity equals zero.
My goal is to add the a message to the current option value
My html is:
<select class="valid">
<option disabled="disabled" selected="selected" value="">Select Bar</option>
<option value="1" quantity="99">value 1 </option>
<option value="2" quantity="0">value 2 </option>
</select>
So far I've tried the following in jQuery but it's not working:
if($(this).attr('quantity') == '0') {
$(this).append('<span>message</span>');
}
If you don't care about preserving the original message, than you can simply say $(this).text("message"). Leave out the <span> since it cannot be rendered inside of an <option> element anyway.
if($(this).attr('quantity') == '0') {
$(this).text('message');
}
If you want to preserve the original message, you have a couple options. One would simply be to append the new message to the original, however, it may get tricky to remove it later, so I would suggest having some sort of delimiter so you can easily identify the original vs the appended message, like so:
var $option = $(this);
if($option.attr('quantity') == '0') {
$option.text($option.text().trim() + ' (message)');
}
Then, to remove the message, you can do something like this:
$option.text($option.text().slice(0, $option.text().indexOf('(')).trim());
You can populate the option with like this,
$(document).ready(function () {
$('.valid').on('change', function () {
if ($(this.options[this.selectedIndex]).attr('quantity') == 0) {
$(this.options[this.selectedIndex]).find('span').remove();
$(this.options[this.selectedIndex]).append('<span>Message</span>')
}
});
});
JSFIDDLE
I'm not entirely sure of what you're trying to achieve from your question, but you cannot add html elements to an option element. You can however change the text as follows:
$(document).on('change', '.valid', function(){
var selected = $('.valid > option:selected');
if(selected.attr('quantity') == '0'){
selected.text('something else');
}
});
if you wanted to append an error you could do so by using jQuery append() or concatenating with the original value. Alternatively if you wanted it as validation outside of the select box, you could simply assign to the value of a div by replacing the line inside of the if statement.
<select class="valid" onchange="quality(this.options[this.selectedIndex].getAttribute('quantity'));">
<option disabled="disabled" selected="selected" value="">Select Bar</option>
<option value="1" quantity="99">value 1 </option>
<option value="2" quantity="0">value 2 </option>
</select>
<span id="msg"></span>
<script type="text/javascript">
function quality(val) {
if(parseInt(val) == 0){
document.getElementById("msg").innerHTML = "Message";
}
}

ng-model select dropdown update - angular

Basically i have a select dropdown
<select class="form-control" id="ursel"
ng-change="changeVal()"
ng-options="a for a in RatedVoltage" data-ng-model="TechCharacters.selectedUr">
<option value="" selected="selected">{{globalLangResource.SelectAny}}</option>
</select>
So on change of this select, have results reflecting to another select
viewModel.changeVal = function(){
var val = viewModel.TechCharacters.selectedUr;
if (val != undefined && val === "7.2kV") {
$rootScope.ud = viewModel.InsulationVoltage["7.2kV"]; // 20,30,40
}
}
The 2nd dropdown looks like this
<select class="form-control" id="udsel"
ng-change="setUd();"
ng-options="a for a in ud" data-ng-model="TechCharacters.InsulVolt">
<option value="" ng-if="false"></option>
</select>
Now i have a submit button, on submit,i am getting the main object.
console.log(TechCharacters);
Here i am not getting TechCharacters.InsulVolt value. it is showing empty.
If i have made change is the 2nd dropdown, the model is updated. until then i am not getting the changed model from 1st dropdown
Basically i want all the ng-model values inside form even it is changed or not.
if you want the first object of second dropdown on change of first one. change code to .
viewModel.changeVal = function(){
var val = viewModel.TechCharacters.selectedUr;
if (val != undefined && val === "7.2kV") {
$rootScope.ud = viewModel.InsulationVoltage["7.2kV"]; // 20,30,40
viewModel.TechCharacters.InsulVolt=$rootScope.ud[0]
}
}
hope it will help you
You can actually do this. This will work.
<select data-ng-model="TechCharacters.selectedUr"
<option ng-selected="{{obj == TechCharacters.selectedUr}}" value="{{obj}}" ng-repeat="(key,value) in RatedVoltage">
</select>
Basically you are doing ng-selected and comparing the ng-model value with that of the ng repeat value, and the selected value will be shown.

how to make sure that selected options are different before submit the form?

<select class="distinctrank" name="rank[]" required>
<option value="">Select</option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
</select>
<select class="distinctrank" name="rank[]" required>
<option value="">Select</option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
</select>
<select class="distinctrank" name="rank[]" required>
<option value="">Select</option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
</select>
I am trying to prevent the user to select the same option twice
EX:
value 1 -> B
value 2 -> C
value 3 -> A
But not allow
value 1 -> B
value 2 -> B
value 3 -> A
I can't use this: answer
because I have 8 <select> with 8 <option>and the user is allow to change his/her option.
Unfortunately, I can't use a single select set to "multiple".
I found this answer just now, but since I don't jquery or Javascript well, I can't make it work without the select tag inside a table:
Here is the answer
UPDATE:
I found a better way to do it, but I am having some problems.
I tried to modify this code: with input tags to make it work with select tags. The problem that I am facing now is that every time you select the same option twice, the error "Please enter a Unique Value" show up (I do want to see it, when the user select the same value twice or more) and when you change the value the "Please enter a Unique Value" does go away. But, It keep a "this field is required" warning behind (when a click a new select tag). So, "this field is required" doesn't go away until the user pick an option for all select tag.
Here is the Jquery code:
jQuery.e
jQuery.validator.addMethod("notEqualToGroup", function(value, element, options) {
// get all the elements passed here with the same class
var elems = $(element).parents('form').find(options[0]);
// the value of the current element
var valueToCompare = value;
// count
var matchesFound = 0;
// loop each element and compare its value with the current value
// and increase the count every time we find one
jQuery.each(elems, function() {
thisVal = $(this).val();
if (thisVal === valueToCompare) {
matchesFound++;
}
});
// count should be either 0 or 1 max
if (this.optional(element) || matchesFound <= 1) {
//elems.removeClass('error');
return true;
} else {
//elems.addClass('error');
}
}, jQuery.validator.format("Please enter a Unique Value."))
// validate form
$("#signupform").validate({
rules: {
'rank[]': {
required: true,
notEqualToGroup: ['.distinctrank']
},
},
});
I wonder if you could simply use a single select set to "multiple"...
<select multiple class="form-control" name="rank[]">
<option value="">Select</option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
</select>
It seems appropriate :-)
Your code...
rules: {
'rank[]': { // <-- will only match one of your three
required: true, ....
You cannot have three different select element all share the same name, in your case, rank[].
The jQuery Validate plugin requires that every form data input element contain a unique name. It's how the plugin keeps track of the form inputs, and there is no workaround for this. You'll have to include an index or change the name.
rules: {
'rank[1]': {
// rules
},
'rank[2]': {
// rules
},
'rank[3]': {
// rules
}
}
If the same rules are used on all three, then you can use the .rules() method to apply them all at once...
$("#signupform").validate({ // plugin initialization
// other rules & options
});
$('[name^="rank"]').each(function() {
$(this).rules('add', {
required: true,
notEqualToGroup: ['.distinctrank']
});
});
$('[name^="rank"]') matches all elements that have a name that "starts with" rank. Then .each() applies the rule to every instance matched by the selector.
You can try something like this:
$(document).ready(function() {
$('select').change(function() {
self = $(this);
choosen = $(this).val();
$('select').not(self).each(function() {
if ($(this).val() == choosen) {
// $(this).prop('disabled', true);
alert('Option is already selected');
$(self).val($(this).find("option:first").val());
}
});
});
});
This is actually partial implementation of code you found in another answer. Commented line would disable already selected options, but... then users can't change their minds... However i would probably use that commented line (edit:probably not, it causes other problems), rather than annoying alerts -> because, with alerts - if user tries to change his mind - user experience is not so great, again...
DEMO: http://jsfiddle.net/dq9j4s32/2

How to set the closed dropdown value on an ng-Options

I'm using angular to manage my select dropdown, from an array.
The entries in the array itself are all lowercase.
The "selected" variable to be used elsewhere in the code wants to be lowercase.
The displayed entries in the dropdown want to be uppercase
When the dropdown is closed it wants to display the currently selected entry (in uppercase) with the string "VIEWING: " prepended.
I understand how to achieve the first 3 (by using myValue.toUpperCase() for myValue in myArrayOfValues) but I don't even remotely know how to go about achieving the 4th point - either in Angular (ideally) or in raw JS/jQuery
Anyone know how to achieve this?
I think you want a combination of:
https://api.jquery.com/focusin/
https://api.jquery.com/change/
https://api.jquery.com/focusout/
HTML:
<select name=dropdown size=1>
<option value="option1">option 1</option>
<option value="option2" selected>VIEWING: option 2</option>
</select>
Javascript:
var dropdown = $('select[name="dropdown"]');
dropdown.focusin(function() {
var selected = dropdown.find(":selected");
selected.html(selected.val());
});
dropdown.change(function() {
updateSelected();
$(this).blur();
});
dropdown.focusout(function() {
updateSelected();
});
function updateSelected() {
var selected = dropdown.find(":selected");
var html = "VIEWING: " + selected.val();
selected.html(html);
}
https://jsfiddle.net/r89oy2zk/

Check if dropdown's selected option is not the first with JavaScript

Below are the options that I have in my HTML code:
<label id="subn">
<select name="subs" id="subs">
<option value="nothing">Choose a Subject</option>
<option value="General Question">General Question</option>
<option value="MemberShip Area">MemberShip Area</option>
<option value="Others">Others</option>
</select>
</label>
I want to create JavaScript code that will check whether the user selected an option other than the first one.
Here is what I tried:
if (document.getElementsByTagName('option') == "nothing"){
document.getElementById("subn").innerHTML = "Subject is Required!";
document.getElementById("subs").focus();
return false;
}
You can check like this if nothing is the first option (usually the case in my experience):
if (document.getElementById('subs').selectedIndex == 0){
To still compare based on the value, do this:
var sel = document.getElementById('subs');
if (sel.options[sel.selectedIndex].value == 'nothing') {
You may want to change your markup so the label is beside, like this:
<select name="subs" id="subs"></select><label id="subn" for="subs"></label>
Otherwise this part: .innerHTML = "Subject is Required!"; will erase your <select> :)
This should do it:
var index = document.your_form_name.subs.selectedIndex;
var value = document.your_form_name.subs.options[index].value;
if (value === "nothing"){
// your further code here.........
}
document.getElementsByTagName('option') gives a collection of all option elements in the document and "nothing" is a string. Comparing a collection to a string is quite useless.
Also setting document.getElementById("subn").innerHTML = "Subject is Required!"; will delete the select element, so document.getElementById("subs") wouldn't find anything any more.
If you just need to know if anything is selected check the selectedIndex property of the select element:
if (document.getElementById("subs").selectedIndex <= 0) {
// nothing is selected
}
EDIT: Changed > 0 to <= 0. I would assume that it should be checked if the user didn't select anything, too.

Categories