How to link to form select option dropdowns - javascript

I have a webpage using 4 search box's in 2 in header & 2 in the body of homepage.
Both Header form & form in body of homepage are the same and query the same search page.
My Question is how could I link dropdowns so that when one changes the others follow.
At the moment I am using php to switch to appropriate categories on arrival to page(s).
eg:
<option value='-1' <?php if ($cat == "-1") {print("selected");}?>>All Categories</option>
<option value='0'<?php if ($cat == "0") {print("selected");}?>>Category One</option>
<option value='1' <?php if ($cat == "1") {print("selected");}?>>Category Two</option>
Which works great when arriving on page(s) after query.
However Because there are 4 forms on my home page I was hoping to somehow dynamically when user changes one of the < select >< options > on page then the other < select >< options > in header and other places all change to same value also?
Any ideas?

Suppose you have 2 'Select' html elements like below:
test.html
<html>
<head>
<script src="connectSelect.js"></script>
</head>
<body onload="connectSelect('first', 'second')">
<select id="first">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select id="second">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</body>
</html>
Just use the already made 'connectSelect' function on body load passing the ids of the 'Select' elements you want to connect.
Include the connectSelect.js file in the header. Below is the code for that:
connectSelect.js
function connectSelect(id1, id2) {
var select1 = document.getElementById(id1);
var select2 = document.getElementById(id2);
var i, val1, text1, val2, text2, errText;
//to check whether both the select elements are of same length or not
if (select1.length != select2.length) {
alert("connectSelect Function Error: Both the 'Select' elements should have same number of options!");
return;
}
//after assuring both the select elements to be of same length
//to check whether both the select elements have same value and text
for (i = 0; i < select1.length; i++) {
val1 = select1.options[i].value;
text1 = select1.options[i].innerHTML;
val2 = select2.options[i].value;
text2 = select2.options[i].innerHTML;
if (val1 != val2 || text1 != text2) {
errText = "Both the 'Select' elements should have same options with same value and text!";
errText += "\n";
errText += "\n";
errText += "First mismatch: Option " + (i+1);
alert("connectSelect Function Error: " + errText);
return;
}
}
//after assuring both the select elements to be same
select1.addEventListener("change", function(){
var index = this.selectedIndex;
select2.options[index].selected = true;
});
select2.addEventListener("change", function(){
var index = this.selectedIndex;
select1.options[index].selected = true;
});
}
I have inserted the code snippet also. Try it.
function connectSelect(id1, id2) {
var select1 = document.getElementById(id1);
var select2 = document.getElementById(id2);
var i, val1, text1, val2, text2, errText;
//to check whether both the select elements are of same length or not
if (select1.length != select2.length) {
alert("connectSelect Function Error: Both the 'Select' elements should have same number of options!");
return;
}
//after assuring both the select elements to be of same length
//to check whether both the select elements have same value and text
for (i = 0; i < select1.length; i++) {
val1 = select1.options[i].value;
text1 = select1.options[i].innerHTML;
val2 = select2.options[i].value;
text2 = select2.options[i].innerHTML;
if (val1 != val2 || text1 != text2) {
errText = "Both the 'Select' elements should have same options with same value and text!";
errText += "\n";
errText += "\n";
errText += "First mismatch: Option " + (i+1);
alert("connectSelect Function Error: " + errText);
return;
}
}
//after assuring both the select elements to be same
select1.addEventListener("change", function(){
var index = this.selectedIndex;
select2.options[index].selected = true;
});
select2.addEventListener("change", function(){
var index = this.selectedIndex;
select1.options[index].selected = true;
});
}
<html>
<head>
<script src="test.js"></script>
</head>
<body onload="connectSelect('first', 'second')">
<select id="first">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select id="second">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</body>
</html>
Hope it helped.
EDIT: For a better solution, please check this (Source: From comments of this question)

Related

Converting a JavaScript function to jQuery - Select option list

