I want to assign a session ID (this will be hidden) whenever the first select dropdown is used. The session ID is the number 300, 301, etc. after the "day".
When a user selects something from the "preferred" dropdown it should assign the "300" value to the "sessionid" dropdown and simultaneously change the value of the "day" dropdown (which works already btw)
How do I do implement it properly?
Please see code below:
<select id="preferred" class="preferred" name="preferred">
<option value="">- Select -</option>
<option value="Mountain Dew">Mountain Dew</option>
<option value="Seven Up">Seven Up</option>
</select>
<select id="day" class="day" name="day">
<option value=""></option>
</select>
<select id="sessionid" class="sessionid" name="sessionid">
<option value=""></option>
</select>
$(function() {
var selectValues = {
"Mountain Dew": {
"Monday": "300"
},
"Seven Up": {
"Tuesday": "301"
}
};
var $preferred = $('select.preferred');
var $day = $('select.day');
var $sessionid = $('select.sessionid');
$preferred.change(function() {
$day.empty().append(function() {
var output = '';
$.each(selectValues[$preferred.val()], function(key, value) {
output += '<option value="' + key + '">' + key + '</option>';
});
return output;
});
}).change();
});
example : http://jsfiddle.net/creativemix/5ZWrE/2/
Try this if you want to set the value of session id dropdown. Include this after setting the output variable in your fiddle.
$sessionid.empty()
.append($("<option></option>")
.attr("value",value)
.text(value));
Here's a link to the fiddle.
But, as others already suggested, why not use a hidden text field to store the value?
To store the value in a hidden field,
<input type="hidden" id="hdnSessionId" />
And add this to the script.
$('#hdnSessionId').val(value);
You can use Element.id = 'id' to set an id in javascript.
https://developer.mozilla.org/en-US/docs/Web/API/Element.id
In your code that would probably be something like this at the point where you want to assign the id:
$sessionid[0].id = $day.val();
But please note an id must start with a letter and numbers are generally bad practice even if it does work.
Putting the value you need in a hidden field is probably preferable over this solution.
Related
I have this sample:
link
CODE HTML:
<select name="card_type" id="card_type" class="card-sel com-c select-full">
<option value="visa">Visa</option>
<option value="mastercard">Mastercard</option>
<option value="discovery">Discovery</option>
<option value="maestro">Maestro</option>
</select>
CODE JS:
$( document ).ready(function() {
var stateSelectValue = "Mastercard"; //this value in my site returns a dynamic type of card
console.log("primul log" + stateSelectValue);
if(stateSelectValue)
{
console.log("al doilea log" + stateSelectValue); $("#card_type").val(stateSelectValue).attr("selected","selected").trigger("change");
console.log("al treilea log" + stateSelectValue);
}
$( ".com-c" ).change(function() {
var data= $(this).val();
console.log(data);
});
});
Perhaps the example understand what they want to do.
Basically when they are receiving a value in the variable stateSelectValue to look if there is value in that list and make selected.
For example IF:
var stateSelectValue = "Mastercard";
then
<option value="mastercard" selected="selected">Mastercard</option>
and so on...
Can you help me to solve this problem please?
Thanks in advance!
First as I have already commented, you do not need to set attribute selected and trigger change function.
$("#card_type").val(stateSelectValue)
This should be enough.
Second, if you do this change, still it will not work. W
Why?:
Variable value:
var stateSelectValue = "Mastercard";
is not equal to value of option
<option value="mastercard">Mastercard</option>
Updated Codepen
You were all good just one typo mistake, your selected value was in capital i.e "Mastercard" where as in option value it was "mastercard". But in simple way doing below was enough without trigger change event.
var stateSelectValue = "mastercard";
$("#card_type").val(stateSelectValue)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<select name="card_type" id="card_type" class="card-sel com-c select-full">
<option value="visa">Visa</option>
<option value="mastercard">Mastercard</option>
<option value="discovery">Discovery</option>
<option value="maestro">Maestro</option>
</select>
This question already asked some . please refers the below link:
JQuery setting the selected attribute on a select list
$(document).ready(function () {
$('#card_type').val("mastercard"); // Select by value
text1 = "Maestro";
$("#card_type option:contains(" + text1 + ")").attr('selected', 'selected'); // select by text
});
Good day community,
I have an ASP.NET MVC4 project, where on edit page I'm use jquery script. But I have a problem to display elements on the page.
Here is my dropdown's HTML markup before changes:
<select id="ProgramId" name="ProgramId"><option value=""></option>
<option value="1">testrtu1</option>
<option value="2">testrtu2</option>
<option value="3">testtsi</option>
<option selected="selected" value="4">testrtu3</option>
</select>
And here is after jquery changes
<select id="ProgramId" name="ProgramId"><option value=""></option>
<option value="1">testrtu1</option>
<option value="2">testrtu2</option>
<option selected="selected" value="4">testrtu3</option>
</select>
But it's display on the page not a selected element testrtu3, always display first element. And when I click save button saved my first value.
Here is my jQuery function:
$(document).ready(function () {
var values = [];
$(".checkboxUniversities:checked").each(function () {
values.push($(this).val());
});
$.getJSON('/Administrator/ProgramList/' + values, function (data) {
alert('Return json result new information');
var items = '<option disabled>Select a Program</option>';
$.each(data, function (i, program) {
items += "<option value='" + program.Value + "'>" + program.Text + "</option>";
});
$('#ProgramId').html(items);
});
//var selectedElement = $("#ProgramId").find(":selected").text();
});
I guess I need somehow add selected value when create my dropdown inside jquery, or after creating, but I don't know how. Can anybody help me?
Before appeding options to your dropdown you have to save selected index or text in variable and use it further.
Sample Code:
<select id="ProgramId" name="ProgramId"><option value=""></option>
<option value="1">testrtu1</option>
<option value="2">testrtu2</option>
<option selected="selected" value="4">testrtu3</option>
</select>
<input id="click" type="button" value="click me"/>
$(document).ready(function(){
var option = '<option value="1">testrtu1</option><option value="2">testrtu2</option><option value="3">testtsi</option><option value="4">testrtu3</option>';
$("input#click").click(function(){
var selInx = $("select[name='ProgramId'] option:selected").index();
$('#ProgramId').html(option);
$('select#ProgramId').prop('selectedIndex', selInx);
});
});
DEMO FIDDLE
NOTE: As we cannot connect to your backend code to get options hardcoded in code itself and on click of button dropdown will be replaced with latest options and will update the selected index based on first one. You can use either selectedindex or text based on your requirement.
I have a simple jquery script set up to calculate the cost of services for a user. the script works great! However, my database side calls to go another route. How can I use the actual output of the option for the calculation rather than the value
jquery:
var $selections = $('#selections');
var $selects = $("select").change(function () {
var total = 0;
$selections.empty();
$selects.each(function () {
var $selected = $(this).find("option:selected");
var price = parseFloat($selected.data("price")) || 0;
total += price;
if($selected.val() !== ''){
$('<li />', {
text: $selected.val() + $(this).parent().clone().children().remove().end().text()+" " + $selected.data("price")
}).appendTo($selections)
}
})
$(".summary").text('Est. Total $' + total);
})
HTML with PHP:
<select name="rooms" id="Areas">
<option value="" selected="selected">0</option>
#foreach ($room as $rooms)
<option data-price="{{ $rooms->pr_clean }}" value='{{ $rooms->room }}'>{{ $rooms->room }}</option>
#endforeach
</select>
Basically I want to be able to add something different in the value field to go into the database but still calculate how many room they are wanting to select using {{ $rooms->room }}
here is a fiddle with the basic idea of how my script works. http://jsfiddle.net/arunpjohny/xf9Fp/
In jQuery .val() will give you the option's value when defined inside the <option> tag. If there is no value in the option it will get the text of the option.
<option value="" selected="selected">0</option>
^------^ ^
value text
So because some of your options have value="", jQuery's .val() will get that value, which is a empty string. Without value="" inside the <option> tag .val() would give you 0.
To be sure you always get the text of the option you can use .text().
So use this: if($selected.text() !== ''){
So I am writing an app that requires an address input and I have a select element for the user to select the state/province. It needs to support the US and Canada so it has nested optgroups to separate those out and a single, first level option as it's default value. Here is a basic example:
<select name="state" id="state">
<option class="co" value="" data-placeholder="true" disabled selected>Choose your state...</option>
<optgroup label="United States">
<option class="co" value="AL">Alabama</option>
<option class="co" value="AK">Alaska</option>
<option class="co" value="AZ">Arizona</option>
</optgroup>
<optgroup label="Canada">
<option class="co" value="AB">Alberta</option>
<option class="co" value="BC">British Columbia</option>
<option class="co" value="MB">Manitoba</option>
</optgroup>
Now I need to programmatically select the option that matches input from an external source and I want to check for a match based on both the value of the option element or its text. Whichever option is a match would then be set as the selected option. I know you can set the selected option by value using
$("#state").val(myValue)
and I know you can set an option based on text in this way
var myText = "The state I want.";
$("#state").children().filter(function() {
return $(this).text() == myText;
}).prop('selected', true);
Is there a clean way to do this without having to run through each child and checking if it's an optgroup and then running through all its children to check for a match? Is there an easy way through jQuery to combine the value and text methods of setting the selected option?
One other complication, I am going to be doing this within an external jQuery plugin. Within the function I need to modify I have the select element as a variable
$element
so I need a way to do it kind of like this if possible:
$element.descendents(":option").filter(function() {
//do the selecting here
}).prop('selected', true);
If you want to select by the option value, use the value selector:
var myText = "AZ";
$('#state option[value="' + myText + '"]').prop('selected', true);
If you want to search by the option's label, use a filter:
var myText = "Arizona";
$('#state option').filter(function () { return $(this).html() == myText; }).prop('selected', true)
Solved. Since I already had my element passed to a function as a jQuery variable, $element, I couldn't just use the standard selector in the form of:
$("#state option").filter(
// filter function
).prop('selected', true);
After a lot of trying, I got this and it works:
function functionIHadToChange($element, value) {
// other code
$element.find("option").filter(function(){
return ( ($(this).val() == value) || ($(this).text() == value) )
}).prop('selected', true);
}
I am not sure I understood completely your question but I am attempting to answer it in this fiddle
The trick being that you can select it by setting the value of the select box directly
$("#state").val( a_value );
You can set it by $("#select_id").prop("selectedIndex", 3); // Select index starts from zero.
Read here for example this.
$element = $('select#state');
$options = $element.find('option');
$wanted_element = $options.filter(function () {
return $(this).val() == "Alabama" || $(this).text() == "Alabama"
});
$wanted_element.prop('selected', true);
Would be one way to do it.
But i would guess, without knowing the exact internas of the .find() method, in the end jQuery will use at least two loops itself to perform this...
I'm late here but for future visitor, easiest way to do that is :
html
<select name="dept">
<option value="">This doctor belongs to which department?</option>
<option value="1">Orthopaedics</option>
<option value="2">Pathology</option>
<option value="3">ENT</option>
</select>
jQuery
$('select[name="dept"]').val('3');
Output: This will active ENT.
Very simple question I hope.
I have the usual <select> box like this
<select id="select">
<option value="1">this</option>
<option value="2">that</option>
<option value="3">other</option>
</select>
I can get the selected value (by using $("#select").val()) and the selected item's display value (by using $("#select :selected").text().
But how can I store like an additional value in the <option> tag? I would like to be able to do something like <option value="3.1" value2="3.2">other</option> and get the value of the value2 attribute (which would be 3.2 in the example).
HTML Markup
<select id="select">
<option value="1" data-foo="dogs">this</option>
<option value="2" data-foo="cats">that</option>
<option value="3" data-foo="gerbils">other</option>
</select>
Code
// JavaScript using jQuery
$(function(){
$('select').change(function(){
var selected = $(this).find('option:selected');
var extra = selected.data('foo');
...
});
});
// Plain old JavaScript
var sel = document.getElementById('select');
var selected = sel.options[sel.selectedIndex];
var extra = selected.getAttribute('data-foo');
See this as a working sample using jQuery here: http://jsfiddle.net/GsdCj/1/
See this as a working sample using plain JavaScript here: http://jsfiddle.net/GsdCj/2/
By using data attributes from HTML5 you can add extra data to elements in a syntactically-valid manner that is also easily accessible from jQuery.
To me, it sounds like you want to create a new attribute? Do you want
<option value="2" value2="somethingElse">...
To do this, you can do
$(your selector).attr('value2', 'the value');
And then to retrieve it, you can use
$(your selector).attr('value2')
It's not going to be valid code, but I guess it does the job.
I made two examples from what I think your question might be:
http://jsfiddle.net/grdn4/
Check this out for storing additional values. It uses data attributes to store the other value:
http://jsfiddle.net/27qJP/1/
HTML
<Select id="SDistrict" class="form-control">
<option value="1" data-color="yellow" > Mango </option>
</select>
JS when initialized
$('#SDistrict').selectize({
create: false,
sortField: 'text',
onInitialize: function() {
var s = this;
this.revertSettings.$children.each(function() {
$.extend(s.options[this.value], $(this).data());
});
},
onChange: function(value) {
var option = this.options[value];
alert(option.text + ' color is ' + option.color);
}
});
You can access data attribute of option tag with option.[data-attribute]
JS Fiddle : https://jsfiddle.net/shashank_p/9cqoaeyt/3/
HTML/JSP Markup:
<form:option
data-libelle="${compte.libelleCompte}"
data-raison="${compte.libelleSociale}" data-rib="${compte.numeroCompte}" <c:out value="${compte.libelleCompte} *MAD*"/>
</form:option>
JQUERY CODE:
Event: change
var $this = $(this);
var $selectedOption = $this.find('option:selected');
var libelle = $selectedOption.data('libelle');
To have a element libelle.val() or libelle.text()
To store another value in select options:
$("#select").append('<option value="4">another</option>')