How to set selected option for select with same name? - javascript

I am getting an array of objects with education data with AJAX and PHP. There can be up to 4 different <select></select> tags to display. How can I set the correct option for each select and remove the duplicate?
I tried this, which causes the duplicate:
<div class="col-md-3">
<label>Levels</label>
<div class="form-group form-group-custom">
<select type="text" class="form-control" placeholder="Degree..." id="userEducationDegree educationCount + '" name="userEducationDegree[]">
<option value="' +data.degree_name + '">' + data.degree_name + '</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
</div>
Then I tried removing the duplicate with JS, which only works with the first select tag:
var usedDegrees = {};
$("select[name='userEducationDegree[]'] > option").each(function () {
console.log("removing");
if(usedDegrees[this.text]) {
$(this).remove();
} else {
usedDegrees[this.text] = this.value;
}
});
Current output what I have with the above setup is:
<option value="A">A</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
What I would like is that the one of <option value="A">A</option> is removed or that <option> is selected.

You don't need to select the corrected value like you did. The duplicate option comes from your selection which is not required.
Just use the below line it will automatically select the value with match string.
Jquery
$("select[id^='userEducationDegree']").val('A');
// in your case it should be data.degree_name instead of 'A'
Here is the Snippet
$(function(){
$("select[id^='userEducationDegree']").val('A');
$("#sel").html('`'+$("select[id^='userEducationDegree']").val()+'`');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select type="text" class="form-control" placeholder="Degree..." id="userEducationDegree educationCount + '" name="userEducationDegree[]">
<option value="-1">--Select--</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
<p>See <strong id="sel"></strong> is selected</p>

As per your requirement
I would like is that the one of A is
removed or that is selected.
we can select the option as per degree name. for this you can try this code
html:
<div class="col-md-3">
<label>Levels</label>
<div class="form-group form-group-custom">
<select type="text" class="form-control" placeholder="Degree..." id="userEducationDegree educationCount + '" name="userEducationDegree[]">
<option value="Select">Select</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
</div>
</div>
js code will go like that
//lets degree_name='B';
var degree_name='B';
$("select[name='userEducationDegree[]'] option").each(function () {
if(degree_name===this.value) {
this.selected=true;
}
});
Hope it will work fine for you.

Related

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>

Get pre-selected value of an HTML select element

Or through example, how can one retrieve "c" via JavaScript or jQuery no matter if the user changed it?
<select id="select-menu">
<option value="a">A</option>
<option value="b">B</option>
<option value="c" selected>C</option>
<option value="d">D</option>
</select>
I tried the following, however, it returns the value of the currently selected menu. I suppose I can take a similar approach which runs upon page load and save the value, but expect there is a more "proper" way to do so.
$('#select-menu > option').each(function(i){
if(this.selected) {
console.log(this.value)
$("#submit").val(this.value);
return false;
}
})
Use jQuery .attr() to get initial value:
function get_initial(){
$('#select-menu > option').each(function(i){
if($(this).attr('selected')) {
console.log('initial: ' + this.value)
}
if(this.selected) {
console.log('current: ' + this.value)
}
})
}
$('.initial').on('click', get_initial);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select-menu">
<option value="a">A</option>
<option value="b">B</option>
<option value="c" selected>C</option>
<option value="d">D</option>
</select>
<button class="initial">check initial</button>
There is no better way. A select is meant to be user-modifiable.
If you want to retain the original value you could save it on load:
$(document).ready(function() {
var initialValue = $("#select-menu").val();
});
You could also write it in a hidden input:
<input type="hidden" name="initial-select-menu" value="c">
This way has the benefit that the value will be submitted along with the rest of the form. Might be preferable in some cases.
Or you could stuff that initial value in a data attribute:
<select id="select-menu" data-initial="c">
<option value="a">A</option>
<option value="b">B</option>
<option value="c" selected>C</option>
<option value="d">D</option>
</select>
You could save the value on an html5 data-* attribute:
<select id="select-menu" data-default="c">
And get it with
$("#select-menu").attr("data-default");
The following code exhibits various examples related to getting of values from select fields using JavaScript.
Working Snippet
const selectMenu = document.getElementById("select-menu");
var selectedIndex = selectMenu.options[selectMenu.selectedIndex].value;
/*Option 1*/
selectMenu.onchange = function() {
selectedIndex = selectMenu.options[selectMenu.selectedIndex].value;
}
/*Option 2*/
/*selectMenu.addEventListener("change", function(){
selectedIndex = selectMenu.options[selectMenu.selectedIndex].value;
})*/
/*Option 3*/
/*function updateSelectedIndex() {
selectedIndex = selectMenu.options[selectMenu.selectedIndex].value;
}*/
document.writeln(selectedIndex);
<!-- Option 3 -->
<!-- <select id="select-menu" onchange="updateSelectedIndex"> -->
<select id="select-menu">
<option value="a">A</option>
<option value="b">B</option>
<option value="c" selected>C</option>
<option value="d">D</option>
</select>
Try this for the appropriate cases:
let preselectedOption = $(targetDropDown).find('option[selected]');
let currentOption = $(targetDropDown).find('option:selected');

combobox jquery onchange event

How i update combobox based on another combobox, i have this code but its not work, can someone help me. Thanks
<select name="marca" id="marca" onchange="javascript:carregaModelos(this.value)" >
<option th:each="marca : ${marcas}"
th:value="${marca.idmarca}"
th:text="${marca.nomemarca}">Marca</option>
</select>
<select name="modelo" id="modelo">
<option th:each="modelo : ${modelos}"
th:value="${idmodelo}"
th:text="${nomemodelo}">Modelo</option>
</select>
<script type="text/javascript">
function carregaModelos(marca) {
var opcao = $(this).('#marca option')
console.log(opcao);
jQuery("#modelo").load( "pesquisa/" + opcao);
return false;
}
and this
#RequestMapping("/pesquisa/{idmarca}")
public String pesquisa(ModelMap model, #PathVariable Long idmarca) {
model.addAttribute("modelo", service.obterModelosByMarcas(idmarca));
return "index";
Add an attribute with value to target element.
data-target-sync="#targetElementId"
The value is jQuery selector so # included with ID of target element
$(document).ready(function() {
$('[data-target-sync]').change(function() {
var cur = $(this);
$(cur.attr('data-target-sync')).val(cur.val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select name="marca" id="marca" data-target-sync="#modelo">
<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
</select>
<select name="modelo" data-target-sync="#marca" id="modelo">
<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
</select>

Multiple id selectors

I have a form with 2 drop down lists on the same page using the same ids.
<select id="country">
<option value="">Any</option>
<option value="ENGLAND">England</option>
<option value="IRELAND">Ireland</option>
<option value="SCOTLAND">Scotland</option>
<option value="WALES">Wales</option>
</select>
<select id="county">
<option value="">Select a country first...</option>
</select>
<div style="clear:both"> </div>
<select id="country">
<option value="">Any</option>
<option value="ENGLAND">England</option>
<option value="IRELAND">Ireland</option>
<option value="SCOTLAND">Scotland</option>
<option value="WALES">Wales</option>
</select>
<select id="county">
<option value="">Select a country first...</option>
</select>
Not sure how to I change the JavaScript code so the second county drop down list functions same as the first one. The existing javascript and how it functions can be seen here:
http://jsfiddle.net/pfYEb/10/
You'll probably want to use class="country" instead of id="country" so that your selector will match both. (same for your id="county") In your jsfiddle, you'll also need to distinguish which county to change within your country change event. One easy way to do this is to use the index of the current element.
I've forked your jsfiddle here.
HTML
<select class="country">
<option value="">Any</option>
<option value="ENGLAND">England</option>
<option value="IRELAND">Ireland</option>
<option value="SCOTLAND">Scotland</option>
<option value="WALES">Wales</option>
</select>
<select class="county">
<option value="">Select a country first...</option>
</select>
<div style="clear:both"> </div>
<select class="country">
<option value="">Any</option>
<option value="ENGLAND">England</option>
<option value="IRELAND">Ireland</option>
<option value="SCOTLAND">Scotland</option>
<option value="WALES">Wales</option>
</select>
<select class="county">
<option value="">Select a country first...</option>
</select>
​
Relevant Javascript:
$('.country').change(function() {
var country = $(this).val(),
county = $('.county').eq($(".country").index(this)); // This matches the county
// Empty county dropdown
county.empty();
// Update dropdown with appropriate contents
if (country === '') {
county.append('<option value="">Select a country first...</option>');
} else {
$.each(counties[country], function(i, v) {
county.append('<option value="' + i + '">' + v + '</option>');
});
}
});
You can't really solve this querying by id. Element ID's have to be unique within a document by specification by the way. Your best shot, use classes instead.

Can't get jquery to set value of select input when value of first select changes

I'm trying to update the value of a select input when I change the value of another select input. I cannot get anything to happen on the page and want to make sure I don't have a syntax error or some other dumb thing in this code.
<div class="group">
<div class="inputs types">
<strong style="font-size:13px;">Category:</strong>
<select name="id" id="ctlJob">
<option value="1">Automotive</option>
<option value="2">Business 2 Business</option>
<option value="3">Computers</option>
<option value="4">Education</option>
<option value="5">Entertainment & The Arts</option>
<option value="6">Food & Dining</option>
<option value="7">Government & Community</option>
<option value="8">Health & Beauty</option>
<option value="9">Home & Garden</option>
<option value="10">Legal & Financial Services</option>
<option value="11">Professional Services</option>
<option value="12">Real Estate</option>
<option value="13">Recreation & Sports</option>
<option value="14">Retail Shopping</option>
<option value="15">Travel & Lodging</option>
</select>
<select name="type" id="ctlPerson"></select>
</div>
</div>
<script>
$(function() {
$("#ctlJob").change(function() {
//Get the current value of the select
var val = $(this).val();
$('#ctlPerson').html('<option value="123">ascd</option>');
});
});
</script>
Try using append instead:
$(function() {
$("#ctlJob").change(function() {
//Get the current value of the select
var val = $(this).val();
var ctl = $('#ctlPerson').append('<option value="123">'+val+'</option>')[0].options;
ctl.selectedIndex = ctl.length-1;
});
});
http://jsfiddle.net/J69q8/
I think you also need to set the 'selected' property. Add
$('#ctlPerson option[value="123"]').attr('selected', 'selected');
to the end of the script. You are currently adding the option to the select list, but are not changing the select list to show it.
<div id="test">
<select name="sel" id="sel">
<option name="1" id="1" value="1">Automotive</option>
<option name="2" id="1 value="2">Business 2 Business</option>
<option name="3" id="1 value="3">Computers</option>
</select>
<select name="sel2" id="sel2"></select>
</div>
<script>
$("#sel").change(function() {
var val = $(this).val();
$('#sel2').html('<option value="1">NEW</option>');
)};
</script>
this works fine for what you need to do.
it's something like what you have

Categories

Resources