form select option dynamic attr - javascript

I need to make Select name with option value, to select a specific value or index. the data where comes from db in a value "{{design}}".
I do get the value currectly, but I dont manage to set "selected" on the currect option value.
here is the code:
console.log("{{design}}");
$(document).ready(function () {
var options = $('select').children('option');
var size = $('select').children('option').length;
for (i=0;i<size;i++)
{
if ( options[i].innerHTML==="{{design}}")
{
options.selectedIndex=i;
}
}
});
the html is :
<select name="design" required id="design" >
<option value="1">flowers</option>
<option value="2">classic</option>
<option value="3">roses</option>
</select>
I need to make to currect {{design}} value, lets say it's 2, so it will be <option value="2" selected>classic</option>`
thanks!
SOLVED
Hi, found the solution to the issue, if anyone eles goes into trouble.
$(document).ready(function () {
var options = $('select').children('option');
var size = $('select').children('option').length;
for (i=0;i<size;i++)
{
if ( $('select').children('option')[i].value === "{{design}}")
{
$('select').children('option')[i].selected=true;
}
}
});
the currect way is to find the right option value and then-> [i].selected=true
goodluck

Try this
var selectedvalue=2; //option with value 2 should be selected
$("#design option[value=selectedvalue]").attr("selected","selected");
Hope this helps...

If I understood right, you are on the right path just taking a minor detour. Try this:
if ( options[i].innerHTML==="{{design}}")
{
options.attr('selected', 'selected');
}
The example of .each() usage:
$(document).ready(function(){
$('select option').each(function(i){
if( i.value === "{{design}}"){
$(this).attr('selected','selected');
}
});
});

try this:
$(document).ready(function(){
$('select option').each(function(i){
//if this option contains the word "{{design}}" Then this is selected
if( $(this).html().indexOf("{{design}}") != -1)
$(this).attr('selected',true);
});
});

Related

Selected option (HTML dropdown list) isn't saved to the localStorage

I'm trying to save the "selected" option from the <select> HTML tag to the localStorage, so when I refresh the page the last selected option is selected. I can see that it's saved in the console.log, but it's not working on the page load. How can I make it work?
<select class="multiply_ing">
<option value="0.5">0.5x</option>
<option value="1" selected>1x</option>
<option value="1.5">1.5x</option>
<option value="2">2x</option>
<option value="2.5">2.5x</option>
<option value="3">3x</option>
<option value="4">4x</option>
<option value="5">5x</option>
<option value="6">6x</option>
<option value="8">8x</option>
<option value="10">10x</option>
</select>
<p class="portion" data-val="<?php echo $portion; ?>"></p> <!-- PHP Generated value, let's just say it's "1" -->
<div class="ingredient">
<p data-val="1"></p>
<p data-val="5"></p>
<p data-val="6"></p>
</div>
<script>
$(function() {
$(".multiply_ing").on("change", function() {
let multiply_val =+ this.value;
$('.ingredient p:nth-child(1)').each(function() {
let ing =+ this.dataset.val;
this.innerHTML = ing * multiply_val;
});
$('.multiply_ing option').each(function() {
let multi_opt = $(this).val();
let portion = parseFloat(document.querySelector(".portion").dataset.val);
let portions = multi_opt * portion;
});
let portion =+ document.querySelector(".portion").dataset.val;
document.querySelector(".portion").innerHTML = portion * multiply_val;
}).change();
jQuery($ => {
let $select = $('.multiply_ing');
// get on load
$select.val(localStorage.getItem('value') || 1); // 1 = default value
$select.on('change', e => {
localStorage.setItem('value', e.target.value);
});
});
});
</script>
Note: there is more code than in this example, but it's irrelevant to the problem.
To do what you require you can just use val() to both get and set the value of the select when required:
jQuery($ => {
let $select = $('.multiply_ing');
// get on load
$select.val(localStorage.getItem('value') || 1); // 1 = default value
$select.on('change', e => {
localStorage.setItem('value', e.target.value);
});
});
Also note that the each() in your example is doing nothing and can be removed. In addition, multiply_val is not defined anywhere.
As a general rule, if you're going to incur the performance penalty of loading jQuery in to the DOM, then you're better off making use of it everywhere. Mixing JS and jQuery just leads to confusion.
To store value in localStorage you have to use key value pair like this localStorage.setItem('selectedValue',yourValue) and to get value use key to access the saved value localStorage.getItem('selectedValue')
$(function() {
$('.multiply_ing').change(function() {
localStorage.setItem('selectedValue', this.value);
});
if(localStorage.getItem('todoData')){
$('.multiply_ing').val(localStorage.getItem('selectedValue'));
}
});
for working code you can see this demo

How do I show a message for a specific dropdown selection using javascript?

