jQuery get element attribute from nested element - javascript

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"));
})

Related

Remove html element with javascript

When I press the Submit button if any error is generated then code create a span element.
My question is how I can clear the old error from the error container element, or if not possible then please sum up the errors.
$.each(err.responseJSON.errors, function (i, error) {
var el = $(document).find('[name="'+i+'"]');
el.after($('<span style="color: red;">'+error[0]+'</span>'));
});
I tried remove() but I cannot do it.
Thanks
you can remove the span with next().
next() finds the next sibling to the input field you are referring to.
it will give you the span:
el.next().remove();
you can use a class on the span f.e. class="validation-span"
el.next(".validation-span").remove();
this will make sure you only remove the span and no other element if existent :)
Add an span element after the input and set its HTML each time instead of using .after.
<input name="yourName">
<span class="errors"></span>
<script>
$(document).find('[name="'+i+'"] + .errors')
.html('<span style="color: red;">'+error[0]+'</span>');
</script>
I updated the both way you want, please pick which is more suitable to you
function logErrorCleanSpan(errorMessage){
$('#errorContainer').text(errorMessage);
}
logErrorCleanSpan("Hello");
logErrorCleanSpan("Jarvis");
function logErrorAppendSpan(errorMessage){
var span = $("<span>"+errorMessage+"</span>");
$('#errorContainerSpanAppend').append(span);
}
logErrorAppendSpan("1. Hello ");
logErrorAppendSpan("2. Jarvis ");
#errorContainerSpanAppend{
display:block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>Append Error and clean the previous error<h3>
<span id="errorContainer"></span>
<h3>Append Error and keep the older one<h3>
<span id="errorContainerSpanAppend"></span>
Assign a id with index to span after each click remove previous span using id
Use jquery remove
$.each(err.responseJSON.errors, function (i, error) {
var el = $(document).find('[name="'+i+'"]');
el.after($('<span id="error'+i+'" style="color: red;">'+error[0]+'</span>'));
if($(document).find('span#error+i - 1+')) {
$( "span#error+i - 1+" ).remove();
}
});
this is just an example code not correct code.

How to use 1 id for everything instead of 3 (for the following code)

