I want show or hide an input by selecting an option in a select if value = 4 or 8, then show the inputs. I know that I have to work with the css (display: "block/none") but my onchange seems to not be working. When I use radio button, it works with an onclick.
Here's my code:
function WorkTravelControl() {
window.addEventListener("load", function() {
document.getElementById("homeworkingselect")
.addEventListener("change", function() {
var value = document.getElementById("homeworking").value
if (value === 0) {
document.getElementById("homeworking").style.display.none
} else {
document.getElementById("homeworking").style.display.inline
}
});
});
}
<!-- probleme de visbilité des elements -->
<select name="homeworkingselect" value="0" onchange="WorkTravelControl()">
<option value="0" selected></option>
<option value="4">4</option>
<option value="8">8</option>
</select>
</td>
<td>
<input type="text" ng-model="outsideluxWork.value" id="homeworking"></td>
</td>
<td>
<input type="text" ng-model="outsideluxTravel.value" id="homeworking"></td>
</tr>
can someone help with the Javascript going with?
You have an event handler wrapped in a function called by an inline event handler. So try getting rid of the onchange in the select and don't have window.addEventListener("load" wrapped in a function. Also add id="homeworkingselect" to your select since that is what the event listener is looking for. You are also reusing IDs, but you can't duplicate IDs.
I used a class for the text elements and looped through the text elements on change.
window.addEventListener("load", function() {
document.getElementById("homeworkingselect").addEventListener("change", function(e) {
value = e.target.value;
homeworking = document.querySelectorAll(".homeworking");
homeworking.forEach(function(el) {
el.style.display = (value == 0) ? "none" : "inline";
});
});
});
<select name="homeworkingselect" id="homeworkingselect">
<option value="0" selected></option>
<option value="4">4</option>
<option value="8">8</option>
</select>
<input type="text" ng-model="outsideluxWork.value" class="homeworking">
<input type="text" ng-model="outsideluxTravel.value" class="homeworking">
Related
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>
I have a datalist that looks like :
<datalist id="foodlist">
<option value="one" ></option
<option value="two" ></option>
<option value="three" ></option>
</datalist>
<input type="text" list="foodlist" autocomplete=true id="inputItem"/>
I want an event to fire when user selects on of the option in the list using JavaScript.
How to achieve it?
onClick, onChange does not seem to work.
I know this is kind of old, but I thought I should document it somewhere. If you're trying to detect input from a dropdown selection rather than a click per se, you can use the "input" event and check the type of the passed event object - cut/paste/keypress input will pass an "InputEvent" object, whereas a datalist selection will pass a generic "Event" object.
var textbox = document.getElementById("inputItem");
textbox.addEventListener("input", function(e){
var isInputEvent = (Object.prototype.toString.call(e).indexOf("InputEvent") > -1);
if(!isInputEvent)
alert("Selected: " + e.target.value);
}, false);
<datalist id="foodlist">
<option value="one" ></option>
<option value="two" ></option>
<option value="three" ></option>
</datalist>
<input type="text" list="foodlist" autocomplete=true id="inputItem"/>
<datalist id="foodlist">
<option value="one" ></option>
<option value="two" ></option>
<option value="three"></option>
</datalist>
<input id="txt" type="text" list="foodlist" autocomplete=true id="inputItem"/>
document.getElementById('txt').addEventListener('input', function () {
console.log('changed');
var val = document.getElementById("txt").value;
alert(val);
});
The datalist tag is only supported in some browsers. Here's simple trick to get selected value.
While this is 4 years old, I stumbled across it today, and ran into the cross browser issues that others have reported. I was able to solve this by listening to the keyup event on the input field, and then checking the event type.
<input type="text" name="field_name" id="field_id" list="fields_list">
<datalist id="fields_list"></datalist>
<script>
var fieldInput = document.getElementById("field_id");
fieldInput.addEventListener('keyup', function(e) { if (isKeyboardEvent(e)) { myFunction(); } });
function isKeyboardEvent(e) {
return (e instanceof KeyboardEvent);
}
function myFunction() {
/* function that does something only on keyboard input */
}
</script>
Actual key strokes will be KeyboardEvent while a datalist option click will be simply be an Event.
Confirmed working in Chrome, Firefox, and Edge.
I have one dropdown upon selection of which I want to copy the value of that dropdown and paste in an input field below without using clt+v every time
Here is the code what I tried:
$('body').append(`<div id="selectDialog" title="Select Regex Type" style="text-align:center;display:none;">
<select id="listSelection">
<option value ="">None</option>
<option value ="[a-z]+">Single Digit Integers</option>
<option value ="^[0-9]">Multi Digit Number</option>
<option value ="/^-?[0-9]+\.?[0-9]*$/">Decimal Number</option>
</select>
<div style="margin:10px">
<button id="closeSelection" style="background-
color:#3B5E9E" >save</button>
</div>
</div>`);
$(function () {
$("#selectDialog").dialog({
autoOpen: false,
});
$('#changePattern').on("click", function () {
$("#selectDialog").dialog("open");
});
$("#listSelection")
.change(function () {
var s = $("#listSelection option:selected").val();
$("#changePattern").val(s);
$("#changePattern").attr("patternMask" , s);
$('#changePattern').select();
document.execCommand("copy");
$('#reg').select();
})
.trigger("change");
$('#reg').select( function (){
/*here I am trying to copy using document.texecCommand("copy");
but unable to copy*/
});
$('#closeSelection').on("click", function () {
$("#selectDialog").dialog("close");
});
});
});
on clicking input having an id changePattern , i am opening an dropdown from which i am populating another field with id =reg
h i am saving a pattern to:
<input id="changePattern" />
<input id="reg" />
<input type="hidden"> or <input hidden>
.on() change of select store it's selected value to a hidden input. then register the inputs to the click event. Whenever a click happens on those inputs the value of the hidden input will be pasted to it.
Did you get an .execCommand() to work on an input? document.execCommand() are for contenteditable elements not form elements.
Demo
$('select').on('change', function(event) {
$('#X').val($(this).val());
});
$('input').on('click', function(event) {
if ($('#X').val() !== null) {
$(this).val($('#X').val());
}
});
<input id='X' hidden value=null>
<select>
<option value=''></option>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
</select>
<br><br>
<input>
<input>
<input>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I have been trying for days to get this to work but to no avail! I have two dropdown lists. Depending on the selection of the first defines the content of the second. However I am having trouble selecting the second dropdown.
Here is the simple dropdowns.
<div id="advanced-search" class="advanced-search">
<select name="Attribute" id="Attribute" class="advanced-attribute" onChange="AttributeChange()"></select>
<select name="Operator" id="Operator" class="advanced-operator">
<option value="">Select Attribute First</option>
</select>
</div>
Then using an on change event I want to define the content:
function AttributeChange() {
var SearchAttribute = $(this).find(':selected').attr('type');
if (SearchAttribute = 'varchar') {
$(this).next().find('.advanced-operator').html('<option value="">Select Operator</option><option value="=">Is Equal To</option><option value="!=">Is Not Equal To</option><option value="LIKE">Contains</option><option value="NOT LIKE">Does Not Contain</option><option value="Start">Starts With</option><option value="End">Ends With</option><option value="IS NULL">Is Empty</option><option value="IS NOT NULL">Is Not Empty</option>');
} else {
$('.advanced-attribute').siblings('.advanced-operator').html('<option value="">Select Attribute First</option>');
}
}
NOTE: The options for the first select are pulled from the Database via PHP.
Ignore the IF statement as that is already working and a attribute I have defined in the option tags.
What I cannot do is select the second dropdown universally by class (as there will be multiple select's with the same class) and I wont know the ID, as it is automatically generated.
So I have been trying to get the next element, but i cant seem to get it to work.
Problem with you implementation are
this doesn't refers to element which you think
= is assignment operator where as == is equality.
.advanced-operator is immediate sibling so use $(this).next('.advanced-operator')
Inline events handler have been considered bad practice, and leads to potential issues as in your scenario.
You should use .on() to bind event handler.
$('.advanced-attribute').on('change', function() {
var searchAttribute = $(this).find(':selected').attr('type');
var nextSelector = $(this).next('.advanced-operator');
//You need to use ==
if (searchAttribute == 'varchar') {
nextSelector.html('<option value="">Select Operator</option><option value="=">Is Equal To</option><option value="!=">Is Not Equal To</option><option value="LIKE">Contains</option><option value="NOT LIKE">Does Not Contain</option><option value="Start">Starts With</option><option value="End">Ends With</option><option value="IS NULL">Is Empty</option><option value="IS NOT NULL">Is Not Empty</option>');
} else {
nextSelector.html('<option value="">Select Attribute First</option>');
}
})
$(function() {
$('.advanced-attribute').on('change', function() {
var searchAttribute = $(this).find(':selected').attr('type');
var nextSelector = $(this).next('.advanced-operator');
//You need to use ==
if (searchAttribute == 'varchar') {
nextSelector.html('<option value="">Select Operator</option><option value="=">Is Equal To</option><option value="!=">Is Not Equal To</option><option value="LIKE">Contains</option><option value="NOT LIKE">Does Not Contain</option><option value="Start">Starts With</option><option value="End">Ends With</option><option value="IS NULL">Is Empty</option><option value="IS NOT NULL">Is Not Empty</option>');
} else {
nextSelector.html('<option value="">Select Attribute First</option>');
}
}).change();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="advanced-search" class="advanced-search">
<select name="Attribute" id="Attribute" class="advanced-attribute">
<option type="char">1</option>
<option type="varchar">2</option>
</select>
<select name="Operator" id="Operator" class="advanced-operator">
<option value="">Select Attribute First</option>
</select>
</div>
I have 4 select tag with class name select2 assigned to it. I want to make the border turn to red if there's no selected options or has an value equal to empty or 0. I've tried to add class using jquery but it makes all select.select2 border turns red.
Style
<style>
.errorType {
border-color: #F00 !important;
}
</style>
HTML
<select name="category" class="form-control select2" id="category" onChange="search_Operator(this.value)">
<option value="0"> Select Operator Category</option>
<option value="1">one</option> <option value="2"> two</option>
</select>
<select name="operatorName" class="form-control select2" id="operatorName" onChange="">
<option value="0"> Select operator Name</option>
<option value="1">one</option>
<option value="2"> two</option>
</select>
<select name="regionName" class="form-control select2" id="regionName">
<option value="0"> Select region Name</option>
<option value="1">one</option>
<option value="2"> two</option>
</select>
<select name="type" class="form-control select2" id="type">
<option value="0"> Select type </option>
</select>
JQUERY
$(function () {
$(".select2").select2();
});
$(".select2-selection").addClass('errorType');
Any idea?
Thanks in advance.
I've attached a function to the click event of the submit button, in order to check the value of every select element on the page:
$(function () {
$('.form-control-select2').select2();
$('#submit_btn').on('click', function(){
var submit_form = true;
$(".form-control-select2").each(function(){
var selected_value = $(this).val();
if (selected_value==0 || selected_value=='') {
$(this).next().find('.select2-selection').addClass('errorType');
submit_form = false;
} else {
$(this).next().find('.select2-selection').removeClass('errorType');
}
});
return submit_form;
});
});
Fiddle here: https://jsfiddle.net/64a41thz/21/.
Also, if you want to remove the red border when valid selection is made, add the following code:
$('.form-control-select2').on('change', function(){
if ($(this).val()!=0 && $(this).val()!='') {
$(this).next().find('.select2-selection').removeClass('errorType');
}
});
Fiddle here: https://jsfiddle.net/64a41thz/24/.
This does the trick. You just need to replace #yourButton with the actual ID you use.
$(document).on("click", "#yourButton", function() {
$(".select2").each(function(index, element) {
$(element).removeClass("errorType");
if ($(element).val() === "0") {
$(element).addClass("errorType");
}
});
});
Put your select tag inside a form with an id="submit" as shown
<form class="" action="" method="post" id="submit">
and add a button below the 4 select tags with this attribute
onclick="return submit_form('form#submit')"
the button should be like this,
<button type="button" class="btn btn-default" onclick="return submit_form('form#submit')">Submit</button>
In your jquery
function submit_form (form_id) {
$(form_id).find('select[name]').each(function (index, node) {
if (node.value == 0) {
var id = "select#" + node.id;
$(id).addClass('errorType');
}
});
}
This will search select tag with name as attribute, if found, it will get the value of the name and check of its empty or not. If found empty it will add new class that turns that select tag into a red border.
Hope this will help