Prevent the duplicate function onchange event jQuery - javascript

I have this snippet below
$(document).ready(function(){
$("#selectTest").change(function(e){
if($(this).val() == "01"){
$(".show").hide();
}else{
$(".show").show();
};
})
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div class="show">
Sample Text
</div>
<select name="test" id="selectTest">
<option value="00"></option>
<option value="01">Click this to hide text</option>
<option value="02">Click this to show text</option>
</select>
</body>
</html>
Above snippets looks fine, but i am getting trouble when the option where selected from the first when the page loaded. I have to click the different button to make the hide function works. I solved that problem by adding the if ... else in my code so that when the page loaded the hide function will run properly.
$(document).ready(function(){
$("#selectTest").change(function(e){
if($(this).val() == "01"){
$(".show").hide();
}else{
$(".show").show();
};
})
if($("#selectTest").val() == "01"){
$(".show").hide();
}else{
$(".show").show();
};
})
Above code looks not appropriate because i have to repeat the function that i have made, is there any better way to resolved this problem ?

Instead of writing code twice, you can trigger the event (change) using jQuery's .trigger():
$("#selectTest").trigger('change');
Working Code Example:
$(document).ready(function(){
$("#selectTest").change(function(e){
if($(this).val() == "01"){
$(".show").hide();
}else{
$(".show").show();
};
});
$("#selectTest").trigger('change');
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="show">
Sample Text
</div>
<select name="test" id="selectTest">
<option value="00"></option>
<option value="01">Click this to hide text</option>
<option value="02">Click this to show text</option>
</select>

Related

Option Value of Javascript file returns undefined

Hi i have following problem. I want that the user picks an option of a select panel. Then after he clicks the button he is taken to another file where the value of his choice is put in a variable and then displayed. It is important that its opened in a new file. But with my code the variable returns undefined. Here is my Code:
function myFunction() {
a=$("#mySelect").val();
switch(a){
case "Orange":
var b="Orange";
return b;
case "Apple":
var b="Apple";
return b;
case "Pineapple":
var b="Pineapple";
return b;
case "Banana":
var b="Banana";
return "Banana";
}
}
var test=myFunction();
$("button").on("click",blub);
function blub(){
window.open(
"/Users/Adrian/Desktop/jj.html",
'_blank'
);
}
<!DOCTYPE html>
<html>
<body>
<select id="mySelect">
<option value="Apple">
Apple
</option>
<option value="Orange">
Orange
</option>
<option value="Pineapple">
Pineapple
</option>
<option value="Banana">
Banana
</option>
</select>
<p class="bla">
Click the button to select the option element with index "2".
</p>
<p>
<b>
Note:
</b>
The index starts at 0.
</p>
<button>
Try it
</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
<script charset="utf-8" src="j.js">
</script>
<script charset="utf-8" src="jj.js">
</script>
</body>
</html>
$(".bla").html(test);
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<p class="bla"></p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="j.js" charset="utf-8"></script>
<script src="jj.js" charset="utf-8"></script>
</body>
</html>
You should only get the value of the select once the button is clicked, not on page load. Then, you can set it in the sessionStorage so that the other page can access it.
JavaScript for first page:
$("button").on("click", blub);
function blub() {
sessionStorage.setItem("value", $('#mySelect').val());
window.open(
"/Users/Adrian/Desktop/jj.html",
'_blank'
);
}
JavaScript for the second page:
$(".bla").text(sessionStorage.getItem('value'));

Multiple fastselect refresh will allow adding on first click but does not work after selecting from list

I am using the multiple fastselect. I can't seem to get the refresh to work. What I mean by that is I need to be able add a new option to the list after selecting items from the dropdown list.
If I click the add button1 the first time it works. When I select an item from the list and then click the add button1 again to add to the list the add no longer works.
Any suggestions on what I might be doing wrong?
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="css/fastselect.min.css">
<script src="js/jquery_2.1.1.js"></script>
<script src="js/fastselect.standalone.min.js"></script>
<style type="text/css">
.fstResultItem .fstSelected {
background-color: green;
}
</style>
</head>
<body>
<div class="container">
<h2>Multiple Select</h2>
<div>
<select id="example2" class="example2" multiple="multiple">
<option value="test1">C1</option>
<option value="test2">C2</option>
<option value="test3">C3</option>
<option value="test4">C4</option>
<option value="test5">C5</option>
<option value="test6">C6</option>
<option value="test7">C7</option>
<option value="test8">C8</option>
<option value="test9">C9</option>
</select>
<div>
<button id="button1">Add Item Set 1</button>
<button id="button2">Add Item Set 2</button>
<button id="rebuild">Rebuild</button>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$('#example2').fastselect({});
$('#button1').click(function () {
//alert('button1 click');
$('#example2').append('<option value="add1">Addition 1</option>');
setTimeout(function () {
$('#example2').fastselect();
}, 500);
});
$('#button2').click(function () {
//alert('button2 click')
$('#example2').append('<option value="add1">Addition 1</option>');
});
$('#rebuild').click(function () {
alert('rebuilding');
$('#example2').fastselect();
});
});
</script>
</body>
</html>
The initial options of the select are copied to a hidden div when calling .fastselect() (you can check that with the developer tools). Later additions to the options are not reflected in the copy.
A possible solution would be to remove fastselect from the select and then add it again:
$('#example2').append('<option value="add1">Addition 1</option>').data('fastselect').destroy();
$('#example2').fastselect();
Line one adds the new select option and then destroys the fastselect instance and line two initializes it again.

Jquery declaration issue?

Recently, my jQuery code using events stopped working. I don't understand why. Do I have a declaration issue?
This is my declaration in the header:
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content=XXXXXXX">
<link href="/Content/bootstrap.css" rel="stylesheet"/>
<link href="/Content/Bootstrap-table.css" rel="stylesheet"/>
<link href="/Content/site.css" rel="stylesheet"/>
<link href="/Content/justified-nav.css" rel="stylesheet"/>
<link href="/Content/simple-sidebar.css" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="/Content/msdropdown/dd.css" />
<link href="/Content/font-awesome-4.6.3/css/font-awesome.min.css" rel="stylesheet">
<link href="/Content/font-awesome-4.7.0/css/font-awesome.min.css" rel="stylesheet">
<script src="/Scripts/jquery-3.1.1.js"></script>
<script src="/Scripts/jquery-3.1.1.min.js"></script>
<script src="/Scripts/bootstrap.js"></script>
<script src="/Scripts/Bootstrap-table.js"></script>
<script src="/Scripts/ManageSeason.js"></script>
<script src="/Scripts/site.js"></script>
<script src="/Scripts/modernizr-2.6.2.js"></script>
<script src="/Scripts/sidebar_menu.js"></script>
<script src="/Scripts/js/msdropdown/jquery.dd.min.js" type="text/javascript"></script>
<title>XXXXXX</title>
</head>
And my jQuery code:
$('select[class*="selectEqRaceId"]').change(function () {
// do some stuff
});
and
$('#menu li a').click(
function () {
// Do some stuff
}
);
It doesn't work. I click on the button or change the value of the select option.
The browser compilator doesn't go inside this event function.
Import jQuery just once, use $(document).ready() function and take a look at the example below.
$(document).ready(function() {
$('select[class*="selectEqRaceId"]').change(function() {
console.log("Changed via slect menu");
});
$('button').click(function() {
console.log("Clicked via button");
});
});
<script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"></script>
<select class="selectEqRaceId">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<br>
<button>
Click me
</button>
EDIT:
You have to place the tags before the events get set or use the $(document).ready() function which will execute the code thats in it after the page finishes loading. It is always a good idea to use the $(document).ready() function.
I have added an example:
1) Script after the tags without $(document).ready()
2) Script before the tags without $(document).ready() (this wont work)
3) Script before the tags WITH $(document).ready() function
<script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"></script>
<h3>Script after the tags without $(document).ready()</h3>
<select class="afterTheTagsWithReady">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<br>
<button class="afterTheTagsWithReady">Click me</button>
<script>
// Without the $(document).ready() function and after the tags
$('select.afterTheTagsWithReady').change(function() {
console.log("Changed via slect menu afterTheTagsWithReady");
});
$('button.afterTheTagsWithReady').click(function() {
console.log("Clicked via button afterTheTagsWithReady");
});
</script>
<h3>Script before the tags without $(document).ready() (this wont work)</h3>
<script>
// Without the $(document).ready() function and after the tags
$('select.beforeTheTags').change(function() {
console.log("Changed via slect menu beforeTheTags");
});
$('button.beforeTheTags').click(function() {
console.log("Clicked via button beforeTheTags");
});
</script>
<select class="beforeTheTags">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<br>
<button class="beforeTheTags">Click me</button>
<h3>Script before the tags WITH $(document).ready() function</h3>
<script>
// With the $(document).ready() function and before the tags
$(document).ready(function() {
$('select.beforeTheTagsWithReady').change(function() {
console.log("Changed via slect menu beforeTheTagsWithReady");
});
$('button.beforeTheTagsWithReady').click(function() {
console.log("Clicked via button beforeTheTagsWithReady");
});
});
</script>
<select class="beforeTheTagsWithReady">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<br>
<button class="beforeTheTagsWithReady">Click me</button>
In short, yes. Since you are loading all of your scripts in the head element, the script is executing correctly. It is attaching the event handler to all elements it finds at the time of script loading (which is none since the DOM tree of the body isn't constructed yet).
You have to wait for the elements to be loaded into the DOM tree before being able to manipulate them so you can fix this by loading your JS code just before the end of the closing body tag (i.e. inside the body after the other elements), or you can use the JQuery helper $().ready(function) so that it waits for the DOM tree to fully load before attempting to attach event handlers to elements.
$().ready(function(){
$('#menu li a').click(function () {
//Do some stuff
});
});

How to display INPUT TYPE on Selection?

I know its a simple but i tried many solutions but i failed. I have a form on which I use <select> tag in <option> i use two values coo and uh i want that when user select uh then it display an extra input type field.
Here is my code.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js"></script>‌​
<script>
$('#s_designation').on('change',function(){
if ($(this).val() === "uh") {
$("#uh").show()
}
else {
$("#uh").hide()
}
});
</script>
<title>Untitled Document</title>
</head>
<body>
<label for="db">Choose type</label>
<select name="s_designation" id="s_designation">
<option value="coo">Chief Operating Officer</option>
<option value="uh">Unit Head</option>
</select>
<div id="uh" style="display:none;">
<label for="specify">Specify</label>
<input type="text" name="specify" placeholder="Specify Designation"/>
</div>
</body>
</html>
I just tested your code and it works fine:
Link:https://jsfiddle.net/g95pyqw6/
Edit: But that could be because of JSfiddle.
Try to uncomment the first line of Javascript, that should help! :-)
I hope I could help you out. If you need more help, feel free to write a comment :-)
You jQuery code is executing before the document loads, which means the select element is not visible to jQuery, and jQuery won't throws error if it didn't find any given element.
use the $(document).ready like the following, it will load your code after document loads:
<head>
-------
-------
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
<script>
$(document).ready(function() {
$('#s_designation').on('change',function(){
if( $(this).val()==="uh") {
$("#uh").show()
}
else {
$("#uh").hide()
}
});
});
</script>
-------
</head>
if you want to execute jQuery code after page loading
you simply place your jQuery code before </body> tag like the following:
<body>
-------
-------
<script>
$('#s_designation').on('change',function(){
if( $(this).val()==="uh") {
$("#uh").show()
}
else {
$("#uh").hide()
}
});
</script>
</body>
here your Working code (checked on my local machine) answer is here for your problem Jquery not working from Google CND
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js"></script>‌​
<script>
$(function() {
$('#s_designation').on('change',function(){
if( $(this).val()=="uh"){
$("#uh").show()
}
else{
$("#uh").hide()
}
});});
</script>
<title>Untitled Document</title>
</head>
<body>
<label for="db">Choose type</label>
<select name="s_designation" id="s_designation">
<option value="coo">Chief Operating Officer</option>
<option value="uh">Unit Head</option>
</select>
<div id="uh" style="display:none;">
<label for="specify">Specify</label>
<input type="text" name="specify" placeholder="Specify Designation"/>
</div>
</body>
</html>
In your code you have commented the $(function() line :
You are also missing the required jquery library files
Please add this to your html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
Fiddle: http://jsfiddle.net/0mqze5ny/
$(function () {
$('#s_designation').on('change', function () {
if ($(this).val() === "uh") {
$("#uh").show()
} else {
$("#uh").hide()
}
});
})

jQuery hide(); and show(); issue in Internet Explorer

I've been wrestling with Internet Explorer for a few hours now and can't seem to figure out my problem. I'm trying to achieve a simple "group option switcher" with jQuery show() and hide().
It's probably best if you look at my demo to see what I mean: http://softwaredb.org/test/jquery-multi-select.html
My code works in every browser except IE. My code is this...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Demo - Jquery Multi Select box</title>
<style type="text/css">
select{width:200px;height:200px;}
select#boysnames, select#girlsnames{display:none;}
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<div id="wrapper" style="padding:50px 0 0 50px;">
<form>
<select multiple="multiple" id="theoptions">
<option value="boysnames">Boys Names</option>
<option value="girlsnames">Girls Names</option>
</select>
<select multiple="multiple" id="placeholder">
</select>
<select multiple="multiple" id="boysnames">
<option>John</option>
<option>David</option>
<option>Tom</option>
</select>
<select multiple="multiple" id="girlsnames">
<option>Jenny</option>
<option>Amanda</option>
<option>Sara</option>
</select>
</form>
</div> <!-- end #wrapper -->
<script type="text/javascript">
$('option[value="boysnames"]').click(function() {
$('select#placeholder, select#girlsnames').hide();
$('select#boysnames').show();
});
$('option[value="girlsnames"]').click(function() {
$('select#placeholder, select#boysnames').hide();
$('select#girlsnames').show();
});
</script>
</body>
</html>
My logic is... on click, hide all other select tags and show the one I'd like to see. It seems to work fine, until I try in IE. Any ideas what I'm doing wrong? I'm very new to jquery (and javascript/programming in general) so forgive me if this is a dumb question.
Instead of tracking clicks on the option level, track a change on the select level.
$('select#theoptions').change(function() {
$('#placeholder, #girlsnames').hide();
if($(this).val() == 'boysnames') {
$('#boysnames').show();
} else {
$('#girlsnames').show();
}
});
There are many ways to make your approach a little more intuitive, but this should get you going on the path that you're on
<script type="text/javascript">
$('#theoptions').click(function() {
if($(this).attr('value') == "boysnames")
{
$('select#placeholder, select#girlsnames').hide();
$('select#boysnames').show();
}
if($(this).attr('value') == "girlsnames")
{
$('select#placeholder, select#boysnames').hide();
$('select#girlsnames').show();
}
});
</script>
use this ..

Categories