Retrieving values from for loop into jquery - javascript

How do I retrieve values from #for loop into jquery..Each value inside for loop should have different id, and jquery should get each separate id....
My for loop,
#for (int i = 0; i < searchList.Count;i++ )
{
<label for="input#i"><input type="checkbox" id="input#i"/>#searchList[i] </label>
}
My jquery which isn't helping,
$("#input#i").on("click", function () {
var currentChk = $(this);
var propCheck = currentChk.prop("checked");
if (propCheck) {
debugger;
var valChk = $("#input#i").val();
alert(valChk);
}
});
Thanks in advance...

You can use Attribute Starts With Selector to bind the event.
$("[id^=input]").on("click", function () {
var currentChk = $(this);
var propCheck = currentChk.prop("checked");
if (propCheck) {
debugger;
var valChk = $("#input#i").val();
alert(valChk);
}
});
As the id of both label and input-checkbox starts with 'input' the click event will bind to both of them. If you want to restrict you can add type to the selector, for instance you want only on checkbox you can change selector as under.
$("input[id^=input]").on("click", function () {...
or
$(":checkbox[id^=input]").on("click", function () {...
If you assign a class to the control you want to attach event then you can use class selector to bind the event.
#for (int i = 0; i < searchList.Count;i++ )
{
<label for="input#i"><input type="checkbox" class="chk-class" id="input#i"/>#searchList[i] </label>
}
$(".chk-class").on("click", function () {...
Edit As Mohamed-Yousef pointed you should use currentChk preferably or $(this) instead of $("#input#i") in statement $("#input#i").val(); as #i will not be the substituted value by C# loop but it will be added as string literal.
As a additional note you may use native javascript whenever possible and suitable e.g I would use this.checked instead of currentChk.prop("checked") to get the better performance, readability and simplicity.
$("[id^=input]").on("click", function () {
if (this.checked)
{
//your code
}
else
{
//your code
}
});

if you want to trigger onclick for all input
$("input").click(function () {
var currentChk = $(this);
var propCheck = currentChk.prop("checked");
if (propCheck) {
var valChk = "Id:" + this.id + " Value:" + this.value;
alert(valChk);
}
});

$("input:checkbox [id^=input]").click(function(){
if ($(this).is(":checked")) {
var valChk = $("this").val();
alert(valChk);
}
});
this another option you can use

Related

After filling a list dynamically (at runtime) even if I add a delegate listener I have to click two times to trigger click-event

When I fill a list (e.g. unordered list) dinamically (at runtime: e.g. Ajax), even if I add a delegate listener, the first click never works. Only after second click the event is triggered. Does anyone know why? What's wrong?
Without delegation
<body>
<input type="text" id="my-textbox"/>
<ul id="list"></ul>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
var sayHello = function (e) {
e.preventDefault();
alert("Hi");
};
var fillList = function (e) {
var text = $(this).val();
var $ul = $('#list').empty();
for (var i = 0; i < text.length; i++) {
var $a = $('<a href="#">').text("List item " + i).on("click", sayHello);
var $li = $('<li>').append($a);
$ul.append($li);
}
};
$(document).ready(function () {
$("#my-textbox").on("keyup, change", fillList)
.bind("input propertychange", fillList);
});
</script>
</body>
With delegation (scope to difference only)
var fillList = function (e) {
var text = $(this).val();
var $ul = $('#list').empty();
for (var i = 0; i < text.length; i++) {
var $a = $('<a href="#">').text("List item " + i); // here edited
var $li = $('<li>').append($a);
$ul.append($li);
}
};
$(document).ready(function () {
$("#list").on("click", 'a', sayHello); // and here edited
$("#my-textbox").on("keyup, change", fillList)
.bind("input propertychange", fillList);
});
Again: first click does not work in both cases. After second click, it works.
Ok, solved. I thoud you use bind("input propertychange") to be sure if you paste text from clipboard, a change (on textbox) is triggered. So, if you use bind("input propertychange"), using on("keyup, change") is redundant.
$("#my-textbox").bind("input propertychange", fillList); // so this is enough; this works

jQuery Show image in a div with a third click

function () {
var i = 0;
$('.class').click(i=i+1)
if(i=3) {
$('.class2').css('display','block');
}
}
This code does not work, Please help me.
Should be :
$(function() { //ready function
var i = 0;
$('.class').click(function(){ //Attach click event to '.class'
i=i+1; //Or i++;
if(i===3) { //Use triple equal '===' for comparaison
$('.class2').css('display','block');
}
})
})
Hope this helps.
You should bind your click event outside the function, and then track the 3rd click. You should also use a comparison operator instead of assignment. Of course, all of this should be wrapped in document ready.
var i = 0;
$('.class').on('click', function() {
i = i + 1;
if(i === 3) {
$('.class2').css('display','block');
}
});
Here is a Fiddle Demo.

JavaScript/jQuery: Select on change event not firing

I have this problem trying to getting one single function attach multiple individual functions on "Change" event of a dropdown list using for ... in loop. The $('select') object top has no method 'on' is the Type error detected by Chrome Debugger.
Here is my code: (I don't have much JavaScript / jQuery knowledge so please be bear up with my coding)
function AKaizerDropdown(HiddenFeild) { //#id of hidden field passed as parameter
var select = $('select'); // select object assigned to variable
var selectcount = 0;
var Selecthold=new Array();
for (select in this) {
select.on('change', function() {
var SelectedIndex = this.attr('selectedIndex');
selecthold[selectcount] = [select.attr('id'), selectedindex];
//Select ID and Selected index assigned as an array into Selecthold Array element
});
selectcount +=1;
}
var item= new array();
//Elements in selecthold array printed onto hidden field
for (item in selecthold) {
$(HiddenFeild).val += item[0] + item[1]; //Assigns values to element Hiddenfield in DOM
}
}
Edited Code :
$.fn.AKaizerDropdown = function (HiddenFeild) {
var select_ = $(this).find('select');
var selectcount = 0;
var Selecthold=new Array();
select_.each(function () {
$(this).on('change', function () { //everything runs fine except dropdownlist doesn't enter into this event when an item is chosen
var SelectedIndex = this.selectedIndex;
Selecthold[selectcount] = [this.id, Selectedindex];
});
});
var button_ = $(this).find('input')
button_.on('click', function () {
for (item in Selecthold) {
$(HiddenFeild).val += item[0] + item[1]+','; //Assigns values to element Hiddenfeild in DOM seperated by ","
}
});
}
Somewhat fixed code still doesn't work
Here is the part where i attach it to popover Bootstrap(twitter 2.3.2) .
//think the problem lies here where the pop up seems to re-render the same same html found in ($#KaizerDragon") where all JavaScript is probably discarded?
$("#ContentPlaceHolder1_ADragonTreeviewt41").popover({
html: true, container: 'body',
trigger: 'click',
content: function () {
$(function () {
$("#KaizerDragon").AKaizerDropdown();
});
return $("#KaizerDragon").html();
}
});
So my question is how can I correct the above code to get the intended output(as in comments within code) ?
You are declaring
var select = $('select'); // select object assigned to variable
But then overriding the value in your for loop
for (select in this) ...
That is to say, the select inside the loop isn't the same as you declared above.
try something like this
select.each(function(){
$(this).on('change', function() {
var SelectedIndex = this.selectedIndex;
Selecthold[selectcount] = [this.id, SelectedIndex];
//Select ID and Selected index assigned as an array into Selecthold Array element
});
})

Target 2 divs for one method?

I have the following function:
$('#cover-drop-zone')[0].ondrop = function(e) {
How can I target two different divs with the above code? I want both divs to have the ondrop method.
Why not use jQuery:
$('#cover-drop-zone, #other-element-id').on('drop', function(e){
// do stuff here
});
Because your question isn't tagged with jquery, you could instead use plain JavaScript:
var elems = document.querySelectorAll('#cover-drop-zone, #other-element-id');
function dropFunction (e) {
// e is the event (passed automatically as the first parameter,
// this will refer to the element on which the function is called
// and whatever your function would/should do...
}
for (var i = 0, len = elems.length; i < len; i++){
elems[i].addEventListener('drop', dropFunction);
}
References:
on().
With this code :
$('#cover-drop-zone, #div2').bind('ondrop ', function(e) { })

Get clicked class index javascript

I have 3 divs with class: wpEdit and onClick: alertName()
<div class="wpEdit" onClick="alertName()">Bruce Lee</div>
<div class="wpEdit" onClick="alertName()">Jackie Chan</div>
<div class="wpEdit" onClick="alertName()">Jet li</div>
When clicked i want to know the Index of class wpEdit of the clicked Div:
function alertName(){
//Something like this
var classIndex = this.className.index; // This obviously dosnt work
alert(classIndex);
}
when clicked on Bruce Lee it should alert : 0
when clicked on Jackie Chan it should alert : 1
when clicked on Jet Li it should alert : 2
I need to know which instance of class="wpEdit" is clicked on
Try this
function clickedClassHandler(name,callback) {
// apply click handler to all elements with matching className
var allElements = document.body.getElementsByTagName("*");
for(var x = 0, len = allElements.length; x < len; x++) {
if(allElements[x].className == name) {
allElements[x].onclick = handleClick;
}
}
function handleClick() {
var elmParent = this.parentNode;
var parentChilds = elmParent.childNodes;
var index = 0;
for(var x = 0; x < parentChilds.length; x++) {
if(parentChilds[x] == this) {
break;
}
if(parentChilds[x].className == name) {
index++;
}
}
callback.call(this,index);
}
}
Usage:
clickedClassHandler("wpEdit",function(index){
// do something with the index
alert(index);
// 'this' refers to the element
// so you could do something with the element itself
this.style.backgroundColor = 'orange';
});
The first thing you might want to address in your code is the inline HTML binding.
You could use document.addEventListener on each element, or rely on event delegation.
The widely most used implementation of event delegation comes with jQuery. If you're already using jQuery, this is the way to go!
Alternatively I've also my own little delegate utility.
const delegate = (fn, selector) => {
return function handler(event) {
const matchingEl = matches(event.target, selector, this);
if(matchingEl != null){
fn.call(matchingEl, event);
}
};
};
const matches = (target, selector, boundElement) => {
if (target === boundElement){
return null;
}
if (target.matches(selector)){
return target;
}
if (target.parentNode){
return matches(target.parentNode, selector, boundElement);
}
return null;
};
This is how you would register the event listener.
document.getElementById('#parent')
.addEventListener('click', delegate(handler, '.wpEdit'));
And this is how you could get the index of the element that generated the event.
const handler = (event) => {
console.log(Array.prototype.indexOf.call(event.currentTarget.children, event.target));
}
Live demo:
const delegate = (fn, selector) => {
return function handler(event) {
const matchingEl = matches(event.target, selector, this);
if (matchingEl != null) {
fn.call(matchingEl, event);
}
};
};
const matches = (target, selector, boundElement) => {
if (target === boundElement) {
return null;
}
if (target.matches(selector)) {
return target;
}
if (target.parentNode) {
return matches(target.parentNode, selector, boundElement);
}
return null;
};
const handler = (event) => {
console.log(Array.prototype.indexOf.call(event.currentTarget.children, event.target));
}
document.getElementById('parent')
.addEventListener('click', delegate(handler, '.wpEdit'));
<div id="parent">
<div class="wpEdit">Bruce Lee</div>
<div class="wpEdit">Jackie Chan</div>
<div class="wpEdit">Jet li</div>
</div>
If you want the index of the div's based on your class wpEdit you can do like this:
HTML:
<div class="wpEdit">Bruce Lee</div>
<div class="wpEdit">Jackie Chan</div>
<div class="other">Other</div>
<div class="wpEdit">Jet li</div>
JS:
$(".wpEdit").bind("click", function(){
var divs = $(".wpEdit");
var curIdx = divs.index($(this));
alert(curIdx);
});
Live example : http://jsfiddle.net/pJwzc/
More information on the index function of jQuery : http://api.jquery.com/index/
Using vanilla javascript, this one works for me:
var wpEdits = document.querySelectorAll(".wpEdit");
for (let i = 0; i < wpEdits.length; i++)
wpEdits[i].addEventListener("click", showID);
function showID(evt) {
for (let i = 0; i < wpEdits.length; i++)
if(wpEdits[i] == evt.target)
alert(i);
}
May not be the best solution though as I am still new to js.
Since I am very new to JS, take the following explanation with a grain of salt:
(Line-1)
This is similar to var wpEdits = document.getElementsByClassName("wpEdit");. It will assign all instances of class="wpEdit" from the html file to the wpEdits variable.
(Line-3 and Line-4)
This two lines will cause any click on the class="wpEdit" to call function showID() defined below.
(Line-6 and Line-10)
When a click event happens, the browser will pass the unique properties of the item being clicked to the evt variable. This then is used in the for loop to compare against all available instances incrementally. The evt.target is used to get to the actual target. Once a match is found, it will alert the user.
To avoid wasting CPU time, running a break; is recommended to exit the loop soon after the match is found.
I could not understand, why people add new functions in previous answers, so...
const wpEdit = document.getElementsByClassName('wpEdit');
for(let i = 0; i < wpEdit.length; i++){
wpEdit[i].addEventListener('click',function(){
alert(i);
});
}
I just added 'click' event, using the loop. And [i] already is the current clicked class index...
FIDDLE

Categories