display current alert when change select value - javascript

I have a select (dropdown) and an input. When I enter a number at input, select value change with that number:
<input id="input" type="text" name="selectChanger">
<select id="select">
<option value="" selected></option>
<option value="0">floor 0</option>
<option value="1">floor 1</option>
<option value="2">floor 2</option>
</select>
I want when change select value, display an alert:
document.getElementById('input').addEventListener('input', function (event){
let de = new Event('change');
document.getElementById('select').dispatchEvent(de);
document.getElementById('select').value = document.getElementById('input').value;
})
document.getElementById('select').addEventListener('change', function (event){
alert(document.getElementById('select').text + ' was selected.')
})
Now when input number 0 , display was selected, and then input number 1 display floor 0 was selected but must display floor 1 was selected.
How can I fix this problem?

I think this will help you.
//First Way
document.addEventListener('DOMContentLoaded', event => {
const target_input = document.querySelector('#input'),
target_select = document.querySelector('#select');
if (target_input != null) {
target_input.addEventListener('input', event => {
const { target } = event;
for (const node of [...target_select.childNodes]) {
if (node.nodeType == 1) {
if (node.value == target.value) {
node.selected = true;
alert(`${node.textContent} is selected`)
break;
}
}
}
})
}
});
// Second way
const {input, select} = {input: document.getElementById('input'), select: document.getElementById('select')};
input.addEventListener('input', function (event){
const selector = select.querySelector(`option[value="${input.value}"]`);
if (selector == null) {
alert('Does not exist!');
return '';
}
selector.selected = true;
select.dispatchEvent(new Event('change'));
})
select.addEventListener('change', function (event){
alert(select.value + ' was selected.')
})
<input id="input" type="text" name="selectChanger">
<select id="select">
<option value="" selected></option>
<option value="0">floor 0</option>
<option value="1">floor 1</option>
<option value="2">floor 2</option>
</select>

Now when input number 0 , display was selected, and then input number 1 display floor 0 was selected but must display floor 1 was selected.
Slightly confused, but-
Steps for detecting dropdown value change:
Get the element
Add an event listener for change
Detect the selected value
Code:
elem = document.getElementById("select")
elem.addEventListener("change", function(e) {
alert(elem.options[elem.selectedIndex].innerText + " was selected")
})

Related

HTML5 datalist: Show all options in dropdown when arrow clicked

There are a few solutions out there to display all the options in a datalist dropdown when a value is set and the down arrow is clicked. But none of them dealt with the case when a placeholder was already set initially.
I have therefore adapted a solution so that the initial placeholder is restored.
How it works:
Down arrow clicked: Set a placeholder with the input value and clear the input value
On mouseenter event: Save the original/initial placeholder value
On mouseleave event: Restore the input value and restore the initial
placeholder, if the input value is blank.
My question is, if you see any flaws or unhandled cases in this code.
https://jsfiddle.net/Smolo/1y9mne2o/
function dlRestoreValue(i) {
let t = $('#' + i);
if (t.val() === '') {
if (t.attr('org-placeholder') !== t.attr('placeholder')) {
t.val(t.attr('placeholder'));
}
t.attr('placeholder', '');
if (t.val() === '') {
t.attr('placeholder', t.attr('org-placeholder'));
}
}
}
function dlShowAllOnArrowClick(i) {
$('#' + i)
.on('click', function(e) {
let t = $(this);
if ((t.width() - (e.clientX - t.offset().left)) < 14) {
if (t.val() !== "") {
t.attr('placeholder', t.val());
t.val('');
}
} else {
dlRestoreValue(i)
}
})
.on('mouseleave', function() {
dlRestoreValue(this.id);
})
.on('mouseenter', function() {
if (!$(this).is("[org-placeholder]")) $(this).attr('org-placeholder', $(this).attr('placeholder'));
})
}
dlShowAllOnArrowClick('favcolors');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Favorite color:
<input type="text" id="favcolors" list="colors" placeholder="Pick a color">
<datalist id="colors">
<option value="Blue">
<option value="Brown">
<option value="Cyan">
<option value="Green">
<option value="Orange">
<option value="Pink">
<option value="Purple">
<option value="Red">
<option value="Yellow">
</datalist>

