Finding value of checkbox in dynamically created element - javascript

So, I'm writing some JS which dynamically creates some DOM elements. Below is a structure of the elements created:
<div class='list_item' key='1'>
<p>Hello, World!</p>
</div>
<div class='cont' key='1'>
<input type='checkbox' name='test'/>
</div>
When an event is triggered, I want to loop through all .list_item, and find their corresponding .cont, using the key attribute as an identifier. I want to find the value of the .cont > input[type="checkbox"].
Here's my code so far:
$('.list_item').each(function() {
var x = $('.cont[key="' + $(this).attr('key') + '"]').find('input[type="checkbox"]').prop('checked');
console.log(x);
});
Instead of getting a true or false response, my code throws undefined as its result. What can I do to my code to get the response I want (the value of the checkbox)?
Thanks

Two problems:
You forgot to close the attribute selector
You forgot the . before cont in the class selector
So:
$('.list_item').each(function() {
var x = $('.cont[key="' + $(this).attr('key') + '"]').find('input[type="checkbox"]').prop('checked');
// ------------^--------------------------------------^
console.log(x);
});
Note that you can do that with a single selector rather than find:
$('.list_item').each(function() {
var x = $('.cont[key="' + $(this).attr('key') + '"] input[type="checkbox"]').prop('checked');
console.log(x);
});
Example:
$('.list_item').each(function() {
var x = $('.cont[key="' + $(this).attr('key') + '"] input[type="checkbox"]').prop('checked');
console.log(x);
});
<div class='list_item' key='1'>
<p>Hello, World!</p>
</div>
<div class='cont' key='1'>
<input type='checkbox' name='test' />
</div>
<div class='list_item' key='2'>
<p>Hello, World!</p>
</div>
<div class='cont' key='2'>
<input type='checkbox' name='test' />
</div>
<div class='list_item' key='3'>
<p>Hello, World!</p>
</div>
<div class='cont' key='3'>
<input type='checkbox' name='test' checked/>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

I see that your selector is wrong. The class dot is missing. Try with this:
$('.cont[key="' + $(this).attr('key') + '"')

you just missed '.' before class selector
$('.list_item').each(function() {
var x = $('.cont[key="' + $(this).attr('key') + '"]').find('input[type="checkbox"]').prop('checked');
console.log(x);
});

Related

Create buttons with data from divs

So i have these divs created from wordpress post and they have data attribute which is taken from php <?php echo $rengdata->format('Y-m'); ?>
<div class="renginiai-box">
<div class="col-sm-3" data-renginiolaikas="2017-09"></div>
<div class="col-sm-3" data-renginiolaikas="2017-09"></div>
<div class="col-sm-3" data-renginiolaikas="2017-09"></div>
<div class="col-sm-3" data-renginiolaikas="2017-10"></div>
</div>
What I need right now is to create one single button with unique date. Result should be like this.
<div class="laikotarpis">
<button value="2017-09" class="laiko-btn">2017 09</button>
<button value="2017-10" class="laiko-btn">2017 10</button>
</div>
I have no idea what function could fit this. Should I make array or there is a jQuery function for this
You can use jQuery to iterate through all elements with the data attribute data-renginiolaikas and append a button:
$('[data-renginiolaikas]').each(function(s, e) {
var val = $(this).attr('data-renginiolaikas');
if(!$('.laikotarpis button[value=' + val + ']').length) {
$('.laikotarpis').append('<button value="' + val + '" class="laiko-btn">' + val.replace('-',' ') + '</button>');
}
});
Example: https://codepen.io/anon/pen/KZQgBw
I think that this is much closer :
$('[data-renginiolaikas]').each(function(s, e) {
if($('.laikotarpis button').val() != $(this).attr('data-renginiolaikas')){
$('.laikotarpis').append('<button value="' + $(this).attr('data-renginiolaikas') + '" class="laiko-btn">' + $(this).attr('data-renginiolaikas').replace('-',' ') + '</button>');
}
});
Fork of delinear's answer
https://codepen.io/boian-ivanov/pen/MrQjPy

How to send emojis using jquery?