I would like to show a message when someone makes a specific selection from an HTML dropdown list. I have this so far:
<select name="configoption[56]" onchange="recalctotals()">
<option value="235"">USA</option>
<option value="206">Europe</option>
</select>
<span class="message">You selected USA!</span>
And the script:
$(document).ready(function() {
$('#configoption[56]').change(function() {
var selectedValue = $('#configoption[56]').find(":selected").text();
if ( selectedValue == '235' ) {
$('.message').show();
} else {
$('.message').hide();
}
});
});
The above does not appear to be working for me, any suggestions? I would also like to be able to show the message on multiple selected values.
Well your .change function is specifically binded to an element with id="configoption[56]" So just add id to your select element as below
<select name="configoption[56]" id="configoption[56]" onchange="recalctotals()">
//Options
</select>
UPDATE
As per #T.J.Crowder's suggestion on invalid selector I would like to modify a slight change on the id. You can use configoption56 as id and write your select.change as follows:
<select name="configoption[56]" id="configoption56" onchange="recalctotals()">
<!--Options-->
</select>
.change
$('#configoption56').change(function() {
//other codes
});
$('#configoption[56]') is looking for an element with the id, not name, configoption[56] (or it would be, but the selector is invalid, you'd have to escape those brackets).
To use the name:
$('select[name="configoption[56]"]')...
Separately, you can just use val, you don't have to use find to get the selected option. You can also use toggle for show/hide:
$(document).ready(function() {
$('select[name="configoption[56]"]').change(function() {
$('.message').toggle($(this).val() == '235');
});
});
Re your comment about toggling based on || and two values:
$(document).ready(function() {
$('select[name="configoption[56]"]').change(function() {
var value = $(this).val();
$('.message').toggle(value == '235' || value == '123');
});
});
I should be doing it like this: http://jsfiddle.net/nmn17cr6/
HTML:
<select name="configoption[56]" id="configoption" onchange="recalctotals()">
<option value="1">Dummy</option>
<option value="235">USA</option>
<option value="206">Europe</option>
</select>
<span class="message">You selected USA!</span>
CSS:
.message {
display:none;
}
jQuery:
$(document).ready(function() {
$('#configoption').change(function() {
var selectedValue = $(this).val();
if ( selectedValue == '235' ) {
$('.message').show();
} else {
$('.message').hide();
}
});
});
Your approach needs a little modification. All you had to do these changes
$(document).ready(function() {
$("select[name=configoption[56]]").change(function() { // change jquery selector for name
var selectedValue = $('#configoption[56]').val(); // and val to get the value
if ( selectedValue == '235' ) {
$('.message').show();
} else {
$('.message').hide();
}
});
});
And with the same jQuery code. below has to be
<select name="configoption[56]" >
// onchange="recalctotals()"> was not required

Populate input text box based on drop down select box in Jquery

I have a drop down select box and input text box. Select box display my categories and its look like this:
<select id="category" name="category">
<option value="">Please select...</option>
<option value="1">Category-1</option>
<option value="2">Category-2</option>
<option value="3">Category-3</option>
<option value="4">Other</option>
</select>
Input text box is like this:
<input type="text" id="otherCategory" name="otherCategory" value="" style="display: none;">
My question is. when an user select only "Other" from dropdown then I need to populate the input text.
I tried it something like this:
$(document).ready(function() {
$('#category').change(function() {
var myValue = $(this).val();
var myText = $("#category :selected").text();
if (myText != '' AND myText == "Other") {
$("#otherCategory").show();
}
});
});
But I couldn't get it to work. Can anybody tell how I figure this out.
NOTE: my dropdown select populating dynamically.
Thank you.
You are missing && in if condition. Also, your condition
myText != '' is redundant and not required.
And you need to hide the input when selection changed.
$(document).ready(function () {
$('#category').on('change', function () {
var myValue = $(this).val();
var myText = $.trim($("#category :selected").text()).toLowerCase(); // Trim spaces and convert to lowercase for comparison
$("#otherCategory").toggle(myText === 'other');
});
});
Demo: https://jsfiddle.net/tusharj/8ykfmtyt/1/
You need to use && instead of AND
Live Demo
if (myText != '' && myText === "Other") {
$("#otherCategory").show();
}
You can further optimize it by hiding with option other then 'other' is selcted.
You do not need to check if it is not empty when you are comparing it with string 'other' so I removed that condition from if statement.
Live Demo
$('#category').change(function () {
$(this).find(":selected").text() === "Other" ?
$("#otherCategory").show() : $("#otherCategory").hide();
});
Try this Demo, if user selects other option showing input field else hiding.
$(document).ready(function() {
$('#category').change(function() {
var myValue = $(this).val();
var myText = $("#category :selected").text();
if (myText == "Other") {
$("#otherCategory").show();
}
else{
$("#otherCategory").hide();
}
});
});

Select or get all values from Select drop down array using jQuery or JavaScript

I have the following HTML code:
<Select name=test[]>
<option value="">--Please Select--</option>
<option value="a">Test Value1</option>
</select>
<Select name=test[]>
<option value="">--Please Select--</option>
<option value="a">Test Value2</option>
</select>
<Select name=test[]>
<option value="">--Please Select--</option>
<option value="a">Test Value3</option>
</select>
Now before submitting the form I want to do the following
Check if any of the above is selected.
If selected retrieve its value.
I believe I need to loop around but I am unable to find the initial syntax with which I can first grab all the values.
I know how to check if any value is selected when 'id' is given for a select element. But in this case I have the 'name' attribute which is an array.
I tried looking at different places but I haven't really come across a good solution. Probably I missed something.
Please let me know if any further information is required.
using map function
var selected = $('select[name="test[]"]').map(function(){
if ($(this).val())
return $(this).val();
}).get();
console.log(selected);
This isn't a complete solution, but may hopefully point you in the right direction (assuming your using jQuery)
The below code should loop through your selects (when they have the name='test[]') and add any values (that aren't blank) to the result array.
var results = [];
$("select[name='test[]']").each(function(){
var val = $(this).val();
if(val !== '') results.push(val);
});
console.log(results);
Demo: http://jsfiddle.net/W2Mam/
The following will let you iterate through select tags which has any selected value other than default "". You can adjust it to any other unwanted values etc.
$("select[name='test[]']").each(function(){
if($(this).val()!='')
{
//doStuff
}
});
you can check and save boxes values this way
var results = [];
$("select[name='test[]']").each(function(index, val)
{
if ($(val).val() == "") {
//Not selected
}
else
{
//Selected
}
//Save results in an array based on the index of selects
results[index] = $(val).val();
});
then you can iter through the array and check values based on index (or you can just check it above on the .each() function)
Try to do this way:
$("select[name='test[]']").on('change', function(){
if(this.value != ""){
alert(this.value);
}else{
alert('no values selected');
return false;
}
});
You have to get values on the event of change so get the elems with attribute selectors and then you can get the values of target elem.
If you use this :
var values = $('select[name^="test["]').map(function(){
if(this.value !== "") return this.value;
})
You'll have an array of values.
To check if one is selected, just check the length : values.length
You can use filter() to return only the selects which have a value, and then map() to get their values:
var values = $('select[name="test[]"]').filter(function() {
return $.trim(this.value).length;
}).map(function() {
return this.value;
}).get();
Obviously with this you won't know which select has which value, if you need to know, you'd have to use the elements' index as that's its only unique identifier (given your markup).
The following would return an array of objects containing the elements' index, and its value:
var values = $('select[name="test[]"]').filter(function() {
return $.trim(this.value).length;
}).map(function() {
return { index: $(this).index(), value: this.value };
}).get();
To check if anything was selected, you'd just check values.length:
if (!values.length) {
alert('Nothing was selected');
}
Here's a fiddle

How to get checkbox value in multiselect onchange event

I implement jquery multiselect and its working properly now i need to add extra feature that when a user select another option in dropdown ( check another checkbox ) then i want to get the value of the related option
in above picture in did not insert checkbox it is automatically inserted by jquery now i want that if i select the check =box with XYZ then i want to get the value of XYZ which is the id of XYZ
here is how i implemented it
<select multiple="multiple" id="CParent" name="parent" class="box2 required">
#foreach (var item in Model.Categories.OrderBy(c => c.Name))
{
if (Model.Coupon.Categoryid.Id == item.Id)
{
<option selected="selected" value="#item.Id">#item.Name</option>
}
else
{
<option value="#item.Id">#item.Name</option>
}
}
</select>
and it is how it looks like after rendering in browser source
Thanks in advance for helping me .
what i tried yet
$('#CParent input:checked').change(function () {
var parentid = $(this).val()+'';
var array = parentid.split(",");
alert(array);
getchildcat(array[array.length -1]);
});
});
Edit
Code to initialize multiselect
$("#CParent").multiselect({
header: "Choose only THREE items!",
click: function () {
if ($(this).multiselect("widget").find("input:checked").length > 3) {
$(warning).show();
warning.addClass("error").removeClass("success").html("You can only check three checkboxes!");
return false;
}
else if ($(this).multiselect("widget").find("input:checked").length <= 3) {
if ($(warning).is(":visible")) {
$(warning).hide();
}
}
}
});
try this
$('#CParent').val();
this will give you the selectbox value
OR
from docs
var array_of_checked_values = $("#CParent").multiselect("getChecked").map(function(){
return this.value;
}).get();

Categories

Resources