I have the following html (it's a card) where a class is added to change the look of it:
<div class="card-small-half" id="card-1">
<a href="components/">
<div class="action-bar">
<p>Add Page</p>
<i class="material-icons">add</i>
</div>
</a>
</div>
and a switch made with a label that checks and unchecks an input type checkbox:
<div class="switch-wrapper" id="switch-wrapper-1">
<input type="checkbox" id="input-1" class="display-none">
<label class="switch" for="input-1"></label>
<p id="switch-caption-1">Visible</p>
</div>
With the following Javascript I add a class called "card-disabled" to the card:
window.onload = function () {
function check() {
if (document.getElementById("input-1").checked) {
document.getElementById("switch-caption-1").textContent = "Disabled";
$('#card-1').addClass('card-disabled');
} else {
document.getElementById("switch-caption-1").textContent = "Visible";
$('#card-1').removeClass('card-disabled');
}
}
document.getElementById('input-1').onchange = check;
check();
}
I know in css you can call id's or classes like so:
#switch-wrapper-1 input { /* styles */ }
or
#switch-wrapper-1 p { /* styles */ }
How can I do this with javascript, so I don't have to use an id for every element and instead use a global id for every wrapper.
EDIT:
The wrapper and input id's are unique! I want to call the paragraph inside the unique wrapper element something like this:
document.getElementById("switch-wrapper-1 p").textContent = "Disabled";
The 'p' here means paragraph
Is this possible and if so: how?
Query Selector is your friend here. You can use CSS selectors to retrieve DOM elements. In your case this call would return the first paragraph child in the #switch-wrapper-1 element.
var node = document.querySelector('#switch-wrapper-1 p');
If you also use jQuery, then as suggested in comments, you can simply use the $ function.
var $node = $('#switch-wrapper-1 p');
To select an individual element inside of an element with a specific ID using Javascript you can do:
document.getElementById('hello').getElementsByTagName('input')[0];
So in your example it would be:
document.getElementById('switch-wrapper-1').getElementsByTagName('input')[0].onchange = check;
The [0] is used because getElementsByTagName returns an array of all the child elements inside the parent element with the specified tag. Note that you will have to keep the unique ID on the input field if you want the for attribute on the label to function correctly.

multiple span calls of javascript value

In my header I have
function addusr() {
document.getElementById("usrout").innerHTML = document.getElementById("usrin").value;}
and in my text I have
code-bla bla bla<span id="usrout"></span> bla!! It works!
but if I try to call <span id="usrout"></span> again on the same page at a different location, none of the others appear.
Example:
text <span id="usrout"></span> more text, code... another <span id="usrout"></span>...
...
..
...
another <span id="usrout"></span> ...
Only the first one appears, why is this? How can I fix it?
An ID needs to be unique. You might want to consider classes instead.
When you’ve assigned classes to the HTML elements, your JavaScript code may look like this:
function addusr () {
var usrin = document.getElementById("usrin").value,
usrout = document.getElementsByClassName("usrout");
Array.prototype.forEach.call(usrout, function (el) {
el.innerHTML = usrin;
});
}
Explanation:
Instead of getElementById, we’re using getElementsByClassName which returns an array of elements having that particular classname. Thus a loop is required to set the innerHTML property of each retrieved element.
First of all, using same ID in more than one element is WRONG and against RFC.
You should make it a CLASS, not ID, and then...
document.querySelector(".usrout").innerHTML = ...
Every single element needs a unique ID.
For example
<span id="usrout1"></span>
<span id="usrout2"></span>
Alternatively, you could use classes as mentioned already
<span class="green"></span>
<span class="green"></span>
Then use a CSS selector such as document.getElementByClass
Element IDs must be unique, so getElementById will only ever return (at most) one element.
You need to use a different search, perhaps querySelectorAll, to get all the applicable elements. You can then loop through them, and set the necessary comment.
For example:
function addusr() {
var inputValue = document.getElementById("usrin").value;
var outputs = document.querySelectorAll("span.usrout");
for (var i = 0; i < outputs.length; ++i) {
outputs[i].textContent = inputValue;
}
}
<input id="usrin" type="text" />
<button type="button" onclick="addusr();">Update</button>
<span class="usrout"></span>
<span class="usrout"></span>
<span class="usrout"></span>
<span class="usrout"></span>
<span class="usrout"></span>
<span class="usrout"></span>

get the childern value using jquery

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

Why jquery selector select element from old value instead of new value

Whenever I select element with jquery with selector it select element from old value instead of new value if I get value of selected element it give me new value. My code is here http://jsfiddle.net/HUdkN/3/.
Here I have use Australia value for selecting element ,even if I change value. It will select element. Why ??? could somebody explain it.
HTML CODE
<input type="text" class="lbl" value="Australia" />
<div id="result"></div>
<br />
<br/>
<input type="button" value="check" id="check_btn">
JAVASCRIPT CODE
function check_fnc() {
jQuery('input').removeClass('error');
jQuery('input[value="Australia"]').each(function () {
$(this).addClass('error');
$('#result').html(this.value);
});
}
$('#check_btn').click(function () {
check_fnc();
})
That's because an Attribute Equals selector such as [value="Australia"] matches the actual HTML attribute, not the current DOM property, and the value HTML attribute will always contain the original value of the element.
To match the current value, you can use filter() instead:
$("input").filter(function() {
return this.value == "Australia";
}).each(function() {
$(this).addClass("error");
$("#result").html(this.value);
});
you use this
jQuery('input[value="Australia"]')
// (") should be remove after (value=) and after Australia
You can use that also
function check_fnc() {
jQuery('input').removeClass('error');
// I eddited here
jQuery('input[value=Australia]').each(function () {
$(this).addClass('error');
$('#result').html(this.value);
});
}
hope this will work..Thanks
You don't need to use any filter for this scenario. Just remove quotes ie, use
$("input[value=Australia]") .each(...)

Categories

Resources