<img> as EventHandler in JS Function - javascript

I'm trying to bind a click handler for my search field to an img or class with on() but it will not work. I'm adding the image with this code:
jQ('#psc').append('<div class"psc-search-wrapper" style="float:left;"><input class="psc-input"></input><img class="psc-search-image"title=""/></div>');
var table = $('#tbl-me').DataTable();
table.columns().eq(0).each(function(colIdx) {
var searchHandler = $(".psc-search-image");
jQ('.psc-input', table.column(colIdx).header()).on('click', searchHandler, function() {
table.column(colIdx).search(this.value).draw();
});
});

You should select the parent of the <div class"psc-search-wrapper" ... you just appended then select the child which is the searchHandler.
you can't select jQ( '.psc-input', ... you should select the parent then use find() to select it :
var myInput = jQ('#psc').find('.psc-input')

var table = $('#tbl-me').DataTable();
jQ('#psc-search').on('click',function(){
var pscValue = jQ('.psc-input').val();
table.column(3).search(pscValue).draw();
});
Solved :)

Related

JS: Fail to obtain object after change of filter

So I have a list of items with anchor a that successfully listen to the following event:
$('body[data-link="media"] #media_content a').on('click',function(e){
e.preventDefault();
var page = $('.page.active a')[0].innerHTML;
var date = $('.year_sorting .filter_years').val();
var id = $(e.currentTarget).data('media');
window.location.href = 'http://'+basePath+'media/content/'+id+'?date='+date+'&page='+page;
})
However in the same page, there is a filter allowing the user to change the year filter and once changed, the following execute and append a list of items that has the exact same layout as the a above $('body[data-link="media"] #media_content a'), which supposes to listen to the above event as well. the filter event is below:
$('.activity.filter_years').on('change',function(){
$('.pagination_ul').remove();
r_year = $(this).val();
$.get("media/getActivity",{type:'0',key:r_year}).done(function(d){
if(d.length>0){
$('#media_content').html('');
var ul = '<ul class="ap pagination-sm pagination_ul"></ul>';
$('.pagination_menu').append(ul);
for(var i=0;i<d.length;i++){
var p = ['',''];
if(!d[i].event_period){
p = ['style="color:#8A8A8A;"','style="color:#C7C7C7;"'];
}
if(locale=='en'){
var event = $('<div class="div_media_content_f2 '+d[i].pagination+' pagination-tr"> <div class="div_media_content_f2_3"> <span class="font12_bold">'+d[i].event_date+'</span> <div>'+d[i].event_title+'</div></div></div>')
}else if(locale=='hk'){
var event = $('<div class="div_media_content_f2 '+d[i].pagination+' pagination-tr"> <div class="div_media_content_f2_3"> <span class="font12_bold">'+d[i].event_date+'</span> <div>'+d[i].event_title_zh+'</div></div></div>')
}else {
var event = $('<div class="div_media_content_f2 '+d[i].pagination+' pagination-tr"> <div class="div_media_content_f2_3"> <span class="font12_bold">'+d[i].event_date+'</span> <div>'+d[i].event_title_cn+'</div></div></div>')
}
$('#media_content').append(event);
}
pagination('.pagination_ul','.pagination-tr',Math.ceil(d.length/20),false);
}else{
$('#div_news_content_right').html('').append('<div class="not_available">No content available</div>');
}
})
})
in which you can see the list of items are being appended into the layout by JS. However, even with the same layout $('body[data-link="media"] #media_content a'), such appended list of items do not listen to the onclick event. the above js codes are together in a separate js file apart from the html file where I tried to put the first a event into the html file but the new appended list of items still do not listen.
Cannot think of other work around at the moment, please help to see what would be the cause of it. Thank you.
Maybe simple try this.
$(document).on('click', 'body[data-link="media"] #media_content a')
If your element is dynamic create you should bind the click event on document and target what's element should dispatch the event.This is different to bind click only on element because the event will unbind while you remove the element.
Updated:
I'm not sure I've understand all the script you have but I try to simplify the issue.
This is the jsbin and its work correctly.
JSBin

Dynamically adding event handler to select box

