get the childern value using jquery - javascript

I have the following html
<li class="selector">
<a>
<input type="checkbox" value="test" />
</a>
</li>
How do i get the value of checkbox. I have following jquery click event.
$('.selector').on('click', function() {
var vals = $(this).children('input').val();
alert(vals); #showing as undefined
});

Try to use find method instead:
var vals = $(this).find('input').val();
If you will have more than 1 input you will need to filter what to get, for example
var vals = $(this).find('input').eq(0).val();
Will get only first input value

Use .find() instead of .children()
var vals = $(this).find('input[type="checkbox"]').val();
find() – search through the matched elements’ child, grandchild, great-grandchild…any levels down.
children() – search through the matched elements’ child only (single level down)
As per your HTML, checkbox is grandchild

Related

Select the elements with at least one value in their data attribute, which is included in a certain array

I am writing a filtering function, in which I need to select the elements that have a certain value in their data attribute, and those values are included in an array, allow me to explain it in an example:
For example, I have three elements and a button as follows:
<div data-foo="aa,cc,ff" ></div>
<div data-foo="bb,cc,ff" ></div>
<div data-foo="bb,dd,ee" ></div>
<div class="button" data-boo="aa,ff" ></div>
The data-foo in each element contains comma-separated values. When I click on the button, I create an array (myArray in the code below) from its data attribute, then I need to select those elements that at least one of the values in that myArray is in their data-foo, for a clear explanation please see the code below:
$( ".button" ).click(function() {
// First I make an array from the button's data attribute
var myArray = $(this).data('boo').split(',');
// Select should be elements that their da-foo has at least one
// — of values in the array above
var Select = "?"
});
How the Select variable can target the first two elements, since the first one has both "aa" and "ff", and the second element has "ff".
I really tried to put it the way that makes sense, if it is not clear enough, please let me know and I will be happy to explain more, thank you.
You can use Attribute Contains Selector:
$( ".button" ).click(function() {
// First I make an array from the button's data attribute
var myArray = $(this).data('boo').split(',');
// produces array of strings like '[data-foo*="aa"]'
var selectors = myArray.map(function(value) {
return '[data-foo*="' + value + '"]';
});
// searches by selectors joined by comma, returns all elements
// that satisfy at least one selector
var selectedElements = $(selectors.join(','));
});
Lets use Array.prototype.some for this:
$(".button").click(function() {
// First I make an array from the button's data attribute
var myArray = $(this).data('boo').split(',');
// Select should be elements that their da-foo has at least one
// — of values in the array above
var Select = $("div[data-foo]"); //select all elements with data-foo
Select.each(function(index, element) {
var isInMyArray = $(element).data("foo").split(",").some(function(element) {
if ( myArray.indexOf(element) != -1)
{return true;}//if true then element is in myArray
}); //using some here - if one value is found in array return true.
console.log(isInMyArray);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-foo="aa,cc,ff"></div>
<div data-foo="bb,cc,ff"></div>
<div data-foo="bb,dd,ee"></div>
<div class="button" data-boo="aa,ff">test</div>

jQuery get element attribute from nested element

I'm in a situation as follows:
<span class="inputgrp">
<span class="additem">
</span>
</span>
<input type="text" avl="abc">
I'm trying to get the value of the attribute avl from the input with a click event on class="inputgrp"
I have tried with:
$(".additem").click(function () {
var v = $(this).parent().find("input:text").attr("avl")
})
and
$(".inputgrp").click(function () {
var v = $(this).prev("span").next("input:text").attr("avl")
})
But without success. Would appreciate some guide as I have no clue what I am dong wrong.
$(".inputgrp").click(function() {
alert($(this).next("input:text").attr("data-avl"))
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="inputgrp">
<span class="additem">
1
</span>
</span>
<input type="text" data-avl="abc">
Use data attribute since avl is not a valid attribute
use .next() since input is next to the click element
.find searches for children of the current element. The input is not a child but a sibling of .inputgrp
$('.inputgrp').on('click',function() {
var v = $(this).siblings('input[data-avl]').attr('data-avl');
});
Use data-avl as an attribute to make it valid.
Use the .sibling() function to select any of the siblings
If the input element is always going to be the next element, use the .next() function
use a data-avl="" attribute on your html input element and in jQuery use .data('avl') to get the value of the attribute
$(".inputgrp").click(function() {
alert($(this).next("input:text").data("avl"));
})

jQuery traversing. Find siblings including itself

I'm using jQuery traversing to jump between DOM elements.
First of i have a onClick function:
$(document).on('keyup', '.size, .ant', function(){
Inside of this function I send data about what's clicked, to another function.
sulorTableRowWeight( $(this) );
function sulorTableRowWeight(thisobj){
Now, I'd like to traverse from the clicked element $(this) to its parent. I'd like to find the parent's siblings and then traverse down to a specific sibling.
var inputSize = $(thisobj).parent().siblings('.sizeTd').children('.size');
My problem is when I want to traverse back down to the element I came from, it is not listed as a sibling because it isn't a sibling...
var inputSize = $(thisobj).parent().siblings(); console.log(inputSize)
console will give me the siblings, but not the one U came from...
So, when a user clicks ".size" I'd like to traverse up to the parent and back to size.... When a user clicks ".ant" I'd like to traverse up to the parent and then down to ".size"...
I tried to hardcode the traversing:
var inputSize = $(thisobj).parent().siblings('.sizeTd').children('.size');
But it won't work because it is not actually a sibling.
So what is it? And how can I get back to it?
If it is not possible, I have to run some if/else statements, U guess...
UPDATE
$(document).on('keyup', '.size, .ant', function(){
//Find changed <select> .tbody
var tbodyId = $(this).parent().parent('tr').parent('tbody').attr('id');
//Check <tbody> #id
if(tbodyId === "cpTableBody"){
}
else if(tbodyId === "sulorTableBody"){
sulorTableRowWeight( $(this) );
}
else if(tbodyId === "konturTableBody"){
konturTableRowWeight( $(this) );
}
else if(tbodyId === "kantbalkTableBody"){
kantbalkTableRowWeight( $(this) );
}
})
//Function sulorTableRowWeight
function sulorTableRowWeight(thisobj){
//Find the selected data-weight
var selectedWeightmm3 = $(thisobj).parent().siblings('.selectTd').children('.select').find(':selected').data('weightmm3');
//Find input .size value
var inputSize = $(thisobj).parent().siblings('.sizeTd').children('.size'); console.log(inputSize)
PROBLEM
My var inputSize will return undefined when I click a ".size" element. That´m's because it is not listed as a sibling to itself.
I know it's keyup, not click...
e.target will select the current input
$(document).on('keyup', '.size, .ant', function(e) {
inputSize = $(e.target);
if($(e.target).is('.ant')) {//test if the element is .ant
inputSize = $(e.target).parent().find('.size');//get .size based on .ant
}
console.log(inputSize[0]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input class="size x1" placeholder="x1">
<input class="ant x1" placeholder="x1 ant">
</div>
<div>
<input class="size x2" placeholder="x2">
<input class="ant x2" placeholder="x2 ant">
</div>
Hmm, if you're passing in $(this) as thisObj I don't think you need to be nesting thisObj in a $(). (See note below)
Anyway, you could try using .parents('<grandparent>').find('<child>') so basically you're traversing one higher level up the tree with <grandparent>, then getting all the descendants that match the child selector. That should include the branch of the three that $(this) represents. But it's hard to say for sure without seeing your HTML.
** A good practice when assigning jQuery objects to variables is to use $ syntax, ie var $this = $(this) so you know anything prepended with a $ is a jQuery object.
inside sulorTableRowWeight , you should have the reference to the clicked element in thisobj variable.

Jquery assign second child attribute

Is there a way to assign nested div attribute with variable? Like
<div>
<div>
123456
</div>
</div>
Become
<div>
<div sectionid="123">
123456
</div>
</div>
BTW above component will be created by JavaScript.
I've tried something like this, but it didn't work.
var a = $('<div><div>123456</div></div>');
a.eq(":nth-child(2)").attr("sectionid", "123");
Try this snippet.
//FOR DOM HTML
console.log("FOR DOM HTML");
//1st way
$('#input > div').find('div').attr("sectionid","123");
console.log($('#input').html());
//2nd way
$('#input > div > div').attr("sectionid","321");
console.log($('#input').html());
//JS HTML
console.log("FOR JS OBJECT");
var input = $('<div><div>123456</div></div>');
//1st way
input.eq(0).children().attr('sectionid', '456');
console.log(input[0].outerHTML);
var input = $('<div><div>123456</div></div>');
//2nd way
$(input[0]).children().attr('sectionid', '789');
console.log(input[0].outerHTML);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="input">
<div>
<div>
123456
</div>
</div>
</div>
nth-child(2) maches elements that are the second child element of their parent. This is not the case for your div, it is the first element of the parent div.
.eq finds an element at a specific index. It is not the place to pass a selector.
The child selector, >, will find a child element, i.e. div>div will find a div that is an immediate child of a div.
Note that the code you've provided, $('<div></div>123456<div></div>');, doesn't create a DOM tree like the one you've pasted.
Update, now that the code is edited, the value of a is a div with a child div. Since a.find will perform a search within a, you don't have to use a child selector, but can find the div immediately:
a.find('div')
Just apply attribute to children. No complicated 'find', eq(), etc.
var a = $('<div><div>123456</div></div>');
a.children().attr('sectionid', '123');
$('body').append(a);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Why don't you add it in the first place? Not clear if you add it later!
$(document).ready(function() {
var sectionid = "123";
var a = $('<div><div sectionid="' + sectionid + '">123456</div></div>');
$('body').append(a);
});
div[sectionid]{
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Try this - I have added comments to the code to explain what is happening.
Inspect the element to see that the attribute is added
var a = $('<div><div>123456</div></div>'); // change this to match the structure you want
a.children() // .children gets the direct descendant (which should be the nested div
.eq(0) // gets the first in the array that is returned (if there are multiple direct descendents) - it is a 0 based index selector
.attr('sectionid', '123');
$('body').append(a)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
More information about .children()
More information about .eq()
try it :
$(document).ready(function(){
$("div").eq(1).attr("sectionid","123");
})

Get value of child input

I have a li that has a hidden value and I want to get this value
...
<li class="list-group-item" id="A1">item name<input type="hidden" class="bssid-val" value="myvalue"></li>
...
I thought the following would work, put apparently not.
$('body').on('click', '#hook_list li', function(){
var BSSID = $('this').siblings('.bssid-val').val();
How do I get myvalue?
There are 2 problems in your code:
this is a keyword. 'this' is a string. $('this') tries to select elements that have tagName of this, i.e. <this></this>. You should remove the quotes.
The target element is the child of the clicked element. So you need to use children or find method instead of the siblings method.
$(this).children('.bssid-val').val();
$('body').on('click', 'li', function(){
var BSSID = $(this).children('.bssid-val').first().attr("value");
alert(BSSID);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li class="list-group-item" id="A1">item name<input type="hidden" class="bssid-val" value="myvalue"/></li>
If you want a different click selector you can use it , I generalized with only li

Categories

Resources