Set an option as selected from select dropdown using jquery - javascript

I have a select dropdown list having n number of options, i want on page load, option which i selected earlier should get selected in dropdown using jquery :
Here is my html code :
<select id="myList">
<option value="1">first</option>
<option value="2">second</option>
<option value="3">third</option>
</select>
<input type="hidden" value="1" id="hiddenoptionid" />
Here is my jquery code :
$(document).ready(function() {
var projectId=document.getElementById("hiddenoptionid").value;
$("#myList option[value="+projectId+"]").attr("selected", "selected");
});
$("#projectlist").on('change', function() {
var id = $(this).val();
document.getElementById("hiddenoptionid").value=id;
location.reload();
});
Thanks.

You can use like,
$(document).ready(function(){
$("#projectlist").val($("#hiddenoptionid").val());
});
Note that, if you reload the page, $("#hiddenoptionid").val() will get reset to 1 again. If you want to retain that value, use cookies for that

Related

selected option doesn't select using JQuery

I'm working on my web appliction using JQuery. My select option menu doesn't print selected option.
$(function() {
$(document).on('click', ".class", function() {
if ($(this).attr("id") == "mySelect")
$("#mySelect").val($('#mySelect').val());
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="mySelect" class="form-control form-control-sm class">
<option id="mySelectOptionIndex0" value=0 selected> A </option>
<option id="mySelectOptionIndex1" value=1> B </option>
<option id="mySelectOptionIndex2" value=2> C </option>
My code is working and select correct option but it doesn't print the selected option. Using browser I see that selected attribute is righty added.
I tried using e.preventDefault();, using .prop(selected, true) instead .attr() but without soluton. How can I solve? Thanks
try it to access option value or option html :
$(function() {
$(document).on('change', ".class", function() {
var optionSelected = $("option:selected", this);
var selectedText = $(optionSelected).html();
var valueSelected = this.value;
console.log(selectedText, valueSelected);
});
});

On Page Load select option jquery like user behaviour (Real Time Change Event Fire)

I want to autoselect select box option on page load. Here is my code which is not working.
jQuery(document).ready(function(){
jQuery(".configure_supre_select_1 option:eq(1)")
.attr('selected',true)
.trigger('change');
});
You are triggering the selected option instead of the select - also use prop
$(function(){
$(".configure_supre_select_1 option:eq(1)").prop('selected',true);
$(".configure_supre_select_1").trigger('change');
});
Alternatively set the value
$(function(){
$(".configure_supre_select_1").val("firstOptionValue").change();
});
$(function() {
$(".configure_supre_select_1").on("change", function() {
$(".optdiv").hide();
var val = this.value;
if (val) {
$("#" + val.replace("OptionValue", "")).show();
}
});
$(".configure_supre_select_1").val("firstOptionValue").change();
$(".configure_supre_select_2 option:eq(1)").prop('selected',true);
$(".configure_supre_select_2").trigger('change');
});
.optdiv {
display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select class="configure_supre_select_1">
<option value="">Please select</option>
<option value="firstOptionValue">First</option>
<option value="secondOptionValue">Second</option>
</select>
<div class="optdiv" id="first">First is selected</div>
<div class="optdiv" id="second">Second is selected</div>
<hr />
Here I use your version <br/>
<select class="configure_supre_select_2">
<option value="">Please select</option>
<option value="firstOptionValue">First</option>
<option value="secondOptionValue">Second</option>
</select>
For make real time click by jquery i added below code. It used "Event".
For change select option on page load i use below code:
jQuery(".configure_supre_select_1").val(jQuery(".configure_supre_select_1 option:eq(1)").val()).change();
and then make it real time changing i use below code:
var dropdown = $("SelectAttributeId"); // Id of select box
var element = dropdown;
var event = 'change';
var evt = document.createEvent("HTMLEvents");
evt.initEvent(event, true, true );
return !element.dispatchEvent(evt);

how do set select option 'selected' after load page?

i have code html
<select class="mySelect">
<option value="1" >Date</option>
<option value="2">Helpfulness</option>
</select>
Updated
So when the user selects 'Helpfulness' and reloads page then
option Helpfulness should be 'selected'. and if 'Date' is choosen
then reloaded page should set Date 'selected'.
thank for help!
Use .val() to set the value to 2 as follows:
$(function() {
$('.mySelect').val( 2 );
});
$(function() {
$('.mySelect').val( 2 );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select class="mySelect">
<option value="1">Date</option>
<option value="2">Helpfulness</option>
</select>
UPDATE
Per your updated question use localStorage or cookies to hold the selected value. When the page refreshes, check for the cookie or localStorage value and load it.
$(function() {
$('.mySelect').on('change', function() {
$.cookie('mySelect', this.value);
});
$('.mySelect').val( $.cookie('mySelect') || 1 );
});
DEMO
For most default value, it would be easy to set on html markup directly like :
<select class="mySelect">
<option value="1" >Date</option>
<option value="2" selected>Helpfulness</option>
</select>
Otherwise, use jQuery .prop code here :
$( function () {
$('.mySelect option[value="2"]').prop('selected', true);
});
Set the value in val() and change() function
jQuery(window).on('load', function () {
$('.mySelect').val(2).change();
});

Database value cannot get it to the Dropdownlist jQuery

In my database there's a column, name is Sequence & it consist of numbers(int). In my application's edit function I need to show that selected number in my jQuery dropdown list.
In my AJAX call I sent ProductId and get the specific row.
Html Control
<select class="form-control" id="drpsequence"></select>
My jQuery dropdown
$("#drpsequence option:selected").append($("<option></option>").val(msg._prodlng[0].Sequence).text(msg._prodlng[0].Sequence));
In the above code msg._prodlng[0].Sequence comes as selected number
I'm not sure what you are trying to do but it looks like you are adding an <option> tag into another <option> tag which is most likely not what you want.
If the returned value already exists as a selected option:
$("#drpsequence").val(msg._prodlng[0].Sequence).prop('selected', true);
Or, if you need to add an option:
var opt = $("<option>")
.val(msg._prodlng[0].Sequence)
.text(msg._prodlng[0].Sequence);
$("#drpsequence").append(opt);
Snippet example:
// foo --> select
$('#foo').val('baz').prop('selected', true);
$('#bim').click(function(){
$('#foo').append('<option id="boop" value="boop">boop</option>'); //<-- or loaded value
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="foo">
<option>-- select --</option>
<option id="bar" value="bar">bar</option>
<option id="baz" value="baz">baz</option>
</select>
<button id="bim">Add an option</button>
You need to do one of following.
Either find that option and make that selected = true like this.
$("#sel option").each(function(i) {
if ($(this).val() == "Orange") $(this).attr("selected", "true");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="sel">
<option>Apple</option>
<option>Orange</option>
<option>Banana</option>
</select>
Or if that option is not found then add and make that selected = true.
Like the one, which you had in your question.

Remove the first select option

I'd like to remove the first option of an select tag when I click on the select tag. Is this possible?
I don't want to see the first option after that click.
Thanks for any help.
You can remove the first option on click with jQuery.
$(document).on('click', 'select', function() {
$(this).find('option').get(0).remove();
});
This simply removes the first option of a select tag on click. You need to add an if statement to check if it was already removed.
There's also a simple no-javascript solution:
<select>
<option style="display: none">--Choose--</option>
<option>Cheese Cake</option>
<option>Hot Pockets</option>
<option>Sausage</option>
<option>Cookies</option>
<option>Bacon</option>
</select>
(Copied from the comments from #chipChocolate.py)
If you use bootstrap add placeholder attribute in your select.
If your not
<select required>
<option value="" disabled selected>Select your option</option>
<option value="1">1</option>
</select>
// to remove first...
document.getElementById("element_id_str").options[0].remove();
//to remove the lot...
document.getElementById("element_id_str").options.length = 0;
<select required>
<option value="" disabled selected hidden>Select your option</option>
<option value="1">1</option>
</select>
Probably you just want this:
<select required>
<option value="" hidden>Select your option</option>
<option value="1">1</option>
</select>
A very naive way of doing this:
$("#selector").change(function(evt) { //listen to changes of selection
var theElement = $(this);
if (!theElement.data("selected")) { //check if flag is not set
theElement.children("option")[0].remove(); //remove 1st child
theElement.data("selected", true); //set flag, so it doesn't continue removing items for every change
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="selector">
<option>--Choose--</option>
<option>Apple</option>
<option>Banana</option>
<option>Papaya</option>
</select>
If you want to remove the first option use this
$(document).ready(function()
{
$("select").children().first().remove();
});
If you want to remove the first option after clicking on the select box use this
$(document).ready(function()
{
var removed=false;
$(document).on("click","select",function()
{
if(!removed)
{
$(this).children().first().remove();
removed=true;
}
});
});
Javascript:
document.getElementById("SelectId")[0].remove();
Get the first option in the select and remove it.
I had the same problem, but the solutions above just work with one form, not with many. I added some extra code in order to validate it for many in your form:
$(document).ready(function()
{
$(document).on("change","select",function()
{
var x = $(this).children().first().attr("name");
var n = x.localeCompare("todelete");
if (n == 0)
$(this).children().first().remove();
});
});
Where "todelete" is the name for all first elements [0] defined inside the
Please select value //all first elem must have the same name
"> //the others another name (can be the same BUT not "todelete")
You need the id or class to remove the item. While testing and debugging I found 'option:first' fails to remove the item. But 'option:first-of-type' always does the work. You can get more info about 'first-of-type' here :first-of-type
$("#ID_or_.CLASS option:first-of-type").remove();

Categories

Resources