Selecting default values in multi-select dropdown - javascript

Problem with multiselect: I am having a need of selecting default options in a multiselect dropdown. Here I am working with Struts2 and default options are coming from server.
Struts Code:
<select multiple >
<s:iterator var="user" value="%{USERS}">
<option <s:if test="%{#approvalStep.isUserSelected(#user.userId) == true}"> selected="selected" </s:if> value="<s:property value="#user.userId"/>" > <s:property value="#user.userName"/></option>
</s:iterator>
</select>
Result of Struts Code:
<div id="selectAndRemoveUser">
<select multiple="">
<option selected="selected" value="2000000002007"> aftabalamm7861111111</option>
<option selected="selected" value="2000000003015"> aftabalam.m+12</option>
<option selected="selected" value="2000000003011"> Aftab</option>
<option selected="selected" value="2000000026353"> aftabalam.m+approver1</option>
</select>
</div>
Problem:
When I am trying to get the selected option using Jquery It's only returning the first option. And if I manually edit the select > option elements (I mean re-write the selected=selected using browser inspect element) it's work fine.
Jquery Code:
console.log($("#selectAndRemoveUser").find('select :selected').length); // the result is 1;
if($("#selectAndRemoveUser").find('select :selected').length > 1 ) {
alert('false');
} else {
alert('true');
}

For multiselect dropdown, the name of the select field should be defined as array i.e add 'name[]' at the end of the name attribute.
**HTML** :
<div id="selectAndRemoveUser">
<select multiple="" name = "user[]">
<option value="2000000002007"> aftabalamm7861111111</option>
<option value="2000000003015"> aftabalam.m+12</option>
<option value="2000000003011"> Aftab</option>
<option value="2000000026353"> aftabalam.m+approver1</option>
</select>
</div>
**Jquery** :
$("select")
.change(function() {
var str = "";
$("select option:selected").each(function() {
str += $(this).text() + " ";
});
console.log(str);
})
.trigger("change");

Related

How to get the OPTION's TEXT value

