How to check if select element changed after close? [duplicate] - javascript

I would like to make a jQuery check if a select field was changed. If it changes, set an alert message (has changed), if returned to default, set another alert message (default value).
$('select').on('change',function () {
var isDirty = false;
$('select').each(function () {
var $e = $(this);
if (!$e[0].options[$e[0].selectedIndex].defaultSelected) {
isDirty = true;
}
});
if(isDirty == true) {
alert("has changed");
} else {
alert("default value");
}
});
Please advise if this is the proper way.

You don't need inner each loop. Plus $(this)[0] can be optimised to just this:
$('select').on('change', function () {
var isDirty = !this.options[this.selectedIndex].defaultSelected;
if (isDirty) {
alert("has changed");
} else {
alert("default value");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="" id="">
<option value="1">Label 1</option>
<option value="2" selected>Label 2</option>
<option value="3">Label 3</option>
<option value="4">Label 4</option>
</select>

I would do something like:
HTML:
<select data-default="one" id="the-select">
<option>one</option>
<option>two</option>
</select>
Javascript:
$('#the-select').change(function() {
var changed = $(this).val() != $(this).data('default');
alert(changed ? 'changed' : 'not changed');
});

Related

Disable dropdown using javascript

I'm having Two Dropdown name as Product and Product line and both are dependent on each other such that after selecting any product only Product Line dropdown will get enable. the sample structure is as below.
<select name="abb_sf_partners-product" data-abb-sf-productelement="" class="abb-select" disabled="">
<option value="">All products</option>
<option value="AA">Product1</option>
<option value="BB">Product2</option>
<option value="BB">Product3</option>
</select>
<select name="abb_sf_partners-product-line" data-abb-sf-productelement="" class="abb-select" disabled="">
<option value="">All products Line</option>
<option value="CC">ProductLine1</option>
<option value="DD">ProductLine2</option>
<option value="EE">ProductLine3</option>
</select>
<SCRIPT>
document.addEventListener("DOMContentLoaded", function() {
checkDropdownvalue();
});
function disableProductline() {
document.querySelector('select[name="abb_sf_partners-product-line"]').disabled = true;
}
function checkDropdownvalue() {
document.querySelector('select[name="abb_sf_partners-product"]').onchange = (e) => {
var selectedProductline = e.target.value;
alert(e.target.value)
if (selectedProductline == "AA") {
disableProductline();
}
}
}
</SCRIPT>
on select of AA in product dropdown ill needed to disable the ProductLine Dropdown.
But i'm guessing due to some razor view changes Product Line dropdown is keep getting enable as the data in Product Line is dynamically inserted
So is there any way such that my code will execute at the end to disable it.
You can try this approach.
document.addEventListener("DOMContentLoaded", function() {
checkDropdownvalue();
});
function checkDropdownvalue() {
const productSelect = document.querySelector('[name="abb_sf_partners-product"]');
const productLine = document.querySelector('[name="abb_sf_partners-product-line"]')
productSelect.addEventListener('change', function(e) {
if (e.target.value === 'AA') {
productLine.disabled = true;
} else {
productLine.disabled = false;
}
});
}
<select name="abb_sf_partners-product" data-abb-sf-productelement="" class="abb-select">
<option value="">All products</option>
<option value="AA">Product1</option>
<option value="BB">Product2</option>
<option value="BB">Product3</option>
</select>
<select name="abb_sf_partners-product-line" data-abb-sf-productelement="" class="abb-select" disabled="true">
<option value="">All products Line</option>
<option value="CC">ProductLine1</option>
<option value="DD">ProductLine2</option>
<option value="EE">ProductLine3</option>
</select>
As mentioned in My case Product Line dropdown was getting enable due to some razor view code. In order resolve this instead of comparing value of a product on change of product dropdown I have done the comparison on Product Line dropdown like if i hover my mouse over Product line dropdown it then trigger an event to check the selected product and compare it with the one i want (i have not used onClick as momentarily(for few milisec) it open the dropdown and then disable it ) i have used below JS script to achieve this.
document.addEventListener("DOMContentLoaded", function()
{
document.querySelector('select[name="abb_sf_partners-product-line"]').onmouseover = function fun() {
var selectedproduct = getSelectedProduct();
/* alert(selectedproduct.value); */
if(selectedproduct.value == "AA")
{
document.querySelector('select[name="abb_sf_partners-product-line"]').disabled = true;
}
else
{
document.querySelector('select[name="abb_sf_partners-product-line"]').disabled = false;
}
}
});
function getSelectedProduct(){
var sel = document.querySelector('select[name="abb_sf_partners-product"]');
var selectedP = getSelectedOption(sel);
function getSelectedOption(sel) {
var opt;
for ( var i = 0, len = sel.options.length; i < len; i++ ) {
opt = sel.options[i];
if ( opt.selected === true ) {
break;
}
}
return opt;
}
return selectedP
}
I hope it will help someone lol.

drop-down validation and Combine If statement on JavaScript with extra condition for validation?

I have a function to check if the value meet the requirement, it is working fine so I have another drop-down(select) to validate with same condition but the drop-down values different I am only checking the blank selection.
Goal:
any way to improve the JS or combine them correctly.
Many thanks in advance
// for 1st drop down
function checkPrimeSelectChangeValue() {
var selObj = document.getElementById("dropdown1");
var selValue = selObj.options[selObj.selectedIndex].value;
if (selValue == "") { // if blank is selected add css for validation
$("#dropdown1").attr('disabled', 'disabled');
$("#dropdown1").addClass("text-error");
} else {
$("#btnUpdateForm").removeAttr('disabled'); // disabled button
removeError("#dropdown1"); // remover error
}
return;
}
// 2nd dropdown like below
function checkSecondSelectChangeValue() {
var selObj2 = document.getElementById("dropdown2");
var selValue2 = selObj.options[selObj.selectedIndex].value;
if (selValue2 == "") { // if blank is selected add css for validation
$("#dropdown2").attr('disabled', 'disabled');
$("#dropdown2").addClass("text-error");
} else {
$("#btnUpdateForm").removeAttr('disabled'); // disabled button
removeError("#dropdown2"); // remover error
}
return;
}
// Can I do this or Any ipmorvent can be done to this
function checkCombinedSelectChangeValue() {
var selObj = document.getElementById("dropdown1");
var selObj2 = document.getElementById("dropdown2");
var selValue = selObj.options[selObj.selectedIndex].value;
var selValue2 = selObj.options[selObj.selectedIndex].value;
if (selValue == "") { // if blank is selected add css for validation
$("#dropdown1").attr('disabled', 'disabled');
$("#dropdown1").addClass("text-error");
} else {
$("#btnUpdateForm").removeAttr('disabled'); // disabled button
removeError("#dropdown1"); // remover error
}
return;
if (selValue2 == "") { // if blank is selected add css for validation
$("#dropdown2").attr('disabled', 'disabled');
$("#dropdown2").addClass("text-error");
} else {
$("#btnUpdateForm").removeAttr('disabled'); // disabled button
removeError("#dropdown2"); // remover error
}
return;
}
<p>1st dropdown1 </p>
<select name="test" id="select">
<option value="">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="nil">nil</option>
</select>
<br>
<p>2nd dropdown1 </p>
<select name="test" id="select2">
<option value="">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="nil">nil</option>
</select>
I optimized your function a little, assuming it's supposed to run when your select changes. I also assume that you want to add the disabled property to your #btnUpdateForm since that isnt really clear with the code you provided.
First add the disabled property to your Update button like this:
<button id="btnUpdateForm" disabled>Update</button>
HTML:
<p>1st dropdown1 </p>
<select class="dropdown" name="test" id="select">
<option value="">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="nil">nil</option>
</select>
<br>
<p>2nd dropdown1 </p>
<select class="dropdown" name="test" id="select2">
<option value="">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="nil">nil</option>
</select>
JQuery:
$('.dropdown').change(function() {
var val1 = $('#select').val();
var val2 = $('#select2').val();
if (val1 == '' || val2 == '') {
$('#btnUpdateForm').prop('disabled', true);
if (val1 == '') {
$('#dropdown1').addClass('text-error');
if (val2 !== '') {
$('#dropdown2').removeClass('text-error');
}
}
else if (val2 == '') {
$('#dropdown2').addClass('text-error');
if (val1 !== '') {
$('#dropdown1').removeClass('text-error');
}
}
}
else {
$('#btnUpdateForm').prop('disabled', false);
$('#dropdown1').removeClass('text-error');
$('#dropdown2').removeClass('text-error');
}
});
Basically now the Error will show up for each Dropdown with value="" and the button will only be enabled when both Dropdown's value isn't 0.

Replacing element with a previously saved element (select boxes)

I've got some javascript to change a select box to a text box if an option is selected then change that text box back to a select box if the user hits delete/backspace to the point where they clear the text box.
http://jsfiddle.net/5e1stz46/6/
<select id='visit'>
<option value='1'>option1</option>
<option value='2'>option2</option>
<option value='3'>option3</option>
<option value='Other'>Other</option>
</select>
$('#visit').on('change', function () {
if ((this.value) == 'Other') {
tmp = this;
$(this).replaceWith($('<input/>',{'type':'text','id':'visit'}));
}
});
$(document).keyup(function(e){
if( $('#visit').length ) {
if($('#visit').is(":focus") && $("#visit").val().length == 0){
$("#visit").replaceWith(tmp);
}
}
});
$('#visit').keyup(function(e){
if(e.keyCode == 46 || e.keyCode == 8) {
alert('box now empty');
}
});
When the text box changes back into a select box, all the events it had seem to be lost.
Should I be somehow reading the event listeners when the select box comes back or should I be saving the select box differently to start with?
The events got removed because you're removing associated Html element from the DOM. You can have both select and input and play with .hide() and .show to visualize the correct element and the events will work fine.
Another approach could be to use event delegation.
Changed Html:
<div id="wrapper">
<select id='visit'>
<option value='1'>option1</option>
<option value='2'>option2</option>
<option value='3'>option3</option>
<option value='Other'>Other</option>
</select>
</div>
Changed JavaScript:
$('#wrapper').on('change', '#visit', function () {
if ((this.value) == 'Other') {
tmp = this;
$(this).replaceWith($('<input/>',{'type':'text','id':'visit'}));
}
});
[ ... ]
Rest of the code remains the same. Here is an updated JsFiddle Demo.
Once you remove the element from DOM, all its handlers are gone as well.
One solution would be to always keep the element, but just hide it from the user's view.
$('select[name=visit]').on('change', function () {
if (this.value == 'Other') {
$(this).addClass('hide');
$('input.hide').removeClass('hide');
}
});
$(document).keyup(function (e) {
var $elem = $('input[name=visit]');
if ($elem.length) {
if ($elem.is(":focus") && $elem.val().length == 0) {
$elem.addClass('hide');
$("select[name=visit]").removeClass('hide');
}
}
});
$('input[name=visit]').keyup(function (e) {
if (e.keyCode == 46 || e.keyCode == 8) {
alert('box now empty');
}
});
.hide {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="visit">
<option value='1'>option1</option>
<option value='2'>option2</option>
<option value='3'>option3</option>
<option value='Other'>Other</option>
</select>
<input type="text" name="visit" class="hide" />
Also as there could be only one element with the unique id I always avoid using id attribute in dynamic HTML.
Second solution
Add a parent div wrapper and attached the handler to it as shown below:
$('#wrapper').on('change', '#visit', function () {
if ((this.value) == 'Other') {
tmp = this;
$(this).replaceWith($('<input/>', {
'type': 'text',
'id': 'visit'
}));
}
});
$(document).keyup(function(e){
if( $('#visit').length ) {
if($('#visit').is(":focus") && $("#visit").val().length == 0){
$("#visit").replaceWith(tmp);
}
}
});
$('#visit').keyup(function(e){
if(e.keyCode == 46 || e.keyCode == 8) {
alert('box now empty');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div id="wrapper">
<select id='visit'>
<option value='1'>option1</option>
<option value='2'>option2</option>
<option value='3'>option3</option>
<option value='Other'>Other</option>
</select>
</div>
JSFIDDLE

Dropdown menu item reversal

I am new to javascript and my code looks as below
In HTML:
<select name="dropdown" onChange="javascript: alertUser()" >
<option value="0" selected>Eat</option>
<option value="1">Work</option>
<option value="2">Sleep</option>
<option value="3" >Enjoy</option>
In javascript:
function alertUser()
{
confirm("Are you sure?");
}
Now, here is my problem.
When I select an element from dropdown, it will pop up confirmation dialogue "Are you Sure?". If I click Ok, the selection should change to selected value. If I cancel, the selected value should reset back to previously selected value in dropdown list.
Could anyone please help me to solve the problem.
Thank you
You can use this:
window.onload = function () {
var select = document.getElementsByName('dropdown')[0];
var lastselected = select.value;
select.onchange = function () {
var newselected = select.value;
if (confirm("Are you sure?")) {
lastselected = newselected
return true;
}
select.value = lastselected;
}
};
I added onload to it so it will run when page loads. I removed your inline js, more clean. So your html would be:
<select name="dropdown">
<option value="0" selected>Eat</option>
<option value="1">Work</option>
<option value="2">Sleep</option>
<option value="3">Enjoy</option>
</select>
DEMO HERE
Here's an alternative using the 'selectedIndex' method.
http://jsfiddle.net/thetenfold/UjYg2/
html
<select name="dropdown">
<option value="0" selected>Eat</option>
<option value="1">Work</option>
<option value="2">Sleep</option>
<option value="3">Enjoy</option>
</select>
JavaScript
function addEvent(elem, type, func) {
if (elem.addEventListener) {
elem.addEventListener(type, func, false);
} else if (elem.attachEvent) {
elem.attachEvent('on' + type, func);
}
}
addEvent(window, 'load', function () {
var select = document.getElementsByName('dropdown')[0],
last = select.selectedIndex;
addEvent(select, 'change', function () {
if( confirm('Are you sure?') ) {
last = select.selectedIndex;
} else {
select.selectedIndex = last;
}
});
});

how to insert textarea content inside <td> using dropdown in jquery

I am new to jquery and have a problem.... Probably you can help...
<select name="prodName[]" class="select-head" id="prodName0">
<option value="">Select Product</option>
<option value="add_prod">Add New</option>
<-- Here i have db select query --><option value=" "></option></select>
My jquery as
$(".select-head").live('change',function() {
if($(this).val() != "") {
$(this).next().val($(this).val());
}
});
$(".select-head").on('change',function () {
var selText = $(this).find('option:selected').text(); //.val() for value
$('.textarea').val(selText);
});
$(".select-head").live('change',function () {
if($(this).val() == "add_prod") {
var price=$(this).find('option:selected').attr('role');
$(this).parent().parent().find('#num').val(price);
}
}

Categories

Resources