Dropdown validation, focus method doesn't work - javascript

I want someone to select an option, but not the first option -- Select --.
HTML
<select name = "sources" id = "brandname" required onblur = "selectText()" />
<option value = "select"> -- Select -- </option>
<option value = "referal"> Referal </option>
<option value = "justdial"> Justdial </option>
<option value = "sulekha"> Sulekha </option>
<option value = "website"> Website </option>
<option value = "others"> Others </option>
</select>
JS
if (document.getElementById("brandname").value == "select") {
alert("Please select the required value");
document.getElementById("brandname")[1].focus();
}
It executes the alert message, after that it moved to the next field. But it supposed to be sticked with that dropdown until and unless the select value changed to any other value.
What is wrong with the code?
Thanks in advance!

HTML
<select id="mySelect">
<option>v1</option>
<option>v2</option>
...
</select>
JavaScript
var s = document.getElementById("mySelect");
Check the selected value with
s.options[s.selectedIndex].value // Keep this in mind
If statement:
if(s.options[s.selectedIndex].value == "select") {
alert("A value is required!");
s.focus();
}
(Your focus without [1]:
document.getElementById("brandname").focus();
)
Demo

Just remove the [1] from the focus statement.As getElementById always returns single object.
var selectText =function(){
if(document.getElementById("brandname").value == "select") {
alert("Please select the required value");
document.getElementById("brandname").focus();
}}
<select name = "sources" id = "brandname" required onblur = "selectText()" />
<option value = "select"> -- Select -- </option>
<option value = "referal"> Referal </option>
<option value = "justdial"> Justdial </option>
<option value = "sulekha"> Sulekha </option>
<option value = "website"> Website </option>
<option value = "others"> Others </option>
</select>

Related

How to refresh a select list in html