I'm trying to dynamically add an event listener to a select box.
With this code I just don't get any response, so no alert box:
var table = $('<table></table>');
var row = $('<tr><td></td></tr>').html('<select id="sel1"><option>test</option><option>test2</option></select>');
$("sel1").on('change', function() {
alert(this.val());
});
table.append(row);
$('#mydiv').append(table);
Also, how can I add the select box between the td?
Currently, it's added between the tr, td simply isn't there.
Here is a fiddle
Updated Fiddle
You should use event delegation on() when you deal with fresh DOM added dynamically :
$("#mydiv").on('change', '#sel1', function() {
alert($(this).val());
});
NOTES :
You should add id selector before sel1 it should be #sel1.
.val() is a jquery method you can't call it on javascript object like this.val() it should be $(this).val().
The current code will not add select inside td it will add it directely inside tr tag so you could replace :
var row = $('<tr><td></td></tr>').html('<select id="sel1"><option>test</option>
<option>test2</option></select>');
By :
var row = $('<tr></tr>').html('<td><select id="sel1"><option>test</option><option>
test2</option></select></td>');
Hope this helps.
Working Snippet
var table = $('<table></table>');
var row = $('<tr></tr>').html('<td><select id="sel1"><option>test</option><option>test2</option></select></td>');
$("#mydiv").on('change', '#sel1', function() {
alert($(this).val());
});
table.append(row);
$('#mydiv').append(table);
td{
border: 1px solid;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mydiv"></div>
Couple of points to note in your code
1) Wrong Selector $("sel1")
The problem in your code is $("sel1") you need to select by id using # so it should be $("#sel1"). So your code would be like
$("#sel1").on('change', function() {
alert(this.val());
});
2) Bind event after appending the HTML to DOM or Use Event Delegation
Your code should be places in this order Working Fiddle
var table = $('<table></table>');
var row = $('<tr><td></td></tr>').html('<select id="sel1"><option>test</option><option>test2</option></select>');
table.append(row);
$('#mydiv').append(table);// now the element is added to DOM so bind event
$("#sel1").on('change', function() {
alert($(this).val()); // note here I changes this.val() to $(this).val()
});
Or another option is using event delegation Working Fiddle
To add event's to dynamic elements use the event delegation
$('body').on('change',"#sel1", function() {
alert($(this).val());
});
3) To place the select tag inside td use the below syntax
var row = $('<tr></tr>').html('<td><select id="sel1"><option>test</option><option>test2</option></select></td>');
Wrap the td along with the select tag and not inside the tr Working Fiddle
You need to bind the change event after appending to the page:
var table = $('<table></table>');
var row = $('<tr><td></td></tr>').html('<select id="sel1"><option>test</option><option>test2</option></select>');
table.append(row);
$('#mydiv').append(table);
$("#sel1").on('change', function() {
alert(this.val());
});
And also you have forgotten the # id selector for "sel1"
There are three major issues in your code
1.The id selector must start with #
$("#sel1").on('change', function() {
2.You should bind the change listener only after you appended the element, because it just doesn't exist in the DOM before
3.With
$('<tr><td></td></tr>')
you'll get a jquery reference to the row (the <tr> element). Then with .html() you are replacing the content of the row (including the <td> of course)

Custom JS/CSS select alternative without jquery

I am trying to make a custom select just like this, but without jquery (I just dont want to import a whole new library for one single thing). I made it until this, but I dont know how I can make the selection with regular JS. How can I select something from the list?
If you just want to show the selected item in the dropdown,
You need to wrap the text to be displayed inside a <span> as follows
<div class="label"><span>Select Element</span><b class="button">▾</b>
</div>
Then you can change it's innterHTML to display the selected item using the following js:
var dd = document.querySelector('.label span');
var options = document.querySelectorAll('div.hidden ul li');
for (var i = 0; i < options.length; i++) {
options[i].onclick = select;
}
function show() {
var selectbox = document.getElementById("options");
if (selectbox.className == "hidden") {
selectbox.setAttribute("class", "visible");
} else {
selectbox.setAttribute("class", "hidden");
}
}
function select() {
dd.innerHTML = this.innerHTML;
}
Demo
Listen to clicks on your div#options. Demo
function choose(ev, el) {
var options = el, target = ev.target,
value = ev.target.innerHTML;
options.setAttribute('class', 'hidden');
options.parentElement.querySelector('.label').innerHTML = value;
}
<div id="options" class="hidden" onclick='choose (event, this);'>
Side notes. I don't recommend to use inline handlers. Use addEventListener instead.
You need to define an onclick handler of your li elements. Either in HTML, or in JS by looping through children of div container with li elements http://jsfiddle.net/rWU5t/2/
If you want fancy item highlights on mouse hover, you also need to define onmouseover and onmouseout handlers.

Attaching data to DOM elements

I m new to jquey.I m facing a problem to attach data to particular inner div's. I am writing a demo code for the problem that i faced which did the same behaviour as original one. I have to small div inside a big div and i want to store (for some further processing) and show some data to small div's based on user input.
[html code]
<div id="ctrl-1001" class="big">
<div id="m1" class="small"></div>
<div id="m2" class="small"></div>
</div>
<div id="input" class="control-group module">
<label class="control-label">Module Name</label>
<div class="controls">
<select id="ModuleName" name="DSname" class="input-large">
<option>TitleImage</option>
<option>SearchBox</option>
<option>CategoryLinks</option>
<option selected>BannerSlides</option>
</select>
</div>
<button id="sa">save</button>
</div>
[jquery code]
$('.small').click(function(){
$('#input').show();
var myId = $(this).attr("id");
var myParentId = $(this).parents('.big').attr('id');
var uniqueId = '#'+myParentId+' #'+myId;
create(uniqueId);
});
function create(uniqueId){
$('#input').show();
$('#ModuleName').change(function(){
var name = this.value;
$('#sa').click(function(){
save_name(name,uniqueId);
});
});
}
function save_name(name,uniqueId){
var div = $(uniqueId)[0];
jQuery.data(div,'store',name);
//alert(uniqueId);
//var val = jQuery.data(div,'store');
$(uniqueId).text(name);
$('#input').hide();
}
But the problem is when I click on second div to store some data the first div also changes the value which second one contains. demo on Jsfiddle
It is because when you click the first time one change handler is added to the select with targeting #m1 element, then again when you click on #m2 a new change handler is added without removing the first one, so when you click the button both these code gets executed.
So try
$('.small').click(function () {
var uniqueId = '#' + this.id;
create(uniqueId);
});
function create(uniqueId) {
$('#input').show();
//remove previously added handlers
//take a look at namespaced event handlers
//also there is no need to have a change handler for the select element
$('#sa').off('click.create').on('click.create', function () {
var name = $('#ModuleName').val();
save_name(name, uniqueId);
});
}
function save_name(name, uniqueId) {
var div = $(uniqueId);
//you can use the .data() method instead of the static jQuery.data() method
div.data('store', name);
//alert(uniqueId);
var val = div.data('store');
$(uniqueId).text(name);
$('#input').hide();
}
Demo: Fiddle
But a more jQueryish solution might look like
var $smalls = $('.small').click(function () {
var uniqueId = '#' + this.id;
$smalls.filter('.active').removeClass('active');
$(this).addClass('active');
$('#input').show();
});
$('#sa').on('click', function () {
var name = $('#ModuleName').val();
save_name(name, '.small.active');
});
function save_name(name, target) {
var div = $(target);
//you can use the .data() method instead of the static jQuery.data() method
div.data('store', name);
//alert(uniqueId);
var val = div.data('store');
div.text(name);
$('#input').hide();
}
Demo: Fiddle

Select2 Dynamic elements not reacting to event

I am using Select2 which works great. However I am using below code to create new dynamic select2 drop down but they do not react/open when clicking on them.
var relationshipcounter = 0;
$('#AddMoreRelationships').click(function () {
var $relationship = $('.relationship'); // div containing select2 dropdown
var $clone = $relationship.eq(0).clone();
$clone[0].id = 'id_' + ++relationshipcounter;
$relationship.eq(-1).after($clone);
$relationship.find('select').trigger('change'); // not working
});
Screenshot:
JSFIDDLE:
http://jsfiddle.net/pHSdP/133/
I had this exact problem and, of course, the first thing I tried was a deep copy with data:
el.clone(true,true);
Which did not work. Instead the best method I found was:
el=other_el.clone()_etc; // cloning the old row
el.find('.select2-container').remove();
el.find('select').select2({width: 268});
el in both of these snippets is the div row that contains the select and so the Select2 element.
Essentially what I do in the second snippet is remove the "old" select2 which will always have the class of .select2-container and then recreate it on all found select elements within my new row.
You need to call clone with the true argument to copy over events and data as well. Otherwise only the element gets cloned, not the events that are bound to it.
$relationship.eq(0).clone(true);
Docs:http://api.jquery.com/clone/
Ok so issue is resolved, fiddle:
http://jsfiddle.net/WrSxV/1/
// add another select2
var counter = 0;
$('#addmore').click(function(){
var $relationship = $('.relationship');
var $clone = $("#RelationshipType").clone();
$clone[0].id = 'id_' + ++counter;
$clone.show();
$relationship.eq(-1).after($clone);
$clone.select2({ "width" : "200px" });// convert normal select to select2
//$('body').select2().on('change', 'select', function(){
// alert(this.id);
//}).trigger('change');
return false;
});
After cloning your object you have to reassign event for em:
var $clone = $relationship.eq(0).clone();
$clone.on("click", function_name);
Use .on to bind dynamically inserted elements to events like
$('body').on('click','#AddMoreRelationships',function () {
});

Categories