change dropdown list to its original state

i have two dropdownlists in my view. by changing the value on the first one i can change the value on the second one. in the first run it works fine using scrip below.
but when i change the first dropdownlist to something else it will not work. i believe if i can change the second dropdownlist value and text and .... rest to its original state it will be ok.
here is my code :
<select id="ddlDepartment">
<option selected disabled>اselect department</option>
#foreach (var item in Model)
{
<option value="#item.DepartmentTitle">#item.DepartmentTitle</option>
}
</select>
</td>
</tr>
<tr>
<td>grade</td>
<td>
<select id="ddlgrade">
<option selected disabled="disabled">Select Grade</option>
<option id="id_bachelor" value="bachelor">bachelor</option>
<option id="id_Masters" value="Master">Masters</option>
<option id="Doctorate" value="Doctorate">Doctorate</option>
</select>
and here is my script :
$('#ddlDepartment')
.change(function() {
debugger;
var ddlDepartment = $('#ddlDepartment').val();
var grade = $('#ddlgrade').val();
getGrade();
function getGrade() {
$('#ddlgrade')
.change(function() {
grade = $('#ddlgrade').val();
$.ajax('/AdminPages/showStudents/' + ddlDepartment + '/' + grade)
.done(function(data) {
$('#lstStudents').html(data);
});
});
}
});
i get the erro here:
if ( !( eventHandle = elemData.handle ) ) {
eventHandle = elemData.handle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ?
jQuery.event.dispatch.apply( elem, arguments ) : undefined;
};
}
You have to move getGrade() function outside. getGrade() function bind a change event handler for second select EVERYTIME you changed the first select.
Final Solution
$('#ddlgrade').change(function() {
var ddlDepartment = $('#ddlDepartment').val();
var grade = $(this).val();
if(ddlDepartment){
$.ajax('/AdminPages/showStudents/' + ddlDepartment + '/' + grade)
.done(function(data) {
$('#lstStudents').html(data);
});
}
else{
alert("Please select department first!");
}
});
Please take a look how works your code:
$('#ddlDepartment')
.change(function() {
var ddlDepartment = $('#ddlDepartment').val();
var grade = $('#ddlgrade').val();
alert(ddlDepartment);
getGrade();
function getGrade() {
$('#ddlgrade')
.change(function() {
grade = $('#ddlgrade').val();
alert(grade);
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="ddlDepartment">
<option selected disabled>اselect department</option>
<option val="1">acb</option>
<option val="1">acfdb</option>
</select>
<select id="ddlgrade">
<option selected disabled="disabled">Select Grade</option>
<option id="id_bachelor" value="bachelor">bachelor</option>
<option id="id_Masters" value="Master">Masters</option>
<option id="Doctorate" value="Doctorate">Doctorate</option>
</select>

Set attribute to readonly when dropdown value is changed

I have this dropdown that has 4 options.
What I want to achieve is to change the attribute of input text number to readonly when a user selects option3 or option4 from the dropdown.
<select id="s_id">
<option value="option1">option1</option>
<option value="option2">option2</option>
<option value="option3">option3</option>
<option value="option4">option4</option>
</select>
number: <input type="text" name="number">
This is the script that I have for now, what it does is just alert the selected value.
$(document).ready(function () {
$("#s_id").change(function () {
var x = $(this).val();
alert($(this).val());
if (x == opel) {
alert("iff");
$(this).attr("readOnly", "true");
}
});
});
JS Fiddle link
Any idea/s would be really appreciated!
Use prop to make readonly and remove it back
DEMO
$(document).ready(function () {
$("#s_id").change(function () {
if (this.value === 'option3' || this.value === 'option4')
$("input[name='number']").prop('readonly', true);
else
$("input[name='number']").prop('readonly', false);//enable it back again
});
});
You can simply check your .value in your change handler and use jQuery .prop method:
$("#s_id").change(function () {
var isReadonly = (this.value === 'option3' || this.value === 'option4');
$("input[name='number']").prop('readonly', isReadonly);
});
or using an array for making it easier to modify it in future:
$("#s_id").change(function () {
var isReadonly = ['option3', 'option4'].indexOf(this.value) > -1;
$("input[name='number']").prop('readonly', isReadonly);
});
Here is the working JSFiddle demo.
Use prop() to set the readonly property of the text-box.
Create an array of all the values of the drop-down which, when selected, the number text-box should be disabled.
Check if the selected value is in the array in the change event handler
If the selected option value is present in the array, disable the number text-box, else enable it
Demo
$(document).ready(function() {
// Values when selected, the number box should be disabled
var values = ['option2', 'option3'];
// On selection change of the dropdown
$("#s_id").change(function() {
// values.indexOf($(this).val()) > -1
// Checks if the value selected is from the array
// Comparison returns true when the value is in array, false otherwise
$('input[name="number"]').prop('readonly', values.indexOf($(this).val()) > -1);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="s_id">
<option value="option1">option1</option>
<option value="option2">option2</option>
<option value="option3">option3</option>
<option value="option4">option4</option>
</select>
number:
<input type="text" name="number">
Try following code :-
$(this).attr("disabled", true);
I think drop down is always read only . what you can do is make it disabled
if you work with a form , the disabled fields does not submit , so use a hidden field to store disabled dropdown value
Please use this, You can also use it dynamically
Given below the HTML code
<select id="s_id">
<option value="option1">option1</option>
<option value="option2">option2</option>
<option value="option3">option3</option>
<option value="option4">option4</option>
</select>
number: <input type="text" id="number" name="number">
Given below the JQuery code
$(document).ready(function () {
$("#s_id").change(function () {
var option_Array = ["option3","option4"]
var x = $(this).val();
$("#number").prop('readonly', false);
for(var i=0; i<option_Array.length; i++){
if (x == option_Array[i]){
$("#number").prop('readonly', true);
}
}
});
});

how to show 2 select options value in another element?

I am have been searched too much on net but nothing found.
I have 2 select options tag.
I want to show option value in the input tag by multiplying option tag value whatever it is.
and selecting 2nd option tag I want to assign 2nd option tag value to 1st option tag value.
and I also want to multiply that values as the 1st options value have before.
how to do this?
here is my code.
My 1st options tag.
<select name="" id="test">
<option selected="" value="0" disabled='disabled'>Select Duration</option>
<option value="1">1/month</option>
<option value="2">2/month</option>
<option value="3">3/month</option>
<option value="6">6/month</option>
<option value="12">12/month</option>
</select>
<input type="text" data-val="9" id="price_value" style="border:1px solid #0a0; padding:1px 10px; color: #f90;" value="0" size="5"/><br>
Here is 2nd option tag.
<select id="plan">
<option value='Basic'>Basic</option>
<option value='Standard'>Standard</option>
<option value='Professional'>Professional</option>
<option value='Enterprice'>Enterprise</option>
</select>
here is JS.
$('#test').on('change',function(e){
var input = $(this).next('input[type="text"]');
var value = $(this).find('option:selected').val();
input.val( input.data('val') * parseInt(value) );
});
$('#plan').on('change',function(e) {
var plan = $(this).find('option:selected').val();
var price_value = $('#price_value');
if (plan == "Basic") {
price_value.removeAttr('data-val');
price_value.attr('data-val','9');
}
else if (plan == "Standard"){
price_value.removeAttr('data-val');
price_value.attr('data-val','19');
}
else if (plan == "Professional"){
price_value.removeAttr('data-val');
price_value.attr('data-val','29');
}
else if (plan == "Enterprice") {
price_value.removeAttr('data-val');
price_value.attr('data-val','59');
}
});
Here is Demo
Changes
Use $(this).val() instead of $(this).find('option:selected').val() to fetch select value. or even better use this.value
use .data() to set value like price_value.data('val', 9); instead of price_value.attr('data-val','9');
No need to use price_value.removeAttr('data-val');
Code
$('#test').on('change',function(e){
var input = $(this).next('input[type="text"]');
var value = $(this).val(); //Or this.value
input.val( input.data('val') * parseInt(value, 10) );
});
$('#plan').on('change',function(e) {
var plan = $(this).val();
var price_value = $('#price_value');
if (plan == "Basic") {
price_value.data('val',9);
}
else if (plan == "Standard"){
price_value.data('val',19);
}
else if (plan == "Professional"){
price_value.data('val',29);2
}
else if (plan == "Enterprice") {
price_value.data('val',59);
}
$('#test').trigger('change'); //Trigger $('#test') change event
});
DEMO
This solution would work if you are okay with changing your HTML a bit:
<select id="plan">
<option value='9'>Basic</option>
<option value='19'>Standard</option>
<option value='29'>Professional</option>
<option value='59'>Enterprise</option>
</select>
Then simply use:
$('#test, #plan').on('change',function() {
var valueOne = $('#test').val();
var valueTwo = $('#plan').val();
$('#price_value').val(parseInt(valueOne) * parseInt(valueTwo));
});
That's all!

How to run a piece of javascript when you select a dropdown option?

I have a select with loads of options. (Code below shortened for sake of example).
I want it to set the value of the input textfield "hoh" to "10" when you click/select all dropdown options, except one, that should set it to 50.
I imagined something like this would work, but its not. What am I doing wrong here?
<select>
<option onselect="document.getElementById('hoh').value = '50'">Hey</option>
<option onselect="document.getElementById('hoh').value = '10'">Ho</option>
<option onselect="document.getElementById('hoh').value = '10'">Lo</option>
....
</select>
<input type="text" id="hoh" value="10">
Something like this should work:
<script>
function myFunc(val) {
if (val == '50') {
document.getElementById('hoh').value = val;
} else {
document.getElementById('hoh').value = '10';
}
}
</script>
<select onchange="myFunc(this.value)">
<option value="1">one</option>
<option value="2">two</option>
<option value="50">fifty</option>
</select>
http://jsfiddle.net/isherwood/LH57d/3
The onselect event refers to selecting (or highlighting) text. To trigger an action when a dropbox selection changes, use the onchange event trigger for the <select> element.
E.g. Since you didn't already set the value attribute of your option tags.
<select id="myselect" onchange="myFunction()">
<option value="50">Hey</option>
<option value="10">Ho</option>
<option value="10">Lo</option>
....
</select>
and somewhere inside of a <script> tag (presumably in your HTML header) you define your javascript function.
<script type="text/javascript>
function myFunction() {
var dropbox = document.getElementById('myselect');
document.getElementById('hoh').value = dropbox[dropbox.selectedIndex].value;
}
</script>
I'm not sure it's wise to repeat the same value among different options in a droplist, but you could expand on this to implement the result other ways, such as if the sole option which will have value 50 is in a certain position, you could compare the selectedIndex to that position.
you could add an onchange event trigger to the select, and use the value of an option to show in the textbox
see http://jsfiddle.net/Icepickle/5g5pg/ here
<select onchange="setValue(this, 'hoh')">
<option>-- select --</option>
<option value="10">Test</option>
<option value="50">Test 2</option>
</select>
<input type="text" id="hoh" />
with function setValue as
function setValue(source, target) {
var tg = document.getElementById(target);
if (!tg) {
alert('No target element found');
return;
}
if (source.selectedIndex <= 0) {
tg.value = '';
return;
}
var opt = source.options[source.selectedIndex];
tg.value = opt.value;
}
Try this code
var inp = document.getElementById('hoh');
sel.onchange = function(){
var v = this.value;
if( v !== '50'){
v = '10';
}
inp.value = v;
};

Categories