I have a drop-down list where depending on the selected value, the next drop-down list shows specific values. when changing the value of the first list and then going back to the old value, the second list does not update. keeps the same value selected before. How can I make the second list update to the value I marked as selected by default whenever I change the value of the first list?
I hope you guys were able to understand me, and I thank you for your time.
Here's the code:
<select onchange="showprd('hidevalue', this), showprd2('hidevalue2', this)">
<option value="" disabled selected hidden>Selecione</option>
<option value="0">São Francisco</option>
<option value="1">Bradesco</option>
</select>
<br>
<br>
<select hidden id="hidevalue">
<option value="" disabled selected hidden>Selecione o produto</option>
<option value="pleno">Pleno</option>
<option value="integrado">Integrado</option>
</select>
<select hidden id="hidevalue2">
<option value="" disabled selected hidden>Selecione o produto</option>
<option value="junior">Junior</option>
<option value="senior">Senior</option>
</select>
</body>
<script>
function showprd(id, elementValue) {
document.getElementById(id).style.display = elementValue.value == 0 ? 'block' : 'none';
}
function showprd2(id, elementValue) {
document.getElementById(id).style.display = elementValue.value == 1 ? 'block' : 'none';
}
</script>
TL;DR. Control the input value changes in one place.
Please see the updated snippet below. html structure hasn't been changed, but I've removed the inline js call and updated the id names. JavaScript blocks are commented in details.
In a nut-shell, this code listens for any change to the parent select dropdown. Whenever a change occurs, its child dropdowns will reset their values and toggle their visibility accordingly.
// Assign each dom element to a variable
const primarySelect = document.querySelector('#primary');
const childSelect1 = document.querySelector('#child1');
const childSelect2 = document.querySelector('#child2');
const defaultValues = document.querySelectorAll('.default');
function resetInputs() {
// Reset the child select options to default
defaultValues.forEach(option => option.selected = true);
}
function handlePrimary(e) {
// Reset the child select values whenever the parent value changes
resetInputs();
// `input` value is always a string. Here we're converting it to a number
const val = parseFloat(e.target.value);
// Toggle visibility of child select dropdowns
[childSelect1, childSelect2].
forEach((select, i) => select.style.display = val === i ? 'block' : 'none');
}
primarySelect.addEventListener('change', handlePrimary);
<select id="primary">
<option value="" disabled selected hidden>Selecione</option>
<option value="0">São Francisco</option>
<option value="1">Bradesco</option>
</select>
<br>
<br>
<select hidden id="child1">
<option class="default" value="" disabled selected hidden>Selecione o produto</option>
<option value="pleno">Pleno</option>
<option value="integrado">Integrado</option>
</select>
<select hidden id="child2">
<option class="default" value="" disabled selected hidden>Selecione o produto</option>
<option value="junior">Junior</option>
<option value="senior">Senior</option>
</select>
If I understood correctly, the expected behavior is when the second or third <select> is hidden, the <select> should go back to default (the first <option>?). If so, then remove disabled and hidden from the first <option> of the second and third <select> then add the following:
selectObj.hidden = true;
selectObj.selectedIndex = 0;
The example below has a <form> wrapped around everything (always use a form if you have more than one form control. By using HTMLFormElement interface I rewrote the code and can reference all form controls with very little code. Inline event handlers are garbage so don't do this:
<select id='sel' onchange="lame(this)">
Instead do this:
selObj.onchange = good;
OR
selObj.addEventListener('change', better)
Read about events and event delegation
const UI = document.forms.UI;
UI.onchange = showSelect;
function showSelect(e) {
const sel = e.target;
const IO = this.elements;
if (sel.id === "A") {
if (sel.value === '0') {
IO.B.hidden = false;
IO.C.hidden = true;
IO.C.selectedIndex = 0;
} else {
IO.B.hidden = true;
IO.B.selectedIndex = 0;
IO.C.hidden = false;
}
}
}
<form id='UI'>
<select id='A'>
<option disabled selected hidden>Pick</option>
<option value="0">0</option>
<option value="1">1</option>
</select>
<br>
<br>
<select id="B" hidden>
<option selected>Pick B</option>
<option value="0">0</option>
<option value="1">1</option>
</select>
<select id="C" hidden>
<option selected>Pick C</option>
<option value="0">0</option>
<option value="1">1</option>
</select>
</form>
I give you an example for your reference:
let secondList = [
[{
value: "pleno",
text: "Pleno"
},
{
value: "integrado",
text: "Integrado"
}
],
[
{
value: "junior",
text: "Junior"
},
{
value: "senior",
text: "Senior"
}
]
]
function update(v){
let secondSelectBox=document.getElementById("second");
secondSelectBox.style.display="none";
let optionList=secondList[v.value];
if (optionList){
let defaultOption=new Option("Selecione o produto","");
secondSelectBox.innerHTML="";
secondSelectBox.options.add(defaultOption);
optionList.forEach(o=>{
let vv=new Option(o.text,o.value);
secondSelectBox.options.add(vv);
})
secondSelectBox.style.display="block";
}
}
<select onchange="update(this)">
<option value="" disabled selected hidden>Selecione</option>
<option value="0">São Francisco</option>
<option value="1">Bradesco</option>
</select>
<select hidden id="second">
</select>

Change text within Label to option from selection menu

This my custom select menu:
<select name="bankSelect" id="bankSelect" onchange="dispchange(this.form.bankSelect)">
<option>EQUIFAX</option>
<option value = 5 >EQUIFAX</option>
<option value = 6>TRANSUNION</option>
<option value = 7>EXPERIAN</option>
<option value = 8>BANK OF AMERICA</option>
<option value = 9>WELLS FARGO</option>
<option value = 10>CITIBANK</option>
<option value = 11>JPMORGAN</option>
<option value = 12>NAVIENT</option>
<option value = 13>CAPITAL ONE</option>
<option value = 14>U.S BANCORP</option>
</select>
This is my label:
<div class="info">
<label>Bank: </label>
<label id="bank">EQUIFAX</label><br>
</div>
I need to change the text within label with the ID='bank to the option i select from the menu i above.
So if i pick the option with value 9, then my label should change the text it's displaying by defualt,'EQUIFAX' to then display 'WELLS FARGO'.
This is what I've tried in my java-script based on googling similar questions:
function dispchange(bankSelect) {
var bsel_index = bankSelect.selectedIndex;
var bselin = bankSelect.options[bsel_index].value;
if(bselin == '6')
document.getElementById("bank").innerHTML = 'Transunion';
else if(opcao == '1')
document.getElementById('complemento').innerHTML = 'Titulo';
}
It does nothing. What am I doing wrong? Is there a better way / another way to change the label? Can I use something other than a label to display my choice from the selection menu? If so, how do I ensure is always displays the choice currently selected?
use option.text instead of option.value:
function dispchange() {
var el = document.getElementById('bankSelect');
document.getElementById('bank').innerHTML = el.options[el.selectedIndex].text;
}
<select name="bankSelect" id="bankSelect" onchange="dispchange()">
<option>EQUIFAX</option>
<option value="5">EQUIFAX</option>
<option value="6">TRANSUNION</option>
<option value="7">EXPERIAN</option>
<option value="8">BANK OF AMERICA</option>
<option value="9">WELLS FARGO</option>
<option value="10">CITIBANK</option>
<option value="11">JPMORGAN</option>
<option value="12">NAVIENT</option>
<option value="13">CAPITAL ONE</option>
<option value="14">U.S BANCORP</option>
</select>
<div class="info">
<label>Bank: </label>
<label id="bank">EQUIFAX</label><br>
</div>
function dispchange(bankSelect) {
console.log(document.getElementById("bankSelect").value)
document.getElementById('bank').innerHTML = document.getElementById("bankSelect").value;
}
<select name="bankSelect" id="bankSelect" onchange="dispchange()">
<option value="EQUIFAX">EQUIFAX</option>
<option value="TRANSUNION">TRANSUNION</option>
<option value ="EXPERIAN">EXPERIAN</option>
<option value= "BANK OF AMERICA">BANK OF AMERICA</option>
<option value ="WELLS FARGO">WELLS FARGO</option>
</select>
<div class="info">
<label>Bank: </label>
<label id="bank">EQUIFAX</label><br>
</div>
If you can change the value of the options from number to the Bank name then the following code is going to work as you need.
Otherwise, you have to create an array or object with the numbers and Bank names.
Is the above code work for you?

Show Value Instead of text in select option

I have country codes dropdown list, in select option text there countryname and ISD Code together, but I want only show ISD Code after Selection.
<select class="form-control-input" name="country_isd_code" id="country_isd_code">
<option value="">Country Code</option>
<option value="+244">Angola (+244)</option>
<option value="+1">Anguilla (+1)</option>
</select>
I have searched for some other forums but I am not able to get how to do this. like if we select Anguilla, then it should show +1 there and if it is selected Angola, it should show +244
A solution with only a <select> element.
How it works:
Initializes a hidden <option> that will be used for showing the selected option's value.
When an option is selected:
affects to the hidden option's value attribute and text content the value attribute of the just selected option if this value is not empty. Then shows that hidden option.
empties value and text content of that option, then hides it, if the chosen value is empty (Country code option here).
document.addEventListener('DOMContentLoaded', () => {
const select = document.querySelector('select');
select.addEventListener('change', () => {
const value = select.value,
showValueOption = select.querySelector('.show-value');
if (value === '') {
showValueOption.style.display = 'none';
showValueOption.value = '';
return;
}
showValueOption.style.display = '';
showValueOption.innerText = value;
showValueOption.value = value;
select.selectedIndex = 0;
});
});
<select class="form-control-input" name="country_isd_code" id="country_isd_code">
<option class="show-value" value="" style="display:none;"></option>
<option value="" selected>Country Code</option>
<option value="+244">Angola (+244)</option>
<option value="+1">Anguilla (+1)</option>
</select>
You can handle change event of select tag like this.
I updated code for display selected value as selected text.
$("#country_isd_code").change(function(){
$("#codeselect").val($(this).val());
})
$("#country_isd_code").change(function(){
$("#codeselect").val($(this).val());
//$("#country_isd_code option:selected").text($(this).val());
$("#selecteditem").val($(this).val())
$("#selecteditem").text($(this).val())
$("#selecteditem").prop('selected', true);
$("#selecteditem").show();
})
#selecteditem{
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="form-control-input" name="country_isd_code" id="country_isd_code">
<option id="selecteditem" value=""></option>
<option value="">Country Code</option>
<option value="+244">Angola (+244)</option>
<option value="+1">Anguilla (+1)</option>
</select>
<input type="text" id="codeselect" />

javascript to dynamically change the dropdown

Attached the screenshot of my web page.
In that picture, under Regression type dropdown list box, there are three values consider 1, 2 and 3
So if I select 1 or 2, drop down below that "F1" should not appear. If value3, then it should appear.
To do this I have added onload under body tag.
HTML CODE:
<div class = "cl-regr" id="div-regr">
<select name = "regr" id="drop-regr">
<option selected="selected" disabled>-----Select-----</option>
<option value = "1"> ips </option>
<option value = "2"> ips sanity </option>
<option value = "3"> Features </option>
</select>
</div>
<div class = "cl-ftr" id="div-ftr" onchange="displayFeatureList()">
<select name = "ftr" class = "cl2" id="drop-ftr">
<option value = "f1"> F1 </option>
<option value = "f2"> F2 </option>
<option value = "f3"> F3 </option>
<option value = "f4"> F4 </option>
</select>
</div>
RESPECTIVE SCRIPT IN SEPARATE .js FILE:
function func1(){
$(".cl-ftr").each(function() {
var that = $(this);
that.find("div.cl2").style.visibility="hidden";
});
};
function displayFeatureList(){
var d_obj = document.getElementById("drop_reg").value;
var op = d_obj.options[d_obj.selectedIndex].value;
if (op == 3){
document.getElementById("drop_ftr").style.visibility = 'visible';
}
else{
document.getElementById("drop_ftr").style.visibility = 'hidden';
}
};
where I'm calling func1 from body tag
<body onload="func1()">
Problems I'm facing are,
1)Whenever the page loads, the "F1" dropdown list box of first row is hiding (ie, ClientIP - 10.213.174.90)
2) If I change the value, displayFeatureList function is not making any effects.
Any help would be much appreciated!!
you are syntax was wrong
$(this) is jquery object style.visiblity its dom function
Use with css() jquery function .style.visiblity is not a jquery object.
For better my suggestion use css .cl2{visiblity:hidden} instead of js
cl2 class in select element not with div so remove the div with cl2 in selector like find('cl2')
fix the id name typo - instead of _
Add change event with first select
Get the value from dropdown direct call the selectelement.value.no need specify index
function func1() {
$(".cl-ftr").each(function() {
var that = $(this);
that.find(".cl2").css('visibility', "hidden");
});
};
function displayFeatureList() {
var d_obj = document.getElementById("drop-regr").value
if (d_obj == '3') {
document.getElementById("drop-ftr").style.visibility = 'visible';
} else {
document.getElementById("drop-ftr").style.visibility = 'hidden';
}
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body onload="func1()">
<div class="cl-regr" id="div-regr">
<select name="regr" id="drop-regr" onchange="displayFeatureList()">
<option selected="selected" disabled>-----Select-----</option>
<option value = "1"> ips </option>
<option value = "2"> ips sanity </option>
<option value = "3"> Features </option>
</select>
</div>
<div class="cl-ftr" id="div-ftr" >
<select name="ftr" class="cl2" id="drop-ftr">
<option value = "f1"> F1 </option>
<option value = "f2"> F2 </option>
<option value = "f3"> F3 </option>
<option value = "f4"> F4 </option>
</select>
</div>
With all respect, your code quality is not very good.
It's filled with typos (changing _ to -, missing single letters for ids etc.) This way, nothing will ever work. Take more care.
An id has to be unique. If an id appears twice in the same HTML document,
the document is not valid by definition. (It still loads though, but you have to expect errors.) You maybe want to keep the ids an add a dynamic number (row number)to keep them unique
If you use jQuery, use it by default. Don't mix up jQuery(func1()) and JS DOM methods(displayFeatureList)
I reduced your code to the following (I commented the whole JS code for better understanding):
$(document).ready(function() { //run when page loading is complete
$(".regessionTypeCell").each(function() { //for each regessionTypeCell class (parent div, might be a table cell in your case)
$(this).find(".drop-regr").change(function(event) { //set onChange function for the containing drop-regr class
var conditionalDropdown = $(this).find(".cl-ftr"); //get the conditional dropdown element
if ($(this).find(".drop-regr").val() == 3) { //if selected index is equal 3
conditionalDropdown.show(); //show dropdown
} else {
conditionalDropdown.hide(); //hide dropdown
}
}.bind($(this))); //bind this to the inner function
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="regessionTypeCell">
<div class="cl-regr">
<select name="regr" class="drop-regr">
<option selected="selected" disabled>-----Select-----</option>
<option value="1"> ips </option>
<option value="2"> ips sanity </option>
<option value="3"> Features </option>
</select>
</div>
<div class="cl-ftr" style="display:none">
<select name="ftr" class="drop-ftr">
<option value="f1"> F1 </option>
<option value="f2"> F2 </option>
<option value="f3"> F3 </option>
<option value="f4"> F4 </option>
</select>
</div>
</div>
<div class="regessionTypeCell">
<div class="cl-regr">
<select name="regr" class="drop-regr">
<option selected="selected" disabled>-----Select-----</option>
<option value="1"> ips </option>
<option value="2"> ips sanity </option>
<option value="3"> Features </option>
</select>
</div>
<div class="cl-ftr" style="display:none">
<select name="ftr" class="drop-ftr">
<option value="f1"> F1 </option>
<option value="f2"> F2 </option>
<option value="f3"> F3 </option>
<option value="f4"> F4 </option>
</select>
</div>
</div>

using 'required' for 'select' tag

How can I use required with the below code of select. I had values for all options. As for required to work, default selected option should have empty value. How can I get the required working without removing value of any option? Is there some tweak ?
<select required>
<option value = "-1" selected> </option>
<option value = "1"> one </option>
<option value = "2"> two </option>
</select>
In most modern browsers, a form containing an element with required will not submit until it has a value.
To make select work like that use an empty string as the value for the default item:
<select required>
<option value = "" selected> </option>
<option value = "1"> one </option>
<option value = "2"> two </option>
</select>
Live example: https://jsfiddle.net/zu80u9my/ (Form will not submit if a value has not been selected)

Categories