How to select option with a name? - javascript

I have the following <select>:
<select id="to" name="contact">
<option value=""></option>
<option name="4307" value="">Nitheesh</option>
<option name="4306" value="">Ramanatan</option>
</select>
When I pass a variable through get, which will be equal to one of the name, I want that particular <option> to selected.

You should use filter method in order to find out option which have your given text.
var name="Nitheesh";
var option=$("select option").filter(function(i,option){
return $(option).text()==name;
}).attr('selected','selected');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="to" name="contact">
<option value=""></option>
<option name="4307" value="Nitheesh">Nitheesh</option>
<option name="4306" value="">Ramanatan</option>
</select>
If you want to obtain an option by particular name attribute, use this:
$("option[name = '" + name + "']").attr('selected','selected');

Use the Attribute Equal Selector like this:
var someName = /*...*/;
var $option = $("[name = '" + someName + "']");
Here is a reference of other CSS Selectors.

Using jQuery can use an attribute selector
var newVal = 4306;
$('#to option[name="' + newVal +'"]').prop('selected',true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="to" name="contact">
<option value=""></option>
<option name="4307" value="">Nitheesh</option>
<option name="4306" value="">Ramanatan</option>
</select>

Here is a sample
$(document).ready(function(){
//given get val
var val = "4307";
$("#to option[name="+val+"]").attr("selected",true);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="to" name="contact">
<option value=""></option>
<option name="4307" value="">Nitheesh</option>
<option name="4306" value="">Ramanatan</option>
</select>

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>

How to get multiple values from an HTML <select> element

How to take the values of value1 and value2 in two variables using javascript?
<select class="form-control" id="country" name="country">
<option value="**value1**" "**value2**" >Select Item</option>
</select>
You could make your own attribute. I know you probably do not want to get the element with an ID, but I don't know the context. You can just call getAttribute on the option and use any name you gave to the "custom" attribute.
window.addEventListener('load', ()=>
{
const option = document.getElementById('option');
function init()
{
//Use this to get the values
console.log(option.getAttribute('other-value'));
}
init();
});
<select class="form-control" id="country" name="country">
<option id="option" value="value1" other-value="value2">Select Item</option>
</select>
I don't know what you really want to do with your piece of code,
but here is a proper way to use the option elements, and a way to split multiple values with a fixed separator:
var example = document.getElementById('example');
example.addEventListener('change', function() {
// Console displays the “value”, and not the text, of the selected option
console.log("option value:", example.value);
});
// Here is what I'll do with your "multiple" values
var country = document.getElementById('country');
var options = country.querySelector('option');
var values = options.value.split("/");
values.forEach(function(val) {
country.innerHTML += "<option value=" + val + ">" + val + "</option>";
});
<p>My simple example</p>
<select id="example" name="country">
<option value="--">Select Country</option>
<option value="GB">Great Britain</option>
<option value="FR">France</option>
</select>
<br>
<br>
<p>Example with option getting splitted</p>
<select class="form-control" id="country" name="country">
<!-- Let's say your multiple values are separated by a "/" -->
<option value="**value1**/**value2**">Select Item</option>
</select>
Hope it helps.
$('select').on('change', function() {
console.log( $('#country').val() );
console.log($(this).find(':selected').data('second'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="form-control" id="country" name="country">
<option value="value1" data-second ="value2" >Select Item 1</option>
<option value="value3" data-second ="value4" >Select Item 2</option>
</select>

How can I pass variable with concatenation to get an option in selection list

I'd like to get an option in a select list by it's value.
I 'd like to replace [value="1"] by idEntrepot but it doens't work.
var $enrepotOrg = $('#appbundle_operation_entrepotOrigine');
$enrepotOrg.change(function () {
var idEntrepot = $enrepotOrg.val();
$('#appbundle_operation_entrepotDestine option[value="1"]').hide();
//.........
I'd like just to pass var idEntrepot instead of static "1"
function hideOption() {
$('#test option').show();
var valueToHide = $("#edit").val();
$('#test option[value="' + valueToHide + '"]').hide();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="test">
<option value="">None</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<input id="edit" />
<button onclick="hideOption()">Click</button>

How to get data attribute of option tag in JavaScript

Want to get data attribute value from selected dropdown option.
<select name="selection" id="mySelect">
<option value="21" data-rc="25" data-clnc="10">Treatment</option>
</select>
var rc = ? //value of data-rc
var clnc = ? //value of data-clnc
No jQuery please only JavaScript :)
You can read them out via dataset property.
var option = document.getElementsByTagName("option")[0];
console.log(option.dataset.rc)
console.log(option.dataset.clnc)
<option value="21" data-rc="25" data-clnc="10">Treatment</option>
Or, if you want to get the values of the selected option:
var selection = document.getElementById("mySelect");
selection.onchange = function(event){
var rc = event.target.options[event.target.selectedIndex].dataset.rc;
var clnc = event.target.options[event.target.selectedIndex].dataset.clnc;
console.log("rc: " + rc);
console.log("clnc: " + clnc);
};
<select name="selection" id="mySelect">
<option value="21" data-rc="25" data-clnc="10">Treatment</option>
<option value="21" data-rc="23" data-clnc="30">Treatment1</option>
<option value="21" data-rc="31" data-clnc="50">Treatment2</option>
<option value="21" data-rc="14" data-clnc="75">Treatment3</option>
</select>
suppose we have a select field
<select id="ddlViewBy">
<option value="1" data-rc="25" data-clnc="10" selected="selected">test1</option>
<option value="2" >test2</option>
<option value="3">test3</option>
</select>
Now we will get the select list and its selected option
var e = document.getElementById("ddlViewBy");
var option= e.options[e.selectedIndex];
Now we have the selected option we can get its attribtues
var attrs = option.attributes;
attrs is the attributes array you can get attribtues by index you want.
Or you can get attribtues by
var datarc = option.getAttribute("data-rc");
Check this working pen
working pen
$('#options').on('change', function(){
alert($(this).find("option:selected").attr('data-rc'))
alert($(this).find("option:selected").attr('data-clnc'))
});
var mySelect = document.querySelector('#mySelect')
console.log('mySelect value ' + mySelect.value)
console.log('mySelect data-rc ' + mySelect.selectedOptions[0].getAttribute("data-rc"))
console.log('mySelect data-clnc ' + mySelect.selectedOptions[0].getAttribute("data-clnc"))
<select name="selection" id="mySelect">
<option value="21" data-rc="25" data-clnc="10">Treatment</option>
</select>
$(selector).find("option:selected").data("rc") for rc and clnc for clnc where selector is your "select" tag id/class
You can do that with jquery selector
var rc = $('select option:selected').data('rc');

Change select box value depending other selected option box

i am new to Javascript/ Jquery
so my problem is :
i want to change the select/option box text and value depending on the other selected option/box
so for examplemy first option is :
<select id="gender">
<option>Select Your Gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
and then one i want to change depending on selected option is :
When its male :
<select id="name">
<option>Select Your Name</option>
<option value="Male1">Male 1</option>
<option value="Male2">Male 2</option>
</select>
when its female :
<select id="name">
<option>Select Your Name</option>
<option value="female1">Female 1</option>
<option value="female2">Female 2</option>
</select>
Thanks for the help! :)
There you go with DEMO
var options=""; //store the dynamic options
$("#gender").on('change',function(){ //add a change event handler to gender select
var value=$(this).val(); //get its selected value
options="<option>Select Your Name</option>"
if(value=="Male") //value ==Male then set male required options
{
options+="<option value='Male1'>Male 1</option>"
+"<option value='Male2'>Male 2</option>";
$("#name").html(options);
}
else if(value=="Female") //else set female required options
{
options+='<option value="female1">Female 1</option>'
+'<option value="female2">Female 2</option>';
$("#name").html(options);
}
else
$("#name").find('option').remove() //if first default text option is selected empty the select
});
I would suggest to have a better HTML architecture to achieve this kind of things. Have each name in one Dropdown only and categorise with some data attribute. When changing the value of Gender Dropdown, filter with type and toggle the options. Follow this:
$(function(){
$("#gender").on("change", function(){
var $target = $("#name").val(""),
gender = $(this).val();
$target
.toggleClass("hidden", gender === "")
.find("option:gt(0)").addClass("hidden")
.siblings().filter("[data-type="+gender+"]").removeClass("hidden");
});
});
.hidden{
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="gender">
<option value="">Select Your Gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
<select id="name" class="hidden">
<option value="">Select Your Name</option>
<option value="Male1" data-type="Male">Male 1</option>
<option value="Male2" data-type="Male">Male 2</option>
<option value="female1" data-type="Female">Female 1</option>
<option value="female2" data-type="Female">Female 2</option>
</select>
Fiddle link: http://jsfiddle.net/ashishanexpert/qzxedcut/
Whenever a change occurs, use the value of the gender dropdown to populate the names one. We use a for loop to produce more than one option per gender.
$('#gender').change(function(){
if(!this.selectedIndex) return;
var gender = $(this).val(),
$name = $('#name').empty(),
$option = $('<option />').text('Select Your Name').appendTo($name);
for(var i = 1; i <= 2; i++)
$option.clone().prop('value', gender + i).text(gender + ' ' + i).appendTo($name);
});
JSFiddle
Follow the Practice:
Do not hardcode options this case.Best practice is get value from Json.
Then later changes are easy instead of change all codings.
Build dynamic Dropdowns. Dont Hide and Show.
HTML
<select id="gender">
<option>Select Your Gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
<select id="gtr" name="location" placeholder="Anycity"></select>
Jquery
jQuery(function($) {
var gender = {
'Male': ['Male1', 'male2'],
'Female': ['Female1','Female1'],
}
var $gndr = $('#gtr');
$('#gender').change(function () { debugger
var GNDR = $(this).val(), gndrs = gender[GNDR] || [];
var html = $.map(gndrs, function(gndr){
return '<option value="' + gndr + '">' + gndr + '</option>'
}).join('');
$gndr.html(html);$gndr.append(new Option("Select Name", "0"));$gndr.val("0");
});
});
JsFiddle
https://jsfiddle.net/2pza5/1135/
I suggest you to try this way:
Change you jquery:
<select id="nameMale">
<option>Select Your Name</option>
<option value="Male1">Male 1</option>
<option value="Male2">Male 2</option>
</select>
<select id="nameFemale">
<option>Select Your Name</option>
<option value="Male1">Male 1</option>
<option value="Male2">Male 2</option>
</select>
Inser this javascript:
<script>
<![CDATA[
$(function() {
$('#nameFemale').hide();
$('#nameMale').hide();
function changeGen(val){
if(val == 'Female'){
$('#nameFemale').show();
$('#nameMale').hide();
}else{
$('#nameFemale').hide();
$('#nameMale').show();
}
}
$('#gender').change(function() {
changeGen($('#gender').val());
});
});
]]>
</script>
FIDDLE
$('#gender').change(function (e) {
var val = $("option:selected", this).val()
console.log(val);
if(val =='Male'){
$('#name').find('option.female').hide();
$('#name').find('option.male').show();
}else if(val =='Female'){
$('#name').find('option.female').show();
$('#name').find('option.male').hide();
}else{
}
});
Added class for each option since it is static.
Then you can hide the option from second select depending on the value of first select
Try this:
$("#gender").on("change",function(){
var sel="";
if($(this).val() == "Female"){
sel=' <option>Select Your Name</option>';
sel+=' <option value="female1">Female 1</option>'
sel+='<option value="female2">Female 2</option>'
}else{// no other if since you have only two options male/female
sel= '<option>Select Your Name</option>';
sel+= '<option value="Male1">Male 1</option>';
sel+= '<option value="Male2">Male 2</option>';
}
$("#name").html(sel);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="gender">
<option>Select Your Gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
<select id="name">
</select>

Categories

Resources