How can I trigger on click event programmatically the second option (select TV)?
I use bootstrap-select plugin.
I want to mimic the same behavior as the user clicks on the "TV" option.
my code in this link:
https://jsfiddle.net/xzv9qkwe/
(btw, I tried to write a snippet here but it throws me an exception error when I include CDN of bootstrap-select... but it works fine in jsfiddle link. If you can tell me the reason for it, I will also edit the snippet here).
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap-select#1.13.14/dist/css/bootstrap-select.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"/>
<select class="selectpicker" data-style="btn-primary">
<option>Computer</option>
<option>TV</option>
</select>
Bootstrap-select plugin link:
https://developer.snapappointments.com/bootstrap-select/
Thanks.
Instead of listening for a click, listen for a change.
If you want to use the click event, you will need to use something other than a select element.
const output = document.querySelector("#output");
var changeCntr = 0;
document.querySelector(".selectpicker")
.addEventListener("change", e => {
if (e.target.value == "TV") {
changeCntr++;
output.innerText = `Changed to TV ${changeCntr} times`;
}
});
select {
font-size: 1.5em;
}
div {
background-color: lightblue;
min-height: 1.5em;
font-size: 1.5em;
}
<select class="selectpicker" data-style="btn-primary">
<option>Computer</option>
<option>TV</option>
</select>
<div id="output">
</div>
Related
Here is my code:
$(".drop-down-arrow-open i").click(function(){
console.log("click function for .drop-down-arrow-open is applied even when it is closed");
let thisParent = $(this).closest(".projects-container").find(".needed-while-hiding");
thisParent.hide();
$(this).closest(".drop-down-arrow-open").removeClass("drop-down-arrow-open").addClass("drop-down-arrow-closed");
$(this).removeClass("fa-chevron-down").addClass("fa-chevron-right");
});
$(".drop-down-arrow-closed i").click(function(){
console.log("This is never applied");
let thisParent = $(this).closest(".projects-container").find(".needed-while-hiding");
thisParent.show();
$(this).closest(".drop-down-arrow-closed").removeClass("drop-down-arrow-closed").addClass("drop-down-arrow-open");
$(this).removeClass("fa-chevron-right").addClass("fa-chevron-down");
});
span.drop-down-arrow-open, span.drop-down-arrow-closed{
font-size: 22px;
color: #636b6f;
float: right;
padding-right: 25px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" integrity="sha384-mzrmE5qonljUremFsqc01SB46JvROS7bZs3IO2EmfFsd15uHvIt+Y8vEf7N7fWAU" crossorigin="anonymous">
<div class="projects-container">
<h1>Project Name<span class="drop-down-arrow-open"><i class="fas fa-chevron-down"></i></span></h1>
<div class="needed-while-hiding">
<p class="description-background full-width adjust-properties">Description</p>
<div class="a-little-inside">
<ul class="list-without-bullets">
<li><span>Duration: </span><span>Some Duration</span></li>
<li><span>Roles: </span><span>Some Role related to development</span></li>
<li><span>Controller: </span><span>Pipeline</span></li>
<li><span>Official Website: </span>Random Link</li>
</ul>
</div>
</div>
</div>
In the above code, I am trying to open and close a drop down. I have two click functions, one for each open and close class. By default, the buttons have open class. At first, all drop downs are open by default, but when the fa-chevron-down is clicked, the close class is added and open is removed from the element using jQuery.
I have seen that in the web inspector, this logic works fine, but when the closed class is appended in the DOM, the click function of that class is never applied, instead the click function for open keeps on applying.
Am I missing something here. Please help me solve this issue. I am trying to make a portfolio, and I am stuck at this issue.
Note : By open class I mean, .drop-down-arrow-open and by close class I mean, .drop-down-arrow-closed.
Thanks in advance.
The issue is that $(selector) binds the click handler at the time it is called. So you're binding the closing handler on the element, and not binding the opening handler anywhere, as such elements don't exist when running the code.
To overcome this, you could remove the callback within the callback itself, while also adding the alternate callback.
$el = $(".drop-down-arrow-open i")
var closeFn = function() {
let thisParent = $el.closest(".projects-container").find(".needed-while-hiding");
thisParent.hide();
$el.closest(".drop-down-arrow-open").removeClass("drop-down-arrow-open").addClass("drop-down-arrow-closed");
$el.removeClass("fa-chevron-down").addClass("fa-chevron-right");
$el.off("click");
$el.click(openFn);
});
var openFn = function(){
let thisParent = $el.closest(".projects-container").find(".needed-while-hiding");
thisParent.show();
$el.closest(".drop-down-arrow-closed").removeClass("drop-down-arrow-closed").addClass("drop-down-arrow-open");
$el.removeClass("fa-chevron-right").addClass("fa-chevron-down");
$el.off("click");
$el.click(closeFn);
});
$el.click(closeFn);
This happens because the class "drop-down-arrow-closed" is not found on the time of DOM creation. To make sure always use
$('body').on('event', 'element', funciton)
So it will bind the event for the element which is already created or created later
$('body').on('click',".drop-down-arrow-open i",function(){
let thisParent = $(this).closest(".projects-container").find(".needed-while-hiding");
thisParent.hide();
$(this).closest(".drop-down-arrow-open").removeClass("drop-down-arrow-open").addClass("drop-down-arrow-closed");
$(this).removeClass("fa-chevron-down").addClass("fa-chevron-right");
});
$('body').on('click',".drop-down-arrow-closed i",function(){
console.log("This is never applied");
let thisParent = $(this).closest(".projects-container").find(".needed-while-hiding");
thisParent.show();
$(this).closest(".drop-down-arrow-closed").removeClass("drop-down-arrow-closed").addClass("drop-down-arrow-open");
$(this).removeClass("fa-chevron-right").addClass("fa-chevron-down");
});
span.drop-down-arrow-open, span.drop-down-arrow-closed{
font-size: 22px;
color: #636b6f;
float: right;
padding-right: 25px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" integrity="sha384-mzrmE5qonljUremFsqc01SB46JvROS7bZs3IO2EmfFsd15uHvIt+Y8vEf7N7fWAU" crossorigin="anonymous">
<div class="projects-container">
<h1>Project Name<span class="drop-down-arrow-open"><i class="fas fa-chevron-down"></i></span></h1>
<div class="needed-while-hiding">
<p class="description-background full-width adjust-properties">Description</p>
<div class="a-little-inside">
<ul class="list-without-bullets">
<li><span>Duration: </span><span>Some Duration</span></li>
<li><span>Roles: </span><span>Some Role related to development</span></li>
<li><span>Controller: </span><span>Pipeline</span></li>
<li><span>Official Website: </span>Random Link</li>
</ul>
</div>
</div>
</div>
As #vijoc said the problem is that when you bind the events to the elements.
As a possible solution you can re-bind the correct event every time it has to change the click function.
Code
$(function(){
bindOpen($(".open"));
bindClose($(".closed"));
});
function bindOpen(element){
$(element).unbind("click").bind("click",function(){
//your open stuff here
console.log("open");
bindClose(element);
})
}
function bindClose(element){
$(element).unbind("click").bind("click",function(){
//your open stuff here
console.log("close");
bindOpen(element);
})
}
Really, the click handler is bound to a known DOMElement matching the specified selector during runtime and when the selector changes you need to take care to update your selectors.
A workaround for this is to use the JQuery.on method to set a listener on a common parent DOMElement and filter through with another selector. An example for this using your use case is.
$(".parent-container").on("click", ".drop-down-arrow-open i", function() {
...
})
However, judging by your intent to reveal project details when the arrow icon is clicked and hide it when it is clicked again I find implementing it this way to be more readable by adding another class drop-down-arrow to target the arrow with.
function toggleProjectDetails() {
const $this = $(this)
$this
.closest(".projects-container")
.find(".needed-while-hiding")
.toggle();
$this
.toggleClass("drop-down-arrow-open drop-down-arrow-closed")
$this.find('i')
.toggleClass("fa-chevron-down fa-chevron-right")
}
$(".drop-down-arrow").on('click', toggleProjectDetails);
span.drop-down-arrow-open,
span.drop-down-arrow-closed {
font-size: 22px;
color: #636b6f;
float: right;
padding-right: 25px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" integrity="sha384-mzrmE5qonljUremFsqc01SB46JvROS7bZs3IO2EmfFsd15uHvIt+Y8vEf7N7fWAU" crossorigin="anonymous">
<div class="projects-container">
<h1>Project Name<span class="drop-down-arrow drop-down-arrow-open"><i class="fas fa-chevron-down"></i></span></h1>
<div class="needed-while-hiding">
<p class="description-background full-width adjust-properties">Description</p>
<div class="a-little-inside">
<ul class="list-without-bullets">
<li><span>Duration: </span><span>Some Duration</span></li>
<li><span>Roles: </span><span>Some Role related to development</span></li>
<li><span>Controller: </span><span>Pipeline</span></li>
<li><span>Official Website: </span>Random Link</li>
</ul>
</div>
</div>
</div>
On a normal select tag I'm able to trigger a change event with jQuery using $('select').val(2).change(). This does not work with Materialize select tags.
$(document).ready(function() {
$('select').formSelect();
$('button').on('click', function() {
//$('select').val(Math.floor(Math.random() * 3) + 1).change(); // Does not work
$('select').val(Math.floor(Math.random() * 3) + 1).formSelect();
});
});
.wrapper {
display: flex;
justify-content: space-around;
padding: 2rem;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/css/materialize.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/js/materialize.min.js"></script>
<div class="wrapper">
<select>
<option value="">Selecione</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
<button class="btn">Change</button>
</div>
I was able to make this work using $('select').val(2).formSelect() but I don't know if this is the correct way as this function is used to initialize the selects on Materialize and I haven't found documentation about it. Is this the "correct" way to achieve this or there are better solutions?
Thank you.
I think its the correct way, you will have to re-initialise the select element after changing its value
If you want to update the items inside the select, just rerun the initialization code from above after editing the original select. Or you can destroy the material select with this function below, and create a new select altogether Materializecss Docs
var select = $('select');
// initialize
select.formSelect();
$('button').on('click', function() {
// change
select.val(2);
// re-initialize material
select.formSelect();
});
var select = $("select#TeamListId");
// initialize
select.formSelect();
console.log(select);
$(select).on("change", function(e) {
teamNameId = $(this).val();
console.log("\n\nteamNameId", teamNameId);
myTable.search(teamNameId).draw();
});
I'm trying to get value of jQuery Chosen element, but not getting anything. I think it could be because there is no value yet when I am searching for it, but not sure with that, because when the page loads, I can already see the value, which I need to get, on page. I've searched some threads here, but no solution worked for me. If anyone would know how to move with this, I would be so glad, thanks!
(I have to get value of <span> inside of <a class="chosen-single"> ) and it's not because I don't have included jQuery library. I have, but I haven't pasted it here.
FIDDLE: https://jsfiddle.net/camm8yLj/
<a class="chosen-single" tabindex="-1">
<span>I/37 Chrudim - obchvat, úsek křiž. I/17 - Slatiňany</span>
</a>
$(document).ready(function(){
$('.chosen-single').chosen().change(function () {
$(this).find('span').each(function(){
alert('Text : '+$(this).text());
alert('Value : '+$(this).val());
});
});
});
You can take the text using find method.
$('select').find('option:selected') retrieves you all the options which are selected.
$('select').chosen();
$('select').change(function(){
$(this).find('option:selected').each(function(){
alert('value:'+$(this).val()+' text: '+$(this).text());
});
});
$(document).ready(function() {
// Chosenify every multiple select DOM elements with class 'chosen'
$('select.chosen').chosen();
$('select.chosen').change(function(){
$(this).find('option:selected').each(function(){
alert('Value:'+$(this).val()+', Text: '+$(this).text());
});
});
});
* { font-family: arial; }
h1 { font-size: 1.5em; }
h2 { font-size: 1.3em; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.1.0/chosen.jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.1.0/chosen.css" rel="stylesheet"/>
<h1>The Chosenified multiple <select></h1>
<p>
<select name="fruits" class="chosen" multiple style="width: 500px;">
<option value="banane">Banane</option>
<option value="pomme">Pomme</option>
<option value="poire">Poire</option>
<option value="ananas" selected>Ananas</option>
<option value="kiwi" selected>Kiwi</option>
<option value="goyave">Goyave</option>
<option value="abricot">Abricot</option>
<option value="fraise" selected>Fraise</option>
<option value="framboise">Framboise</option>
<option value="avocat" selected>Avocat</option>
</select>
</p>
Look at this example code:
<html>
<head>
<script type="text/javascript" src="jquery-1.8.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("body").on('click', "#teste",function(){
$('#teste').append('<option id="pera">pera</option>')
$('#teste').show();
});
});
</script>
</head>
<body>
<select id="teste">
<option value="banana">banana</option>
<option value="laranja">laranja</option>
</select>
</body>
My problem here is that the click event show the select box and only after it updates it with the new value ("pera"). What I need to do is first update the select with the new value and only after show it. Is there anyway to do that using jQuery? Thanks in advance, guys!
EDIT:
Ok, let me try to explain a little bit clear: Whenever you click in a select to show the options it show it automatically (it's obvious!). My problem is that I need to intercept the click event, update the select and only after it show the select. But it's showing the select (it's the default behaviour) before updating. Here is what happening:
1) Select with initial values: banana, laranja
2) User click it. What I want: Show banana, laranja and pera as options. What happens: It shows banana, laranja in the list, show it and only after update the select (If I inspect the html code with fiebug, the pera option is there!). If I click again inthe select, the pera options appears normally and as the code above says, it appends another pera option in the select that only appears in the next click and so on.
I'm a little bit confused.. do you just want to update the select when the page loads? If so you can do:
CSS:
#teste {
display: none;
}
JS:
$(function(){
$('#teste').append('<option id="pera">pera</option>').val("pera").show();
});
I think this might be what you are searching for:
Using the value:
$('[name=options]').val( 3 );//To select Blue
To reset it use:
$('[name=options]').val( '' );
Using the text:
$('[name=options] option').filter(function() {
return ($(this).text() == 'Blue'); //To select Blue
}).prop('selected', true);
Link: http://forum.jquery.com/topic/how-to-dynamically-select-option-in-dropdown-menu
i think you want to prevent showing multiple times the teste option.
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<style>
#teste{
display: none;
}
</style>
<script type="text/javascript">
$(document).ready(function(){
$(document).click(
function(){
if(!$('#teste').is(':visible')){
$('<option/>',{
'id' : 'pera',
'html' : 'pera',
'selected' : 'selected'
}).appendTo('#teste');
$('#teste').show('slow');
}
})
});
</script>
</head>
<body>
<select id="teste">
<option value="banana">banana</option>
<option value="laranja">laranja</option>
</select>
</body>
I am trying to check if a check box is checked and show an element on the page if it is checked.
This is my function:
function checkedTechSolutions(){
Y.one('#techsol input[type=checkbox]').on('change', function (e) {
var target = e.currentTarget,
techSBox = Y.one('#techsolutions');
if (target.get('checked')){
techSBox.show();
} else techSBox.hide();
}
}
This is my css:
#techsolutions {width: 380px; height: 100px; background-color:#cee4f2; display: none;}
#techsolutions .box {text-align: center;}
This is my html:
<div id="techsolutions">
<div class=box>
<label for="TypeOfTS">Tech Solutions: </label>
<select name="techSolutionsDrop">
<option value="techServices">Choose your services </option>
</select>
</div>
</div>
Some notes:
Your example lacked the checkbox in #techsol
Was checkedTechSolutions ever called? You do not need a document ready type event to attach a listener to a checkbox when using YUI.
Use css classes to change visuals like this. It is easier to understand and cleaner.
Take a look at the full solution in this jsfiddle