I have example HTML code like this:
<select id="label_1">
<option></option>
</select>
<select id="item_1">
<option></option>
</select>
<select id="label_2">
<option></option>
</select>
<select id="item_2">
<option></option>
</select>
How do I write jQuery code to match the label and item id with the same number?
if($("#label_" + [/[0-9]+$/]) == $("#item_" + [/[0-9]+$/])) {
//do something
}
You can find all the label elements first and then iterate them to find the matching item elements
$("select[id^='label_']").each((_, label) => {
const idSuffix = label.id.split("_").pop();
const item = $(`#item_${idSuffix}`);
// now you have both `label` and `item`
});
The vanilla JS version isn't much different
document.querySelectorAll("select[id^='label_']").forEach((label) => {
const idSuffix = label.id.split("_").pop();
const item = document.getElementById(`item_${idSuffix}`);
// now you have both `label` and `item`
});
If you want to do one time : return false
$.each($("select[id^= 'label_']"), function(){
let num = this.id.replace('label_', '')
let equal = $(this).value === $("#item_" + num).value
if(equal) {
// do something
// if you want to run one times ( return false)
return false
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="label_1">
<option value="1" selected>1</option>
</select>
<select id="item_1">
<option value="1" selected>1</option>
</select>
<select id="label_2">
<option value="2" selected>2</option>
</select>
<select id="item_2">
<option value="2" selected>2</option>
</select>
Related
edit: see "Edit" Section for updated question
I am trying to make the second dropdown selection dependent of the first, using jquery.
get "data-type" of first selection
if "data-type" == "String" trigger filter change of second selections "data-foo" containing value N
HTML Selections
<select id="first" name="first-selection" class="form-control">
<option value="a" class="b" data-type="c">a</option>
</select>
<select id="second" name="second" class="form-control">
<option value="n" data-foo="m">n</option>
</select>
I used to following code to check if I am able to get the "data-type" value and display it. But any attempt to get the data for an if statement failed so far.
$('#first').change(function () {
var selected = $(this).find('option:selected');
$('#type').html(selected.data('type'));
}).change();
edit - code with if statement
how do I use "data-type" for an if statement?
EDIT
New code and jsfiddle to make myself clear
<select id="first" name="first-selection" class="form-control">
<option value="1" class="type1" data-type="snowboot">bli</option>
<option value="2" class="type2" data-type="nose">bla</option>
<option value="3" class="type3" data-type="head">blu</option>
</select>
<p>Test output: <span id="type"></span>.</p>
<select id="second" name="second-selection" class="form-control">
<option value="11" data-foo="green">one of three</option>
<option value="22" data-foo="red">two of three</option>
<option value="33" data-foo="red">three of three</option>
</select>
$(function(){
$('#first').change(function(){
var selected = $(this).find('option:selected');
$('#type').html(selected.data('type'));
}).change();
});
Question
How do I use "data-type" and put it as an if statement before the function? The following won't do anything
if ($('select[id=first] option').filter(':selected').type() == "nose")
if(selected.data('type') == "nose")
var myvar = $('#first option:selected').data();
if(myvar == 'nose')
This is the code I want to run after the if statement:
var $firstvar= $("#first");
$secondvar= $("#second");
$options = $secondvar.find('option')
$firstvar.on('change', function () {
$secondvar.html($options.filter('[data-foo="' + 'red' + '"]'));
}).trigger('change');
This will do what you want. It will check, whether the selected option of the first select was of any of the types mentioned in the object conditions and will then go through all options of the second select and either show or hide them (using the jQuery .toggle(.toggle(!isNose||this.dataset.foo==="red")) method). The expression show=!found||this.dataset.foo===found will evaluate to true for all cases where found is undefined and to false only if found is "trueish" AND this.dataset.foo===found is false.
$(function() {
const conditions={nose:"red",head:"green"}; // add as many as you like ...
$('#first').change(function() {
let show,first=true; // first makes sure only ONE option can be set
const found=conditions[ $(this).find(":selected").data("type") ];
$('#second option').each(function(){
$(this).toggle(show=!found||this.dataset.foo===found);
if(first&&show) first=!(this.selected=true); // select first visible option
})
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="first" name="first-selection" class="form-control">
<option value="1" class="type1" data-type="snowboot">bli</option>
<option value="2" class="type2" data-type="nose">bla</option>
<option value="3" class="type3" data-type="head">blu</option>
</select>
<p>Test output: <span id="type"></span>.</p>
<select id="second" name="second-selection" class="form-control">
<option value="11" data-foo="green">one of three</option>
<option value="22" data-foo="red">two of three</option>
<option value="33" data-foo="red">three of three</option>
</select>
I have this very simple select element:
<label>Items per page</label>
<select class="form-control input-sm w25" ng-model="itemsPerPage">
<option value="5">5</option>
<option value="10">10</option>
<option value="25">25</option>
<option value="50">50</option>
</select>
with controller:
$scope.itemsPerPage = 5; // default value
But the default value is a blank option and the default value attempt doesn't do anything.
How do I make the value 5 the default?
Angular is probably converting that value to a string, so do:
$scope.itemsPerPage = "5";
The blank option appears because ng-model can't find an option that matches the value of the bound property (option values are converted to string and the bound property is number).
If you don't want to change the type of your itemsPerPage property and make it a string, you can keep a number and define, in your $scope, an object with a getter and setter that will take care of the type conversion.
angular.module('dummyApp', [])
.controller('DummyController', function($scope) {
var itemsPerPage = 5; // still a number
Object.defineProperty($scope, "itemsPerPage", {
get: function() {
return itemsPerPage + "";
},
set: function(newValue) {
itemsPerPage = parseInt(newValue);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.2/angular.js"></script>
<div ng-app="dummyApp" ng-controller="DummyController">
<label>Items per page</label>
<select class="form-control input-sm w25" ng-model="itemsPerPage">
<option value="5">5</option>
<option value="10">10</option>
<option value="25">25</option>
<option value="50">50</option>
</select>
</div>
<option value="5" selected>5</option>
This should work^^
I run a joomla site and would like to create an html form within an article that does the following:
<form action="compare.html" method="post">
<select id="select1" name="select1" required="">
<option value="A">OptionA</option>
<option value="B">OptionB</option>
<option value="C">OptionC</option>
</select>
<select id="select2" name="select2" required="">
<option value="1">Option1</option>
<option value="2">Option2</option>
<option value="3">Option3</option>
</select>
<input id="submit" type="submit" />
</form>
After selecting from the 2 dropdowns and submitting the form, the user should go to a page based on the selected options. E.g.
OptionA + Option1 --> goes to page_97.html
OptionA + Option2 --> goes to page_451.html
OptionA + Option3 --> goes to page_13.html
OptionB + Option1 --> goes to page_77.html
and so on.
I was hoping this could be done in pure html or with some simple JS (I'm a newbie to js,php)?
I came up with the following solution which works, but I am sure this could be optimized.
<select id="select1" name="select1" required="" oninput="join_names();">
<option value="">=== SELECT ===</option>
<option value="A">OptionA</option>
<option value="B">OptionB</option>
<option value="C">OptionC</option>
</select>
<br>
<select id="select2" name="select2" required="" oninput="join_names();">
<option value="">=== SELECT ===</option>
<option value="1">Option1</option>
<option value="2">Option2</option>
<option value="3">Option3</option>
</select>
<br>
<button id="compareButton" class="float-left submit-button">COMPARE</button>
<script type="text/javascript">
var urlMap = {
"default" : "/default.html",
"A1" : "/page_97.html",
"A2" : "/page_451.html",
"A3" : "/page_13.html"
"A3" : "/page_77.html"
}
function join_names() {
var input_select1 = document.getElementsByName('select1')[0].value;
var input_select2 = document.getElementsByName('select2')[0].value;
var var_select12 = concatenate(input_select1, input_select2);
var var_select12_url = getMapValue(urlMap,var_select12);
document.getElementById("compareButton").onclick = function () {
window.location.href = var_select12_url;
};
}
function concatenate(string_one, string_two) {
return string_one+string_two;
}
function getMapValue(obj, key) {
if (obj.hasOwnProperty(key)) {
return obj[key];
} else {
return obj['default'];
}
}
</script>
Please can someone help me - I want the second drop-down to change based on a selection from the first option and also the third drop-down to change based on a second selected option. Here is my html:
<select name="selectLevel" id="selectLevel" >
<option value="">-- select a level --</option>
<option value="jhs">Junior High School</option>
<option value="shs">Senior High School</option>
<option value="tertiary 3">Tertiary</option>
</select>
<select name="selectSubject" id="selectSubject">
<option value=""> -- select a subject -- </option>
<option data-value="jhs" value="english">English Language</option>
<option data-value="shs" value="maths">Mathematics</option>
<option data-value="tertiary" value="IT">Business Math</option>
</select>
<select name="selectTopic" id="selectTopic" >
<option value=""> -- select a topic -- </option>
<option data-value="jhs">Spelling</option>
<option data-value="shs">Matrix</option>
<option data-value="tertiary">Calculus</option>
</select>
And here is my script:
$(document).ready(function(){
$('#jhs').change(function(){
if($(this).data('options') == undefined){
$(this).data('options', $('#selectSubject option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[data-value=' + id + ']');
$('#selectSubject').html(options).show();
});
$('#selectSubject').change(function(){
if($(this).data('options') == undefined){
$(this).data('options', $('#selectTopic option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[data-value=' + id + ']');
$('#selectTopic').html(options).show();
});
});
Thank You very much!
I change a little bit to make it easier.
When we change the first select, it will check the second select's option and change its value.
After that, it will trigger the second select's change event and so on.
$(document).ready(function() {
// Save all selects' id in an array
// to determine which select's option and value would be changed
// after you select an option in another select.
var selectors = ['selectLevel', 'selectSubject', 'selectTopic']
$('select').on('change', function() {
var index = selectors.indexOf(this.id)
var value = this.value
// check if is the last one or not
if (index < selectors.length - 1) {
var next = $('#' + selectors[index + 1])
// Show all the options in next select
$(next).find('option').show()
if (value != "") {
// if this select's value is not empty
// hide some of the options
$(next).find('option[data-value!=' + value + ']').hide()
}
// set next select's value to be the first option's value
// and trigger change()
$(next).val($(next).find("option:first").val()).change()
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="selectLevel" id="selectLevel">
<option value="">-- select a level --</option>
<option value="jhs">Junior High School</option>
<option value="shs">Senior High School</option>
<option value="tertiary">Tertiary</option>
</select>
<select name="selectSubject" id="selectSubject">
<option value=""> -- select a subject -- </option>
<option data-value="jhs" value="english">English Language</option>
<option data-value="shs" value="calculus">Calculus</option>
<option data-value="tertiary" value="IT">Info Tech</option>
</select>
<select name="selectTopic" id="selectTopic">
<option value=""> -- select a topic -- </option>
<option data-value="calculus">Calculus</option>
<option data-value="calculus">Matrix</option>
<option data-value="english">Basic English</option>
<option data-value="english">Basic English 2</option>
<option data-value="IT">Info Tech Studies</option>
<option data-value="IT">Info Tech Studies 2</option>
</select>
i got it u would add script CDN code in your code
https://www.w3schools.com/jquery/jquery_get_started.asp
just above your script code
Like this :
<select name="selectLevel" id="selectLevel" >
<option value="">-- select a level --</option>
<option value="jhs">Junior High School</option>
<option value="shs">Senior High School</option>
<option value="tertiary 3">Tertiary</option>
<select name="selectSubject" id="selectSubject">
<option value=""> -- select a subject -- </option>
<option data-value="jhs" value="english">English Language</option>
<option data-value="shs" value="maths">Mathematics</option>
<option data-value="tertiary" value="IT">Business Math</option>
<select name="selectTopic" id="selectTopic" >
<option value=""> -- select a topic -- </option>
<option data-value="jhs">Spelling</option>
<option data-value="shs">Matrix</option>
<option data-value="tertiary">Calculus</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#selectLevel').change(function(){
if($(this).data('options') == undefined){
$(this).data('options', $('#selectSubject option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[data-value=' + id + ']');
$('#selectSubject').html(options).show();
});
$('#selectSubject').change(function(){
if($(this).data('options') == undefined){
$(this).data('options', $('#selectTopic option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[data-value=' + id + ']');
$('#selectTopic').html(options).show();
});
});
You can do this by Ajax request.
I want to change the select option selected to another value.
I.e.,
<select id="myid">
<option value="1" selected="selected">1 </option>
<option value="2" >2 </option>
<option value="3" >3 </option>
<option value="4" >4 </option>
</select>
I have to trigger a change in this select and select the 3rd option I have the value how can I do it.?
I am adding an option each time by a function and I want after each addition of the option, I want it to be selected to do further activities.
To change by index
<input type="button" value="Change Select" onclick="changeSelect(3)" />
function changeSelect(x) {
document.frm.myid.selectedIndex = x-1;
}
to change by value
<input type="button" value="Change Select" onclick="changeSelect1(3)" />
function changeSelect1(x) {
var myid = document.getElementById('myid');
var st = myid.options;
for(var i=0; i<st.length; i++) {
if(st[i].value == x) {
myid.selectedIndex = i;
}
}
}
function Change() {
for (i = 0; i < document.getElementById('ddStream').options.length; i++) {
if (document.getElementById('ddStream').options[i].value == 1)
document.getElementById('ddStream').selectedIndex = i;
}
alert(document.getElementById('ddStream').selectedIndex);
return false;
}
<select id="ddStream" onchange="return Change()">
<option value="">EEE</option>
<option value="">ECE</option>
<option value="">CSE</option>
<option value="1">E&I</option>
</select>
This is the basic syntax.. The other things that you have mentioned will go by the logic u write.. Eg, to select the last option that u add dynamically,
document.getElementById('ddStream').selectedIndex = document.getElementById('ddStream').options.length -1
selected="selected" selects the option you want, just put it on the 3rd option tag
E.g.
<select id="myid">
<option value="1">1 </option>
<option value="2">2 </option>
<option value="3" selected="selected">3 </option>
<option value="4">4 </option>
</select>