Jquery to update dropdown - javascript

I need to use jQuery to change following dropdown for example
<select id="select1">
<option value="free">Free</option>
<option value="basic">Basic</option>
</select>
to
<select id="select1">
<option optionId="0" value="free">Free</option>
<option optionId="1" value="basic">Basic</option>
</select>
The optionIds value will depend on the number of options.
I am not able to hard code dropdown, it needs to be jquery.
The number of options is generated by MVC DropdownListFor()
Not sure but something like, but not sure how to set unique values:
$(.select1 options).attr("optionId")

Using jQuery (or plain JavaScript) you can create a function that accepts a select ID and adds the attributes to the option elements. It would also be easy to modify the code to apply the attribute to all selects on the page.
Note that jQuery attr() (setAttribute) converts names to lower case. So optionId becomes optionid. Would be better to use a data attribute for this like data-id, which would be more standard.
function setOptions(id) {
$("#" + id + " option").each((index, option) => {
$(option).attr("optionId", index);
});
}
Snippet
function setOptions(id) {
$("#" + id + " option").each((index, option) => {
$(option).attr("optionId", index);
});
stdout.innerHTML += $("#" + id).html(); // test
}
setOptions("select1");
setOptions("select2");
<select id="select1">
<option value="free">Free</option>
<option value="basic">Basic</option>
</select>
<select id="select2">
<option value="free">Free</option>
<option value="basic">Basic</option>
<option value="advanced">Advanced</option>
</select>
<br/>
HTML:
<textarea id="stdout" style="width:100%;height:8em;"></textarea>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Related

How can I get the latest HTML tags of a changeable elements, like Select, Checkbox, Input in JS/Jquery?

