Now I have an input when typing in the input it automatically displays a list based on query.
When the 'Favourite' star icon is clicked I want to call some function. Here the problem is when the input is in focus. The first click is not working when input is still in focus. The second time the function is called.
How do I avoid this and make the click work first time even though input is in focus?
let name = 'foo';
jQuery($ => {
$("#search-input").on("change keydown paste input", function() {
if (this.value == "") {
return true;
}
// some filter function on object to loop and display below list.
$(".search-result").append("<li class='searchitem'>" + name + " <i class='favourite far fa-star'></i></li>");
});
$(document).on("click", ".favourite", function() {
alert("hi");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" integrity="sha512-1ycn6IcaQQ40/MKBW2W4Rhis/DbILU74C1vSrLJxCq57o941Ym01SwNsOMqvEBFlcgUa6xLiPY/NS5R+E6ztJQ==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<input type="text" id="search-input" />
<ul class="search-result">
</ul>
Related
Suppose, I have a delegated input field with the class name 'bulk_number' inside a parent class name 'all_bulk_inputs', and a button that will add a random number to that input field whenever I click it. Now I want to trigger a change event listener whenever the number change.
For Example:
<!-- input field under all_bulk_inputs -->
<div class="all_bulk_inputs">
<input class="bulk_number" name="rand_number" /> <!-- dynamically added under the 'all_bulk_inputs' parent -->
</div>
<button id="add_rand">Add Random Number</button>
<script>
$('#add_rand').on('click', function(){
$('.bulk_number').val(10) //suppose, 10 is my random number
//what I want is forcefully trigger on change like bellow, if possible
$('.all_bulk_inputs').trigger('change', 'bulk_number', function(){
console.log('bulk number changed)
})
})
</script>
First of all you have an error in line log. There is a few way to do this but this is the simple one i have explained what does code with comments
console.log('bulk number changed)
then you may want to check document of change Change
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<div class="all_bulk_inputs">
<input class="bulk_number" name="rand_number" /> <!-- dynamically added under the 'all_bulk_inputs' parent -->
</div>
<button id="add_rand">Add Random Number</button>
<script>
$(document).ready(function() {
//When random number setted to the input under all_bulk_inputs div below will triggered
$('.all_bulk_inputs .bulk_number').on('change', function() {
console.log(`bulk number changed and the value is ${$(this).val()}`)
})
$('#add_rand').on('click', function() {
// create between 0 and 100 number and set to input
const rnd = Math.floor(Math.random() * 100)
$('.bulk_number').val(rnd).change()
})
});
</script>
</body>
</html>
I am using Bootstrap select dropdown which has the following code.
HTML
#Html.DropDownList("Product", SelectList, new { data_live_search = "true", #class = "content-small selectpicker", #tabindex = 1 })
In this dropdown I need to provide an option to add new values which are typed in the search bar in the dropdown to the existing collection of the dropdown based on the click event. I have modified the UI to say "Create" instead of No results found. Please refer the code and UI below.
JS
$('#Product').selectpicker({ noneResultsText: 'Create ' });
UI
I am trying to add click event to this text "Create" content which is highlighted in the screenshot above to add that content dynamically to the existing collection of the dropdown.
But, while clicking that text the dropdown gets closed and the element which shows the text gets removed, hence I could not call the on click function to add this item dynamically.
What are the possibilities of using this?
I think you're skipping that the input you're dealing with is outside of the .selectpicker. You can find working snippet below.
$('.selectpicker').selectpicker({
noneResultsText: 'Create '
});
$(".selectpicker").on("click",".creator",function(){
$("p span").html("Clicked for "+$(".pickercontainer .bs-searchbox input").val());
});
.creator {
display:inline-block;
float:left;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel = "stylesheet" type = "text/css" href = "https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" />
<link rel = "stylesheet" type = "text/css" href = "https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/css/bootstrap-select.css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/js/bootstrap-select.js"></script>
<div class='pickercontainer'>
<select class="selectpicker" data-live-search="true" >
<option>Alabama</option>
<option>Alaska </option>
<option>Arizona </option>
</select>
</div>
<br>
<p>Action: <span></span></p>
$('.selectpicker').selectpicker({
noneResultsText: '<span class="pointer" onclick="createNew(this);"><b>{0}</b> (create new)</span>'
});
function createNew(event){
var value = $(event).parents('div').siblings('.bs-searchbox').find('input').val();
//Do something....
alert(value);
}
I have a focusout event
$('.alpha').on("focusout", function () {...});
and I want want to trigger it from somewhere else in the code.
I tried $('#input12').focus().blur();
and also tried $('#input12').trigger("focusout")
edit: I am using a dynamically generated elements.
but no luck there...
the element #input12 has the class name alpha so I expect The focusout event to be triggered.
Is there any way of getting it done?
here is a jsfiddle example of when I am trying to do https://jsfiddle.net/jnmnk68d/
You need to delegate your events to a non-dynamic parent element.
In this example, we listen for focusout events on the form but only fire our function if the event's target matches the selector (in this case ".alpha"). This way the event can be fired on any elements that match now or in the future.
$("form").on("focusout", ".alpha", function() {
console.log("focusout happened!");
});
Here's a full demo which allows you to see how using delegated events we are able to trigger the event on dynamically inserted content.
$(function() {
$("form").on("focusout", ".alpha", function(e) {
console.warn("focusout triggered on " + e.target.outerHTML);
});
//example trigger
//click the link to trigger the event
$("a").on("click", function(e) {
e.preventDefault();
$("#input12").trigger("focusout");
});
//demo injecting content
//click the create button then focus out on the new element to see the delegated event still being fired.
var i = 12;
$("form").on("submit", function(e) {
e.preventDefault();
var id = "input" + (++i);
$(this).find("fieldset").append("<input id='" + id + "' class='alpha' placeholder='" + id + "' />");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<fieldset>
<input id="input12" class="alpha" placeholder="input12" />
<input type="submit" value="create new" />
</fieldset>
</form>
trigger on input12
Using [0] on the jQuery element works! Also kontrollanten options works too! And doing a normal trigger on focusout too!
$(".alpha").on("focusout", function(e){
console.log(e.type, true);
});
//option 1
$('#input12')[0].focus(); //vanilla
$('#input12')[0].blur(); //vanilla
//option 2
$('#input12').trigger('focusout');
//option 3
$('#input12').trigger('blur');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="alpha" id="input12" />
Here is a working example taken from the jQuery docs.
var focus = 0,
blur = 0;
$("p")
.focusout(function() {
focus++;
$("#focus-count").text("focusout fired: " + focus + "x");
})
.inputs {
float: left;
margin-right: 1em;
}
.inputs p {
margin-top: 0;
}
<html lang="en">
<head>
<meta charset="utf-8">
<title>focusout demo</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div class="inputs">
<p>
<input type="text"><br>
<input type="text">
</p>
</div>
<div id="focus-count">focusout fire</div>
</body>
</html>
Maybe if you add your full code I can be of better help?
Hope this helps!
See this code, it will call focusout 1second after focus has happend.
$('.alpha').on("focusout", function() {
console.log('FOCUSOUT!');
});
$('.alpha').on("focus", function() {
var self = $(this);
window.setTimeout(function() {
self.focusout();
}, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="text" class="alpha" />
I found out what seemed to be wrong with my code..
first of all I changed my event to use delegation and I connected it to a non dynamic element (element that was not added dynamically) just as some here advised.
I also needed to call the trigger function inside a setTimeout because it turns out that it takes a while to render the dynamically added element, so using the setTimeout did the trick.
Thank you all for helping out!
I've some problems with JQuery Autocomplete, my code it's like:
var mySource = [{"label":"Value one","id":"1"},{"label":"Value two","id":"2"},{"label":"Value three","id":"3"}];
$("#txtAutocomplete").autocomplete({
source: mySource,
select: function(event, ui){
if(ui.item){
//console.log('select', ui.item.label);
$("#hiddenField").val(ui.item.id);
return ui.item.label;
}
else{
//console.log('select with null value');
$("#hiddenField").val('');
}
},
change: function(event, ui){
if(ui.item){
//console.log('change', ui.item.id);
$("#hiddenField").val(ui.item.id);
}
else{
//console.log('change with null value');
$("#hiddenField").val('');
}
}
});
<link href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<p>
<ol>
<li>Type 'Value' in the text box</li>
<li>Press 'arrow down' to select the first element</li>
<li>Press enter</li>
<li>Keep pressed backspace to delete completely the selected item</li>
<li>Press TAB</li>
<li>Value in 'readonly' field is still there</li>
</ol>
</p>
<input type="text" id="txtAutocomplete">
<input type="text" id="hiddenField" disabled="disabled">
<button>Button added just to have an element to focus on</button>
When I put the string 'value' in the editable field, autocomplete appears correctly, so I can select one value and put it in the textbox with id hiddenField.
Then, if I clear the value in the textbox, I can't update the related hiddenField with a blank value, because change event doesn't fire. Why?
Steps to test snippet:
Write 'value' in the editable field
Select one value
Clear the selected value
hiddenField will still contain old value.
Thanks
Note: It doesn't work when I clear the field after selection but still keeping the focus on it.
Updated: I reported the bug here on bugs.jqueryui.com
I have run to this problem and there is a hack to avoid the problem. You have to force a blur but with a setTimeout
if(ui.item){
//console.log('select', ui.item.label);
$("#hiddenField").val(ui.item.id);
setTimeout(function () {
$(event.target).blur();
});
return ui.item.label;
}
You don't have to keep the inputs in sync inside the autocomplete options. Attach a separate event handler to your text input like so:
$("#txtAutocomplete").autocomplete({
source: ['test1', 'test2', 'test3'],
select: function(event, ui){
console.log('select', ui.item.value);
$("#hiddenField").val(ui.item.value);
}
});
$("#txtAutocomplete").on("input propertychange", function () {
console.log("change", this.value);
$("#hiddenField").val(this.value);
});
<link href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<input type="text" id="txtAutocomplete">
<input type="text" id="hiddenField" disabled="disabled">
When I run your code snippet, the change event does get fired each time I select an item, or when I clear the value, and the log gets printed. But the event gets fired only after I tab out after a selection, or after I click outside the auto-complete input element.
This is because, as per the documentation, the change event gets fired only when the element loses focus.
Steps that make it work:
Write 'test' in the editable field, and select an option
Tab out - this fires the change event
Delete the value
Tab out - this fires the change event
I have a list of of checkboxes that are being used a search fields for a database. When someone clicks a checkbox it will show a button with the text from the label of that checkbox. However, I need that button to be have empty text when it is not visible (in the case of someone clicking the checkbox to hide the button).
Here's my code:
$(document).ready(function() {
$('#locationAll').click(function() {
var value = $('#locationAll').parent().text();
$('#location-all-button').html(value + " ×").toggle('fast');
});
});
$(document).ready(function() {
$('.search-popup').click(function() {
$(this).hide('fast');
});
if ($('.search-popup').css('display') == 'none') {
$(this).text("");
};
});
button {
background-color: lightgray;
border-radius: 20px;
display: none;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
<input type="checkbox" value="all" id="locationAll" />All
</label>
<br>
<br>
<button class="search-popup btn" id="location-all-button"></button>
For some reason I can't make the button stay hidden before the checkbox on the example here but that isn't a problem in my full code. if you need more info let me know I might have missed something.
Ok so I changed a few things. I made this work for any checkbox that follows the naming scheme I made really quickly. The scheme is the id of the button = the "button-"+id. Also I hiding all buttons with a class right form the start to set their default state.
$(document).ready(function()
{
\\change to allow all checkboxes to trigger
$('input[type=checkbox]').click(function()
{
\\change the id so it match a button when add "button-" to the start
\\this allows me to target the matching button with any chechbox
$('#button-'+$(this).attr('id')).toggle('fast');
});
$('.search-popup').click(function()
{
$(this).hide('fast');
\\ sets the check box to false so it not checked when you close it
$("#"+$(this).text().replace(" ×","")).attr('checked', false);
});
\\hides all buttons right form the start
$('button.search-popup').each(function()
{
$(this).hide();
});
});
<label>
<input type="checkbox" value="all" id="All" />All
</label>
<br>
<br>
<button class="search-popup btn" id="button-All">All ×</button>
now if you want to create and remove buttons when a checkbox has changed state you can add an if state meant in that checks to see if the button with the matching id exists or not,!$(tag).size().