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

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);
}
}
}

Related

How to get the same value populated in 2nd picklist if the value is selected on 1st picklist using JavaScript

I have 2 picklists with the same values. In the 1st picklist, it has more values than the 2nd picklist. So when the user selects some value from the 2nd picklist, it is showing the same value in the 1st one.
But I would like to show if the value Testing 1 is selected in picklist 1 then the same value should show in the 2nd picklist. If the user selects Testing 2 from the 1st picklist then the 2nd picklist should also show the same value.
Not sure how to achieve this. Could someone help me with this?
var sMap = {};
sMap["ABC"] = ["Test2ABC", "Style"];
sMap["CDE"] = ["Test2CDE", "style"];
sMap["EFG"] = ["Test2EFG", "style"];
function onChangeRadio(ele) {
var id = $(ele).attr("id");
var type = $(ele).attr("type");
var tagName = $(ele).prop("tagName");
if (tagName.toLowerCase() == "select") {
var val = $(ele).val();
$('#codes').append($("<option value='" + val + "'>" + val + "</option>"));
setsc(val);
} else {
var Code = Object.keys(sMap).find(key => sMap[key].includes(id));
setsc(Code);
}
}
function setsc(val) {
$('[name="Code"]').val(val);
window.dispatchEvent(new Event('resize'));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<td id="TD1">
<input type="hidden" name="Test1" id="hidden-test1" value="">
<input list="codes" name="Code" id="slist" class="Mandatory">
<datalist id="codes">
<option value="">-- Choose one --</option>
<option value="ABC">Testing 1</option>
<option value="CDE">Testing 2</option>
<option value="EFG">Testing 3</option>
<option value="ABC">worker</option>
<option value="NAP">Port</option>
</datalist>
</td>
<select name="T-Test2" id="Test2" onchange="onChangeRadio(this)">
<option value="" selected="">Choose one</option>
<option value="ABC">Testing 1</option>
<option value="CDE">Testing 2</option>
<option value="EFG">Testing 3</option>
</select>
You need to detect the onchange event on the datalist. You do that by checking the input event on the <input>.
You can use the inputType on the InputEvent to filter out any unwanted onInput events. This is "insertReplacementText" on Firefox 81 and null for Chrome/Edge 86. If you need to support IE11 you will need to validate the value is valid.
$("#slist").on("input", (event) => {
// Detect change on the datalist
if (event.inputType == "insertReplacementText" || event.inputType == null) {
console.log(event.target.value);
})
Other explains areinside the below code.
var sMap = {};
sMap["ABC"] = ["Test2ABC", "Style"];
sMap["CDE"] = ["Test2CDE", "style"];
sMap["EFG"] = ["Test2EFG", "style"];
function onChangeRadio(ele) {
var id = $(ele).attr("id");
var type = $(ele).attr("type");
var tagName = $(ele).prop("tagName");
if (tagName.toLowerCase() == "select") {
var val = $(ele).val();
$('#codes').append($("<option value='" + val + "'>" + val + "</option>"));
setsc(val);
} else {
var Code = Object.keys(sMap).find(key => sMap[key].includes(id));
setsc(Code);
}
}
function setsc(val) {
$('[name="Code"]').val(val);
window.dispatchEvent(new Event('resize'));
}
$("#slist").on("input", (event) => {
// Detect change on the datalist
if (event.inputType == "insertReplacementText" || event.inputType == null) {
let selectedValue = event.target.value;
if (!selectedValue) return;
// Get the text of the option associate with the value
let optionData = $(`#codes > option[value="${selectedValue}"]`).text();
console.log(optionData);
// Append in the <select>
// if the otpion is not existed, use a temporary attribute, so we can clear it out later
let selectedOption = $(`#Test2 > option[value="${selectedValue}"]`)[0];
if (selectedOption) {
// selected option exists, show it
selectedOption.selected = 'selected';
} else {
// selected option doesn't exist, add then show
// Clear the temporary options out of the select
$('#Test2 > [temporary="true"]').remove();
$('#Test2').append($('<option>', {
value: selectedValue,
text: optionData,
selected: true,
temporary: true,
}));
}
}
});
// Whenever you change the value on the select, clear out the temporary options
$('#Test2').on('change', (e) => {
$('#Test2 > [temporary="true"]').remove();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<td id="TD1">
<input type="hidden" name="Test1" id="hidden-test1" value="">
<input list="codes" name="Code" id="slist" class="Mandatory">
<datalist id="codes">
<option value="">-- Choose one --</option>
<option value="ABC">Testing 1</option>
<option value="CDE">Testing 2</option>
<option value="EFG">Testing 3</option>
<option value="HIJ">worker</option>
<option value="NAP">Port</option>
</datalist>
</td>
<select name="T-Test2" id="Test2" onchange="onChangeRadio(this)">
<option value="" selected="">Choose one</option>
<option value="ABC">Testing 1</option>
<option value="CDE">Testing 2</option>
<option value="EFG">Testing 3</option>
</select>

How to link to form select option dropdowns

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)

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>

Javascript: Dynamically add fields from a select input with a button

i need to add dynamically fields from a list values, i have this one:
HTML:
<select name="list">
<option>Select One</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
JS:
$("[name=list]").on("change", function (e) {
var val = $(this).val();
if (val.length > 0) {
$("<input>").attr("name", "the-name").val(val).appendTo($("#the-form"))
}
});
This works fine, but i want to add a "Add field" button to do this, how i can do that?
Its just simple. Instead of writing your code into onchange, you bind it to click event of your button.
For example, say you have button with id - #addField. Your click event for button would be
$("#addField").on('click',function(){
var val = $("[name=list]").val(); //get the selected val from select element
if (val.length) {
$("<input>").attr("name", "the-name").val(val).appendTo($("#the-form"))
}
});
You will move the logic of the .change() event of select to the .click() event of the button.
something similar to:
$("#btnId").on("click", function (e) {
var val = $("[name=list]").val();
if (val.length > 0) {
$("<input>").attr("name", "the-name").val(val).appendTo($("#the-form"))
}
});
where btnId is the id of the button
try this : https://jsfiddle.net/qact415y/
<select id="list">
<option>Select One</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
// enter the text you want to add to the combo
<input type="text" id="input"/>
<button name="add">Add</button>
$("[name=list]").on("change", function (e) {
var val = $(this).val();
if (val.length > 0) {
$("<input>").attr("name", "the-name").val(val).appendTo($("#the-form"))
}
});
$("[name=add]").on("click", function (e) {
console.log("add");
var x = document.getElementById("list");
var option = document.createElement("option");
option.text = document.getElementById("input").value;
x.add(option);
});

How to get selected values in SumoSelect dropdown?

I am using the SumoSelect dropdown for multiselect options. But i cannot get the selected values array.
Below the sample code :
<script type="text/javascript">
$(document).ready(function () {
window.testSelAll = $('.testSelAll').SumoSelect({okCancelInMulti:true, selectAll:true });
$('.btnOk').on('click', function(){
var obj = [];
$('option:selected').each(function () {
obj.push($(this).index());
alert("Selected Values=="+$(this).val());
});
for (var i = 0; i < obj.length; i++) {
$('.testSelAll')[0].sumo.unSelectItem(obj[i]);
}
});
});
</script>
<select multiple="multiple" placeholder="Share Your Friends" onchange="console.log($(this).children(':selected').length)" class="testSelAll">
<option value="1">Volvo</option>
<option value="2">Saab</option>
<option value="3">Mercedes</option>
<option value="audi">Audi</option>
<option value="bmw">BMW</option>
<option value="porsche">Porche</option>
<option value="ferrari">Ferrari</option>
<option value="mitsubishi">Mitsubishi</option>
</select>
If you want the selected values instead of the text, just change .text() to .val().
If you want to get the array, see below with working example at the bottom.
jQuery
$(document).ready(function() {
$('.testSelAll').SumoSelect({
okCancelInMulti: true,
selectAll: true
});
$('.btnOk').on('click', function() {
var obj = [],
items = '';
$('.testSelAll option:selected').each(function(i) {
obj.push($(this).val());
$('.testSelAll')[0].sumo.unSelectItem(i);
});
for (var i = 0; i < obj.length; i++) {
items += ' ' + obj[i]
};
alert(items);
});
});
HTML
<select multiple="multiple" class="testSelAll">
<option value="car1">Volvo</option>
<option value="car2">Saab</option>
<option value="car3">Mercedes</option>
<option value="car4">Audi</option>
</select>
Working JSFIDDLE
You can get them from underlying hidden select element.
using jquery eg.
$('.select1 option:selected')
I think the cleanest way to do this. Is to take advantage of html5 select element underlying SumoSelect.
HTML
<select multiple="multiple" class="testSelAll" id="multi-select">
<option value="car1">Volvo</option>
<option value="car2">Saab</option>
<option value="car3">Mercedes</option>
<option value="car4">Audi</option>
</select>
Javascript
var values = $('#multi-select').val();
This line will return a string list of the values selected.

Categories

Resources