I need to get the HTML tags of the changeable element so that I can pass them to create a PDF. But, whenever I use element.innerHTML or element.html(), I get the HTML tags generated after page load but not after I made the changes.
In HTML:
<select id="testSelect">
<option id="no">-- not selected --</option>
<option id="one" selected>1</option>
<option id="two">2</option>
</select>
In JS:document.getElementById("testSelect").innerHTML
It returns:
"
<option id="no">-- not selected --</option>
<option id="one" selected="">1</option>
<option id="two">2</option>
"
And now if I manually change the value to 2, then
In JS:
document.getElementById("testSelect").value
"2"
as you can see the value is changed. But, the HTML tags won't change as
In JS:
document.getElementById("testSelect").innerHTML
"
<option id="no">-- not selected --</option>
<option id="one" selected="">1</option>
<option id="two">2</option>
"
Still, I get the old tags. Instead, I want something like this.
"
<option id="no">-- not selected --</option>
<option id="one">1</option>
<option id="two" selected="">2</option>
"
I made this script for you hope it helps you!
var selectBox=document.querySelector("#testSelect");
selectBox.addEventListener("change", function(){
const selectBoxOptions=selectBox.querySelectorAll("option");
selectBoxOptions.forEach((option)=>{
option.removeAttribute("selected");
});
detectOptionObjectByValue(this, this.value).setAttribute("selected", "selected");
});
function detectOptionObjectByValue(selectBox, value){
const options=selectBox.querySelectorAll("option");
let pos=0, obj=false;
options.forEach(function(option){
option.value==value?obj=options[pos]:0;
pos++;
});
return obj;
}
<select id="testSelect">
<option id="no">-- not selected --</option>
<option id="one" selected>1</option>
<option id="two">2</option>
</select>
You can make a function which will iterate through all options and set all the selected attributes to false
$('select option[value=' + i + ']').attr("selected",false);
Then based on the value selected set the attribute to true
$('select option[value=' + this.value + ']').attr("selected",true);
const dropdownElement = document.getElementById('testSelect')
dropdownElement.onchange = function () {
clearSelected()
$('select option[value=' + this.value + ']').attr("selected",true);
console.log("value selected: " + this.value);
console.log("html: " + dropdownElement.innerHTML)
};
// set all the options to unselected
function clearSelected(){
var elements = dropdownElement.options;
for(var i = 0; i < elements.length; i++){
$('select option[value=' + i + ']').attr("selected",false);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="testSelect">
<option id="no" value="0">-- not selected --</option>
<option id="one" value="1" selected>1</option>
<option id="two" value="2">2</option>
</select>
On jQuery site you have similar question explained:
https://learn.jquery.com/using-jquery-core/faq/how-do-i-get-the-text-value-of-a-selected-option/
$(function(){
$('#select').change(function(){
$('#output-value').text($(this).val());//get value
$('#output-element').text($(this).find('option:selected').text());//get text of selected element
$(this).find('option').each(function(){
$(this).attr('selected', $(this).is('option:selected')); //adds and removes selected attribute
});
$('#output-html').text($(this).html());
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="select" >
<option>--</option>
<option value="1" >1 val</option>
<option value="2" >2 val</option>
<option value="3" >3 val</option>
</select>
<br/>
Value
<div id="output-value" ></div>
Element
<div id="output-element" ></div>
HTML
<div id="output-html"></div>

Add new select with unqiue name onchange of previous select

I have a job that requires several hundred select elements on a page. I want to show each select dynamically as the previous is changed. I have a working version in which I put all the select elements in the markup, and then used a simple function to hide them all and show only the first. Then on change of each select the next is added.
This works just fine, but is obviously not ideal. I don't want to put 500 select items in the markup and hide them all for no reason, and my JS function would be 1500 lines long. Plus that would make me feel silly.
How can I automate this process with JS?
I do not need each select to have a unique id, but I do need each select to have a unique and incremented name. Is this possible? I have a working fiddle.
HTML:
<select name="select-one" class="hidden" id="one">
<option value="">not this one</option>
<option value="">pick this one</option>
</select>
<select name="select-two" class="hidden" id="two">
<option value="">not this one</option>
<option value="">pick this one</option>
</select>
<select name="select-three" class="hidden" id="three">
<option value="">not this one</option>
<option value="">pick this one</option>
</select>
<select name="select-four" class="hidden" id="four">
<option value="">not this one</option>
<option value="">pick this one</option>
</select>
JS:
$(document).ready(function() {
$('.hidden').hide();
$('#one').show();
$('#one').change(function(){
$('#two').show();
});
$('#two').change(function(){
$('#three').show();
});
$('#three').change(function(){
$('#four').show();
});
// and so forth...
});
HTML:
<select class="hidden" id="one" name='name_0'>
<option value="">not this one</option>
<option value="">pick this one</option>
</select>
jQuery
$('select').on('change', function() {
$('body').append($(this).clone(true))
})
Result:
Note we are using the overload of the clone() method. This means event handlers and data will be copied along with the elements. So whatever event handler you attached to the original select gets cloned.
If you want to increment the name just use a counter and add the attribute after the clone:
cnt=0;
$('select').on('change', function() {
cnt++
$('body').append($(this).clone(true).attr('name', 'name_' + cnt))
})
My solution:
CSS
.hidden {
display: none;
}
JS
const createSelect = index => `
<select name="select-${index}" class="hidden select" data-index=${index}>
<option value="">not this one</option>
<option value="">pick this one</option>
</select>
`;
$(document).ready(function() {
// Generate 100 selects
for (let i = 0; i < 100; i++) {
$("body").append(createSelect(i));
}
// Show first select
$(`.select[data-index='0']`).show();
$('.select').on('change', function() {
// Store index of a select currently changed
const index = parseInt($(this).attr('data-index'), 10);
// Show next select
$(`.select[data-index='${index + 1}']`).show();
});
});

Change value of select list with value of another select list jquery

How can I change the value of a select list with the value of another select list
<select class="main-filter" id="Test1" name="Test1"><option value="">Select Option</option>
<option value="1">One</option>
<option value="2">Two</option>
</select>
Need to replace #ReplaceThisText# with value selected from above select box
<select id="selectfilter" name="selectfilter" class="form-control main-filter">
<option value="">Sort Products</option>
<option value="/?id=na&selectfilter=hl&Type=#ReplaceThisText#">Chnage Value</option>
</select>
I have tried code from this link Change the Text of a Option with jQuery
and jquery how to find and replace a selected option that has a certain value
but cannot seem to get it to work
My code is
$('#Test1').change(function () {
sessionStorage.setItem("Test1", $(this).val());
$('.main-filter :selected:contains("#ReplaceThisText#")').val($(this).val());
location.href = $(this).val();
});
:contains will look at the .text() value - but your #ReplaceThisText# is not in the .text() value - so you'll need to use .filter() to find it instead:
Adding some console.logs so you can see what's happening and updated the .val(newval) code to make the replacement.
$('#Test1').change(function() {
var newval = $(this).val();
console.log("before", $(".main-filter :contains('Change Value')").val())
var opt = $('.main-filter option').filter(function() {
return $(this).val().indexOf("#ReplaceThisText#") >= 0;
});
console.log("opt length", opt.length);
opt.each(function() {
$(this).val($(this).val().replace(/#ReplaceThisText#/gi, newval));
});
console.log("after", $(".main-filter :contains('Change Value')").val())
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="main-filter" id="Test1" name="Test1">
<option value="">Select Option</option>
<option value="1">One</option>
<option value="2">Two</option>
</select>
<select id="selectfilter" name="selectfilter" class="form-control main-filter">
<option value="">Sort Products</option>
<option value="/?id=na&selectfilter=hl&Type=#ReplaceThisText#">Change Value</option>
</select>

Why select option change event can't have this and event.target to get selected value?

In select option change event,why can't we get this or event.target to get selected value instead of writing clumsy code like $( "select option:selected" ) to get selected value ?
Pure JavaScript
If you want a pure JavaScript approach, then use the event.target. To quote the official MDN documentation...
The target property of the Event interface is a reference to the object onto which the event was dispatched. (Source: MDN Web Docs: Event.target.)
Since that gives us the element selected, all we then need is the value attribute, and getting the text display would be nothing more than event.target[event.target.selectedIndex].text...
function getSelectedValue(event) {
console.log("Value: " + event.target.value + "; Display: " + event.target[event.target.selectedIndex].text + ".");
}
<select onchange="getSelectedValue(event)">
<option selected disabled>--Pick an Option--</option>
<option value="blue1">Blueberry</option>
<option value="rasp2">Raspberry</option>
<option value="straw3">Strawberry</option>
</select>
Using the above approach, it would be trivial to update it to add in other attributes of the selection option value, all in pure JavaScript.
jQuery
If you want a jQuery approach, then try using the :selected query term...
$("#selector").on('change', function(){
console.log("Value: " + $(this).val() + "; Display: " + $(this).find('option:selected').text() + ".");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="selector">
<option selected disabled>--Pick an Option--</option>
<option value="blue1">Blueberry</option>
<option value="rasp2">Raspberry</option>
<option value="straw3">Strawberry</option>
</select>
$("select").on('change', function(){
console.log($(this).val());
console.log($(this).find('option:selected').attr('data-attribute'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select>
<option data-attribute="a">1</option>
<option data-attribute="b">2</option>
<option data-attribute="c">3</option>
<option data-attribute="d">4</option>
</select>
You can't get the selected value, but of course you can get the element and the event.target.
<select onchange="mySelectOnchange(this, event)"></select>
function mySelectOnchange(elm, e) {
// **
}
It exists... take a look at this code for example
var selectElem = document.getElementById('select');
selectElem.addEventListener('change', onSelect_change);
function onSelect_change(domEvent){
// get the selected value :
var selectedValue = domEvent.target[domEvent.target.selectedIndex].value;
// you can also do it using domEvent.target.value but the other solution allows you to get every option's property you want
console.log("Selected: " + selectedValue);
}
<select id="select" name="select">
<option value="value1">Value 1</option>
<option value="value2" selected>Value 2</option>
<option value="value3">Value 3</option>
</select>
Hope it helps ;)
PS: have a look on http://www.w3schools.com/jsref/prop_select_selectedindex.asp if you want more examples
The only property that's automatically transferred from the selected option to the <select> element itself is the value, because that's the main purpose of selecting an option from a drop-down menu. Other attributes like data-* are not automatically copied, because it's possible for the <select> to have its own attributes, e.g.
<select id="x" data-name="select">
<option value="1" data-name="option1">1</option>
<option value="2" data-name="option2">2</option>
</select>
It wouldn't make sense for $("#x").data("name") to return the name of the selected option instead of the name of the <select>.
<select onchange="getSelectedValue(this)"></select>
...
function getSelectedValue(select) {
console.log(select.value)
}

Using jQuery to replace an option element in one select box with another?

I have two select boxes, one of which is dynamically populated. The second box I would like to replace the option element with whatever is selected. At the moment, I have it working with this:
var currentManCodeSelected = $('#sltmanu').find(':selected')[i].value;
var currentManCodeName = $('#sltmanu').find(':selected')[i].text;
$('#sltmanuCurrent option:first').replaceWith("<option value='" + currentManCodeSelected + "'>" + currentManCodeName + "</option>");
Is there a better way of doing this? A shorter and more elegant way?
You can do that like following;
HTML:
<select id="left">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
<select id="right">
<option value="d">d</option>
<option value="e">e</option>
<option value="f">f</option>
</select>
JS:
$(document).ready(function() {
$("#left").on('change', function() {
$('#right :selected').val($('#left :selected').val()).text($('#left :selected').text());
});
});
Here is a working fiddle: http://jsfiddle.net/Azugu/
Just change the value and text instead of replacing the whole element
$('#sltmanuCurrent option:first').val(currentManCodeSelected).text(currentManCodeName);

Categories

Resources