In my webpage, I have an input method and a button which opens a popup with smiles. When a user taps a smile once, the input value is changed to 'current value' + ':smile1:', for example. However, I have about 28 smile icons and this way to send emojis is a little bit difficult. How can I make this process easier? Because after this, I'll need to parse all 28 smiles and check if the input value equals one of them.
My popup:
<div class="smile-popuptext" id="smPopup">
<div class="smile1"></div>
<div class="smile2"></div>
<div class="smile3"></div>
//.....and other 25 divs
</div>
My function that sends the smile:
$('.smile1').on('click', function () {
var message = $('#message').val() + ' :smile1:';
$('#message').val(message);
});
I'd recommend giving all the buttons a single class and giving them unique id's.
So something like this:
<div class="smile-popuptext" id="smPopup">
<div class="smile" id="smile1"></div>
<div class="smile" id="smile2"></div>
<div class="smile" id="smile3"></div>
//.....and other 25 divs
</div>
Then:
$('.smile').on('click', function () {
var message = $('#message').val() + ' :' + this.id + ':';
$('#message').val(message);
});
JSFiddle
You could bind an EventListener on the container and defining the value as a data attribute:
var container = document.querySelector('.smile-popuptext');
container.addEventListener('click', function(event) {
var target = event.target;
var emoji = target.getAttribute('data-emoji');
if(emoji) {
console.log('clicked', [':', emoji, ':'].join(''));
}
});
<div class="smile-popuptext" id="smPopup">
<div class="sm1" data-emoji="smile1">1</div>
<div class="sm2" data-emoji="smile2">2</div>
<div class="sm3" data-emoji="smile3">3</div>
</div>
With no changes in your markup:
$('#smPopup div[class^="smile"]').on('click', function () {
var message = $('#message').val() + ' :' + this.className + ':';
$('#message').val(message);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="smile-popuptext" id="smPopup">
<div class="smile1">smile 1</div>
<div class="smile2">smile 2</div>
<div class="smile3">smile 3</div>
</div>
<textarea id="message"></textarea>

JavaScript | jQuery | Selecting In Layers: Select Closest Children But Their Children

The goal is to select any descendant(s) -- regardless of direct-descendant indication -- but not their children. In other words, if I'm searching from document I'd like to find all children which are not wrapped by the target selector:
<div id="a1" class="scenario-1" data-behavior="test">
test
<div id="a2" data-behavior="test">
test 1
<div id="a3" data-behavior="test">
test 2
</div>
</div>
</div>
<div class="scenario-2">
<div id="b1" data-behavior="test">
test 1
<div id="b2" data-behavior="test">
test 2
</div>
</div>
</div>
$(document).findAllInFirstLayer([data-behavior]);
This, ideally, would select #a1 & #b1 in the result-set. However, #a2, #a3, and #b2 should not be included, as this would proceed one scope to many.
The complimentary function for this will be recursive to drill down to the next scope for each layer-element in the set. So the next recursive call would return a set containing #a2, #b2, but not #a3 or any children ([data-behavior]) of #b2.
Also, this Question should not be marked as a duplicate of this question as the Accepted-Answer is not acceptable here -- the accepted answer here should use a jQuery selector or prove its impossibility with only using a jQuery selector.
Edit
With #guest271314's help, we reached the following answer:
'[data-behavior]:not([data-behavior] [data-behavior]), [data-behavior]:first'
Now, a recursive function can be used to take a parent-context and find the first-level scopes -- and recur in that fashion indefinitely. Here's an example:
arm: function autoRegisterModules(parent) {
var $firstScope = $(parent).find('[data-behavior]:not([data-behavior] [data-behavior]), [data-behavior]:first');
console.log('#context, #first-scope', parent, $firstScope);
if ($firstScope.length) {
$firstScope.each(function (i, p) {
autoRegisterModules(p);
});
}
},
Please be sure to give credit where it's due.
#prethanks
This, ideally, would select #a1 & #b1 in the result-set.
Try using :not() for first result set , :first for next results
var first = $("[data-behavior]:not([data-behavior] [data-behavior])"),
second = first.find("[data-behavior]:first"),
third = second.find("[data-behavior]:first");
console.log(first, second, third);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="a1" class="scenario-1" data-behavior="test">
test
<div id="a2" data-behavior="test">
test 1
<div id="a3" data-behavior="test">
test 2
</div>
</div>
</div>
<div class="scenario-2">
<div id="b1" data-behavior="test">
test 1
<div id="b2" data-behavior="test">
test 2
</div>
</div>
</div>
So the next recursive call would return a set containing #a2, #b2, but not #a3 or any children ([data-behavior]) of #b2.
using $.fn.extend()
(function($) {
$.fn.extend({
layers: function(sel) {
var root, next, res = [],
sel = sel || this.selector;
if ($(sel + ":not(" + sel + " " + sel + ")").length) {
root = $(sel + ":not(" + sel + " " + sel + ")");
res.push([root]);
if (root.find(sel + ":first").length) {
next = root.find(sel + ":first");
res.push([next]);
while (next.find(sel + ":first").length) {
next = next.find(sel + ":first");
res.push([next])
}
}
}
return this.data("layers", res)
}
})
}(jQuery))
var layers = $("[data-behavior]").layers().data("layers");
$.each(layers, function(key, value) {
console.log(key, value[0])
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="a1" class="scenario-1" data-behavior="test">
test
<div id="a2" data-behavior="test">
test 1
<div id="a3" data-behavior="test">
test 2
</div>
</div>
</div>
<div class="scenario-2">
<div id="b1" data-behavior="test">
test 1
<div id="b2" data-behavior="test">
test 2
</div>
</div>
</div>

JQuery DOM get Binded attribudes

I have a code
$(".showerPr").on('click', '.prototypeDiv',function(){
});
HTML looks like
<div class='showerPr' data-id='3'>
<div class='prototypeDiv' data-id='5'><div>
</div>
Is there some solution to get showerPr data-id and prototypeDiv data-id seperately?
somethink like
$(this).attr('data-id');
$(this).before().attr('data-id');
:-D thank you.
.showerPr isn't before() the .prototypeDiv element, it's the parent element
var proto = $(this).data('id');
var shower = $(this).parent().data('id');
$(".showerPr").on('click', '.prototypeDiv',function(){
var proto = $(this).data('id');
var shower = $(this).parent().data('id');
$('#result').html('prototypeDiv : ' + proto + '<br />' + 'showerPr : ' + shower)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='showerPr' data-id='3'>
<div class='prototypeDiv' data-id='5'>Click Me !!!<div>
</div>
<br/><br/>
<div id="result"></div>
#adeneo is right, .showerPr is the parent element. You may want to check the Traversing Methods for jQuery.
Here are the snippets.
$(".prototypeDiv").on('click', function(){
alert($(this).data('id'));
alert($(this).parent().data('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='showerPr' data-id='3'>
<div class='prototypeDiv' data-id='5'>123<div>
</div>

JQuery Adding the values of 2 divs into a third div

I have 3 divs with numbers in each...
<div id="one">1</div>
<div id="two">5</div>
<div id="total">0</div>
What I need to do for example is:
If #one is click then Add the values of #one and #two and update it on #total
So, in the case above total would look like this:
<div id="total">6</div>
HTML:
<div id="one">1</div>
<div id="two">5</div>
<div id="total">0</div>
<input id="btn-calculate" type="button" value="Calculate" />
JavaScript:
var one = document.getElementById('one'),
two = document.getElementById('two'),
total = document.getElementById('total');
document.getElementById('btn-calculate').onclick = function() {
total.innerHTML = parseInt(one.innerHTML) + parseInt(two.innerHTML);
};
Demo
$('#one').click(function(){
$("#total").text(
parseFloat($(this).text()) +
parseFloat($("#two").text())
);
});
​$("#one")​.click(function(){
$("#total").html(parseInt($(this).text()) + parseInt($("#two").text()))
})​
http://jsfiddle.net/daniilr/G4Snm/
Try this,
Live Demo
$("#one").click(function() {
$('#total').text(parseFloat($('#one').text()) + parseFloat($('#two').text()));
});​

Categories

Resources