In this case, only primary dropdown will change, other dropdowns' values will change automatically according to it (so users wont be changing them) I'm trying to get the Option's TEXT value using PHP with $_POST. But i can only get it when i manually changed the other dropdown .
I have tried to use the trigger() method, but it fails to get the option text value. Any idea why the code fails to work. Thank you.
function setDropDown() {
var index_name =
document.getElementsByName('ForceSelection')[0].selectedIndex;
var others = document.querySelectorAll('.secondary');
for (var i = 0; i < others.length; i++) {
others[i].selectedIndex = index_name;
}
}
<!-- try to get the option text value and pass it to input field-->
<!-- Then in the php code use $_POST[] to retrieve the input value-->
function setTextField(ddl) {
document.getElementById('make_text').value = ddl.options[ddl.selectedIndex].text;
}
$("select").trigger("change");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post">
<div><b>Primary dropdown:</b>
<select name="ForceSelection" id="ForceSelection" onChange="javascript:return setDropDown();">
<option value="" selected>Select</option>
<option value="treatmentid1">treatmentname1</option>
<option value="treatmentid2">treatmentname2</option>
</select>
</div>
<div>
<b>Other dropdown 1</b>:
<select class='secondary' id="Qualifications" name="Qualifications" onChange="setTextField(this)">
<option value="select">select</option>
<option value="treatmentid1">treatmentname1</option>
<option value="treatmentid2">treatmentname2</option>
</select></div>
<input id="make_text" type="hidden" name="make_text" value="" />
<div> <b>Other dropdown 2</b>:
<select class='secondary' id="Qualifications2" name="Qualifications2">
<option value="select">select</option>
<option value="treatmentid1">treatmentname1</option>
<option value="treatmentid2">treatmentname2</option>
</select>
</form>
PHP Code
$value =$_POST['make_text'];
Html element <select> onchange doesn't fire for programmatic changes, you need to fire it yourself with
$(".secondary").trigger("change");
or by Id
$("#Qualifications").trigger("change");
The problem is that your hidden <input> never had the value. if you remove the hidden it on your code you can check it.
So when you POSTED the values the value on make_text was empty string. So if you fire the trigger after the for loop then it will work.
function setDropDown() {
var index_name = document.getElementsByName('ForceSelection')[0].selectedIndex;
var others = document.querySelectorAll('.secondary');
for (var i = 0; i < others.length; i++) {
others[i].selectedIndex = index_name;
}
$("#Qualifications").trigger("change");
}
function setTextField(ddl) {
document.getElementById('make_text').value = ddl.value;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post">
<div><b>Primary dropdown:</b>
<select name="ForceSelection" id="ForceSelection" onChange="javascript:return setDropDown();">
<option value="" selected>Select</option>
<option value="treatmentid1">treatmentname1</option>
<option value="treatmentid2">treatmentname2</option>
</select>
</div>
<div>
<b>Other dropdown 1</b>:
<select class='secondary' id="Qualifications" name="Qualifications" onChange="setTextField(this)">
<option value="select">select</option>
<option value="treatmentid1">treatmentname1</option>
<option value="treatmentid2">treatmentname2</option>
</select></div>
<input id="make_text" name="make_text" value="" />
<div> <b>Other dropdown 2</b>:
<select class='secondary' id="Qualifications2" name="Qualifications2">
<option value="select">select</option>
<option value="treatmentid1">treatmentname1</option>
<option value="treatmentid2">treatmentname2</option>
</select>
</form>
I have to say that I don't see any need to use a hidden input text to POST data to PHP because you can just post the value of the <select> and retrieve it in PHP like this $force = $_POST["ForceSelection"];.
Otherwise, if you want to continue what you started, you can change your setDropDown() function to this :
function setDropDown() {
#Get the selected value of the ForceSelection select :
var index_name = $('#ForceSelection').val();
#Change the value of the other secondary select :
$(".secondary").each(function( index ) {
$(this).val(index_name).change();//This will change the value and trigger the change event.
});
}

Select option is not updated 'selected' property in HTML web page

Please, explain how can I change 'selected' property of option?
E.g.:
<select id="lang_select">
<option value="en" selected="selected">english</option>
<option value="ar">العربية</option>
<option value="az">azərbaycanlı</option>
<option value="bg">български</option>
<option value="ca">català</option>
<option value="cs">český</option>
<!-- some data cut -->
</select>
So, if I change the drop down list value nothing is changed in html-data.
Why?
Only if I try to force reload the property using jQuery it works.
$(document).on('change',"select",function(){
var i = $(this)[0].selectedIndex;
var ch = $(this).children().each(function(index){
$(this).prop('selected',index == i);
if (index == i) {
$(this).attr('selected','selected');
} else {
$(this).removeAttr('selected');
}
});
});
Why? How can I avoid this? Is it possible to change "selected" using pure html?
EDIT
I namely want this attrbute in html tag because I need to save and restore the part of this html-code in future.
Updated, substituted .attr("selected", true) for .prop("selected", true)
Note , value of selected attribute returns true or false , not "selected".
Try utilizing selector $("option[value=" + this.value + "]", this) , set property selected to true , .siblings() to remove selected attribute from option not selected
$(document).on("change","select",function(){
$("option[value=" + this.value + "]", this)
.attr("selected", true).siblings()
.removeAttr("selected")
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="lang_select">
<option value="en" selected="true">english</option>
<option value="ar">العربية</option>
<option value="az">azərbaycanlı</option>
<option value="bg">български</option>
<option value="ca">català</option>
<option value="cs">český</option>
<!-- some data cut -->
</select>
It's not change the html itself but it does change the value of the select
$('select').change(function(){
$('#result').html($(this).val());
}).trigger('change');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="lang_select">
<option value="en" selected="selected">english</option>
<option value="ar">العربية</option>
<option value="az">azərbaycanlı</option>
<option value="bg">български</option>
<option value="ca">català</option>
<option value="cs">český</option>
<!-- some data cut -->
</select>
<hr />
<div id="result"></div>
Use the val() method. So in your case, $("#lang_select").val('en'); selects the english option. And by the way if you want the first option to be selected you don't need the selected="selected". By default the first option is automatically selected.

HTML Select Box, remove option through javascript 'None' option appears

I have the following HTML Select Box
<select id="orderByItem" name="orderByItem">
<option selected="" value="Status">Status</option>
<option value="ABCD">ABCD</option>
</select>
'Status' option is selected. Now when I remove the 'ABCD' option through javascript it gets replaced by None
This is the javascript I use
$("#orderByItem option[value='ABCD']").remove();
I am not sure how 'None' gets into the select, and this is causing major problems.
Try this http://jsfiddle.net/1q97q8z6/1/
HTML
<select id="orderByItem" name="orderByItem">
<option selected="" value="Status">Status</option>
<option value="Status2">Status2</option>
<option value="ABCD">ABCD</option>
</select>
<input type="button" name="but" id="but" Value="click"/>
JS
$( "#but" ).click(function() {
$("#orderByItem option[value='ABCD']").remove();
$("#orderByItem").get(0).selectedIndex = 1;
var tempVal = $("#orderByItem").val();
alert(tempVal);
});
var x = document.getElementById("orderByItem");
x.remove(x.selectedIndex);
Reference w3schools

Show/hide dropdown based on Multiselect selection

I have the following HTML.
<select id="segment_c" name="segment_c[]" multiple="true" size="6" style="width:150" title="" tabindex="0">
<option label="" value="" selected="selected"></option>
<option label="Mobile1" value="Mobile1">Mobile1</option>
<option label="Mobile2" value="Mobile2">Mobile2</option>
<option label="Mobile3" value="Mobile3">Mobile3</option>
</select>
<select name="Mobile1_c" id="Mobile1_c" title="">
<option label="" value=""></option>
<option label="Samsung" value="Samsung">Samsung</option>
<option label="Nokia" value="Nokia">Nokia</option>
</select>
<select name="Mobile2_c" id="Mobile2_c" title="">
<option label="" value="" selected="selected"></option>
<option label="Samsung" value="Samsung">Samsung</option>
<option label="Nokia" value="Nokia">Nokia</option>
</select>
<select name="Mobile3_c" id="Mobile3_c" title="">
<option label="" value=""></option>
<option label="Motorola" value="Motorola">Motorola</option>
<option label="Nokia" value="Nokia">Nokia</option>
</select>
This is a Multiselect List
I needed help in jQuery in the following.
I would like to iterate the multiselect (id="segment_c") such that if value="Mobile1" and value="Mobile2" and value="Mobile3" is selected then show dropdown with id="Mobile1_c" and id="Mobile2_c" and id="Mobile3"
Basically show/hide dropdown based on value selected in multiselect.
Thanks in advance.
John
Notice that values from multiple select are stored inside an array.
$(document).ready(function () {
function hideAll() {
$('#Mobile1_c,#Mobile2_c, #Mobile3_c').hide();
}
hideAll();
$('#segment_c').change(function() {
hideAll();
var val = $(this).val();
if (val == "") {
hideAll();
} else {
for (var i = 0; i <= val.length; i++) {
$('select[name*="' + val[i] + '"]').show();
}
}
});
});
http://jsfiddle.net/4nuAW/2/
#Freak_Droid almost has it but I can't comment for lack of rep.
with that implementation you don't need all three selected as requested
$('#Mobile1_c,#Mobile2_c, #Mobile3_c').toggle();
$('#segment_c').change(function(){
//val returns an array not a jquery object so dont prefix with a $
var val = $(this).val();
//you may want a more robust check here
if(val.length === 3){
$('#Mobile3_c').show();
}else{
$('#Mobile3_c').hide();
}
});
http://jsfiddle.net/VuN78/1

HTML setting default text on select

I have a select element of the form:
<select id="test" name="test">
<option value="blah">Test1</option>
<option value="blah">Test2</option>
.
<option value="blah">Testn</option>
</select>
I want to display the text "Select a test" as default.
I know the way of doing this is to set a new option
<option selected="selected">Select a test</option>
at the top. But I'm looking for some other way where I don't have to use the tag.
Is it possible through javascript (jQuery will also do)?
I've done this with a dummy entry in the past...
HTML
<select id="test" name="test">
<option value="0">Select an option...</option>
<option value="blah">Test1</option>
<option value="blah">Test2</option>
<option value="blah">Test3</option>
<option value="blah">Test4</option>
<option value="blah">Test5</option>
</select>​
Javascript
​$("#test").on("change", function() {
if ($(this).val() != "0") {
$("option[value=0]", this).remove();
}
});​​​​​​
Here's a working example on jsFiddle...
http://jsfiddle.net/97Bqr/
The "Select an option" option is removed as soon as you select something else.
Here's a plain js solution:
var selecttest = document.querySelector('#test');
selecttest.insertBefore(new Option('select a test'),selecttest.firstChild);
selecttest.selectedIndex = 0;

Categories