This is literally the first time I've worked with jQuery and I've read the entire chapter in my textbook but am finding a hard time wrapping my head around it. I'm attempting to convert a JavaScript function (a simple option selection drop-down list) to jQuery. I've attempted a few lines of code that I've gotten from the book or from w3schools and api.query but to no avail. I'll try to make this quick and simple, I just cannot understand jQuery for some reason.
What I've attempted usually doesn't work. Before my option list works fine, then I tried experimenting but I didn't get too far.
I also apolgize for the vagueness of the question, I'd appreciate any help!
Here's something I've tried:
$(document).ready( function () {
var c = ???
if ($(c...
calc.js and index.html below it
function selectedCountry() {
var c = document.getElementById("countryChooser").value;
var message;
if (c == "nothing") { //if they selected the default option, error pops up.
alert("Please select a country.");
} else if (c == "usa") {
message = "United States of America";
document.getElementById("count").innerHTML = "Your country is: " + message;
} else if (c == "canada") {
message = "Canada";
document.getElementById("count").innerHTML = "Your country is: " + message;
} else {
message = "Mexico";
document.getElementById("count").innerHTML = "Your country is: " + message;
}
}
<script src = "calc.js"></script> <!--JavaSript link -->
<select name="countrylist" id="countryChooser" onchange="selectedCountry()">
<option value="nothing">Select a country</option>
<option value="usa">United States of America</option>
<option value="canada">Canada</option>
<option value="mexico">Mexico</option>
</select>
<p id="count"></p>
Through jQuery you can do it like below:-
Example:-
$(document).ready(function(){
$('#countryChooser').change(function(){ // on change of select
if($(this).val()!=='nothing'){ // if selected value is some country
$('#count').html("Your country is: "+$("#countryChooser option:selected").text()); // get country name and add it to paragraph
}else{
$('#count').html("");
alert('Please select a country.'); // alert for selecting a country
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="countrylist" id="countryChooser">
<option value="nothing">Select a country</option>
<option value="usa">United States of America</option>
<option value="canada">Canada</option>
<option value="mexico">Mexico</option>
</select>
<p id="count"></p>
Get an element by id:
var c = $('#countryChooser');
Get the value of this input/select element
var value = c.val();
Set the html of an element using the element id
$('#count').html('some html');
or set the text (html is not parsed this way)
$('#count').text('some html');
You can also handle the events with jQuery
$(document).ready(function() {
$('#countryChooser').on('change', function(event) {
// this is the DOM element with the id 'countryChooser'
// same as the native: var val = this.value;
var val = $(this).val();
// ...
});
});
I have bind the onchange() event of your select list inside the jQuery(document).ready() method. check this out-
// Updated code--
$(document).ready(function (){
$('#countryChooser').on('change' ,function () {
if(this.selectedIndex){
$('#count').html("Your country is: "+ this.options[this.selectedIndex].text);
}else{
$('#count').html("");
alert("Please select a country.");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src = "calc.js"></script> <!--JavaSript link -->
<select name="countrylist" id="countryChooser">
<option value="nothing">Select a country</option>
<option value="usa">United States of America</option>
<option value="canada">Canada</option>
<option value="mexico">Mexico</option>
</select>
<p id="count"></p>
$('#countryChooser').change(function(){
var selectedCountry = $(this).val();
if(selectedCountry == 'nothing'){
console.log('Select A country');
}
else{
$('#count').html('Your country is '+$('#countryChooser option:selected').text());
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!--JavaSript link -->
<select name="countrylist" id="countryChooser" >
<option value="nothing">Select a country</option>
<option value="usa">United States of America</option>
<option value="canada">Canada</option>
<option value="mexico">Mexico</option>
</select>
<p id="count"></p>
Please check the code might help you out
thanks

How to get the value of option with attribute selected

I'm trying to get the value of the option which have the attribute "selected" to compare it to the current option selected.
function onChangeOption(opt) {
var update_value = opt.value;
var selectedValue = '???'; // get selected attribute
if (update_value != selectedValue) {
// Do some things
}
}
<select class="form-control" onchange="onChangeOption(this)">
<!-- I wanna got the content of option selected=selected-->
<option selected="selected" value="1">1</option>
<option value="2">2</option>
</select>
// save initial selected value to a variable
var initSelected = $('.form-control option:selected').val();
$('select').on('change', function() {
// check if the selected value is the same as the initial one was
if(this.value == initSelected) {
console.log('same values');
} else {
console.log('not same values');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control">
<option selected="selected" value="1">1</option>
<option value="2">2</option>
</select>
Just add change event listener.And get the selected value.You can achieve comparision between selected value and changed value by maintaining an array.Like below.
values = []//creates an array
select = document.querySelector('#myselect');
values.unshift(select.value);
//console.log(values);
select.addEventListener('change',function(){
update_value = this.value;
console.log(this.value);
if (update_value != values[0]) {
// alert('Not matched');
console.log('Not matched');
}
else{
//alert('Matched');
console.log('Matched')
}
});
<select class="form-control" id="myselect">
<option selected="selected" value="1"> 1 </option>
<option value="2"> 2 </option>
</select>
I think alexis actually wants something more like this:
function onChangeOption(opt) {
var update_value = opt.value;
var options = document.getElementsByTagName("option");
if (options[0].getAttribute("selected")=="selected") {
var selectedValue = options[0].value;
} else {
var selectedValue = options[1].value;
}
if (update_value != selectedValue) {
// If the selected option's value is not equal to the value of the option with the attribute "selected", then do... (this way, you can change the attribute to any of the options!)
console.log(selectedValue);
}
}
<select class="form-control" onchange="onChangeOption(this)">
<option selected="selected" value="1">1</option>
<option value="2">2</option>
</select>
Comment the result and if you need anything else. Glad to help.
You can always store previously selected values, if you want to access them somehow later on: working example.
HTML:
<select id="mySelect" class="form-control" onchange="onChangeOption(this)">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<p>Previous: <span id="prev"></span></p>
<p>Current: <span id="curr"></span></p>
JS:
var selectElem = document.getElementById("mySelect");
var prev = document.getElementById("prev");
var curr = document.getElementById("curr");
var allEverSelected = [ selectElem.value ];
selectElem.addEventListener("change", function(evt){
allEverSelected.push( this.value );
prev.innerHTML = allEverSelected[allEverSelected.length - 2];
curr.innerHTML = allEverSelected[allEverSelected.length - 1];
});
To access default value, just get the <select> value after DOM loads.
selected attribute on <option> tag exist only to make other than first <option> element inside <select> default option, i.e.:
<select>
<option value="1">1</option>
<option selected value="2">2</option>
</select>
Above select's default value is 2.
I think this is the one what you want. Try it.
function onChangeOption(opt) {
var update_value = opt.value;
console.log(update_value);
var selectedValue;// = '???'; // get selected attribute
// I think this is the one you want
//If you want to select the HTML element,
selectedValue=document.querySelector("option[value='"+update_value+"']");
console.log(selectedValue);
//
if (update_value != selectedValue) {
// Do some things
}
}
//onChangeOption(document.querySelector('form'));
function start(){
while(typeof document.querySelector('form')!=typeof {}){}
onChangeOption(document.querySelector('.form-control'));
}
<body onload="start()">
<select class="form-control" onchange="onChangeOption(this)">
<option selected="selected" value="1">1</option>
<!-- I wanna got this -->
<option value="2">2</option>
</select></body>

Sorting drop down menus when changed

I have a page that builds drop down menus dynamically from the database as follows:
<select name="set_order[]" class="form-control" data-catid="3">
<option value="1" selected="">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select name="set_order[]" class="form-control" data-catid="2">
<option value="1">1</option>
<option value="2" selected="">2</option>
<option value="3">3</option>
</select>
<select name="set_order[]" class="form-control" data-catid="1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3" selected="">3</option>
</select>
What I want to do is that when one of them is changed, I want to resort the drop downs according to the change that was made with Javascript and update the selected dropdown in each dropdown so as that each drop down has a unique choice made.
I've been trying to sort them but I haven't been successful.
Thank you in advanced!
Edit, as requested, here is my trial JS to sort them:
$(document).on('change', 'select[name="set_order[]"]', function(){
var newOrder = $(this).val();
var change_id = $(this).attr('data-catid');
console.log(newOrder, ' ', change_id);
var order = new Array();
var cat_id = new Array();
var checker = false;
$('select[name="set_order[]"]').each(function(i){
order[i] = parseInt($(this).val());
cat_id[i] = parseInt($(this).attr('data-catid'));
console.log(order[i], ' ', cat_id[i], ' ', i);
if(checker == false){
if(cat_id[i] == change_id){
checker = true;
}else{
order[i] = order[i] + 1 ;
}
}else{
order[i] = order[i] - 1;
}
//console.log(order[i], ' ', cat_id[i], ' ', i);
});
});
You can do that with jQuery
//Sort alphabetically the contact list in the biography page
function sortList() {
//Replace #list by the id of the div who enclose your select
$("#list").html(
$(".form-control").children("option").sort(function (a, b) {
return $(a).text().toUpperCase().localeCompare(
$(b).text().toUpperCase());
})
);
};

Display items of drop down based on each other

1) I have two drop downs with exactly the same values. I want the drop down 2 to display the values based on the selection of items of drop down 1. So the selected index of drop down 2 will be equal to or more than the selected index of drop down 1. ( this code is working)
but When I add one more drop down and based on its items the other two dropdowns should behave as:
2) If I select TCD in the first Dropdown and change to value B in the second dropdown the value should be B in the third dropdown too but If I select BCD from the first dropdown it should retain the values of other two dropdown from the previous selection.( should not go back to A)
The first part is working but the second part is having issues.
Fiddle : 1) http://jsfiddle.net/wtLm4805/2/
Fiddle with three dropdowns : 2) http://jsfiddle.net/wtLm4805/3/
while (select2.firstChild) {
select2.removeChild(select2.firstChild);
}
for (var i = 0; i < select1.options.length; i++) {
var o = document.createElement("option");
o.value = select1.options[i].value;
o.text = select1.options[i].text;
(i < select1.selectedIndex)
? o.disabled = true
: o.disabled = false ;
select2.appendChild(o);
}
Where am I going wrong ?
You can go somewhere along these lines
var typeValue = 'TCD'; // default initialisation
$('#Type').change(function(){
var value = $(this).val();
console.log(value);
if(value == 'TCD')
{
typeValue = 'TCD';
// change something in other selects too
}
else if(value == 'MCD')
{
typeValue = 'MCD';
}
else if(value == 'BCD')
{
$('#SELECTA').val('B');
$('#SELECTB').val('B');
typeValue = 'BCD';
}
});
$('#SELECTA').change(function(){
var value = $(this).val();
console.log(value);
if(typeValue = 'TCD')
{
$('#SELECTB').val(value);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select name="Type" id="Type" >
<option value="TCD">TCD</option>
<option value="MCD" >MCD</option>
<option value="BCD" >BCD</option>
</select>
<select id="SELECTA" class="SELECTA">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
<select id="SELECTB" class="SELECTB" >
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
Since you have only one element with class SELECTA and one with class SELECTB, these will always be undefined:
var select1 = document.getElementsByClassName("SELECTA")[1];
var select2 = document.getElementsByClassName("SELECTB")[1];
var select1 = document.getElementsByClassName("SELECTA")[2];
var select2 = document.getElementsByClassName("SELECTB")[2];
If you're trying to target the options, you could move the classes to the options themselves, or you could reference them like this:
document.getElementsByClassName("SELECTA")[0].options[1]
Not sure why you're deleting/adding items to the SELECTB element, but is this what you're going for?
function clickButton() {
var Type= document.getElementById('Type');
var select1= document.getElementById('SELECTA');
var select2= document.getElementById('SELECTB');
if(Type.value === 'TCD') {
for(var i = 0 ; i < select1.options.length ; i++) {
select2.options[i].disabled= i < select1.selectedIndex;
}
select2.value= select1.value;
}
else {
for(var i = 0 ; i < select2.options.length ; i++) {
select2.options[i].disabled= false;
}
}
}
<select name="Type" id="Type" onchange="clickButton()">
<option value="TCD">TCD</option>
<option value="MCD">MCD</option>
<option value="BCD">BCD</option>
</select>
<select id="SELECTA" onchange="clickButton()">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
<select id="SELECTB">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>

Can I pass multiple Id's inside a document.getelementbyID?

I have a form which has got 45 dropdownlist and I m using the bottom code for its
validation.
how can I use only one function of bottom code to do validation for all of my 45 dropdownlist ??
Here is the Function
function Validate()
{
var e = document.getElementById("dropdownlistone");
var strUser = e.options[e.selectedIndex].value;
var strUser1 = e.options[e.selectedIndex].text;
if(strUser==0)
{
alert("Please select a user");
}
}
----- HTML CODE
<select id="dropdownlistone">
<option value="0">Select</option>
<option value="1">test1</option>
<option value="2">test2</option>
<option value="3">test3</option>
</select>
<input type="button" onClick="Validate()" value="select"/>
This is a case when you need to use classes. Then use querySelectorAll method:
function Validate() {
var e = document.querySelectorAll(".dropdownlistone");
for (var i = 0; i < e.length; i++) {
var strUser = e[i].options[e[i].selectedIndex].value;
var strUser1 = e[i].options[e[i].selectedIndex].text;
if (strUser == 0) {
alert("Please select a user");
return;
}
}
}
Demo: http://jsfiddle.net/cwNaH/
And here is one more example with more user friendly validation messages: http://jsfiddle.net/cwNaH/1/
You can use DOM Method getElementsByTagName for select box and set an data-attr to "validate" for those whom you want to validate, if you dont want it to be validate simply don't add the above mentioned attribute.
Ex. HTML
<select id="sel1" data-attr="validate">
<option value="0">Select</option>
<option value="1">test1</option>
<option value="2">test2</option>
<option value="3">test3</option>
</select>
<select id="sel2" data-attr="validate">
<option value="0">Select</option>
<option value="1">test1</option>
<option value="2">test2</option>
<option value="3">test3</option>
</select>
JavaScript
function validate()
{
var ele = document.getElementsByTagName("select");
for(var i=0;i<ele.length;i++)
{
if(ele.getAttribute("data-attr") && ele.getAttribute("data-attr")=='validate')
{
// you have all 47 select boxes whoose data-attr is validate
// each select box will be in ele[i]
var value= ele[i].options[ele[i].selectedIndex].value;
var text= ele[i].options[ele[i].selectedIndex].text;
alert( value+ " : " + text);
}
}
}

Categories

Resources