Cannot add class to next element of $(this) - javascript

I want to add class, next to checked input. So, class will be added to span, which is next to a checked input radio.
<label>
<input type="radio" name="option[228]" value="20" checked="checked">
<span data-toggle="tooltip" data-placement="top" title="" data-original-title="Purple (+₹20)">
<img src="http://countrylivings.com/image/cache/catalog/sample/q2-50x50.png" alt="Purple +₹20" width="36px" height="36px">
</span>
</label>
I have tried a no. of ways to do so... But didn't work. like---
$(document).ready(function(){
if ($('label input').is(':checked')) {
$(this.element).next().addClass('hloo');
alert($(this.element).val());
};
});
But i get an alert of undefined when input is checked.
So,
if ($('label input').is(':checked')) {
is working fine to detect if checkbox is checked But
$(this) or $(this.element)
is not working.
Anyone know what is going wrong?

There's three issues in your code. Firstly ::checked is not a valid jQuery selector, it's just :checked.
Secondly, assuming this is a reference to an Element object (as it is in the vast majority of cases in jQuery) then there is no element property. Just use $(this).
Lastly, if conditions run under the outer scope, so this would refer to the document in your example, not the input. It's for this reason val() is undefined; you're looking at document.value. To fix this, select the element directly before working with it:
$(document).ready(function() {
var $checkedInput = $('label input:checked');
$checkedInput.next().addClass('hloo');
console.log($checkedInput.val());
});
.hloo { color: #C00; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>
<input type="radio" name="option[228]" value="20" checked="checked">
<span data-toggle="tooltip" data-placement="top" title="" data-original-title="Purple (+₹20)">
<img src="http://countrylivings.com/image/cache/catalog/sample/q2-50x50.png" alt="Purple +₹20" width="36px" height="36px">
</span>
</label>

Related

Get variable inside certain div with jquery, when there are multiple divs with same id

I'm printing an arraylist with jsp. Each object inside of that arraylist is printed with a loop like this:
<% ArrayList <MessageObject> list = (ArrayList<MessageObject>) request.getAttribute("list"); %>
<%int index = 0;%>
<%for(MessageObject msg :list){
index++;
if(mensaje.getState().compareTo("unread") == 0){%>
<tr data-status="unread" class="unread">
<td>
<a href="javascript:;" class="star">
<i class="glyphicon glyphicon-star"></i>
</a>
</td>
<td>
<div class="media">
<h4 class="title">
User Identifier
</h4>
</div>
</td>
<td id="unread-id">
<div class="media">
<p class="summary"><% out.print(msg.getMessage());%></p>
<input id="index" type="text" value="<%out.print(index);%>"></input>
</div>
Some of the closing tags and other structures are not written above, in order to make my code easier to read.
Basically that prints me messages from a queue, and its index in the arraylist:
My problem is that I want to save the index value of any of my messages when I click on them.
I tried this:
<script>
$(document).on('click', '#unread-id', function () {
var index = $('#index').val();
$("#setindex").val(index);
});
So I click on any div containing a message, the script is called, but I always get the same index value, 1.
Problem is that having always the same div with the same id name, causes that my script always selects the first div with id unread-id, which is always the first one, so it returns 1.
How can I get the index of the clicked div, if all my container divs have the same id value?
Add a class to your <td id="unread-id"> like row and change your script for the following one. Your td should end up looking like <td class="row">. Also, don't use ids in your inputs, change it to a class, like row-input.
JS
$(document).on('click', '.row', function () {
var index = $(this).find('.row-input').val();
$("#setindex").val(index);
});
JSP Changes
<td id="unread-id"> to <td class="row">
<input id="index" type="text" value="<%out.print(index);%>"></input> to <input class="row-input" type="text" value="<%out.print(index);%>"></input>
Note
You are setting the same id to all your rows. An id must be unique and that is the reason you keep getting the same index.
First - id should be unique in your page. You should really fix this (and if you need some selector to work with multiple elements - you can use classname instead).
However - your code can work (might cause issues with some browsers, so I really advise you to fix this asap):
$(function() {
$(document).on('click', '#unread-id', function () {
console.log($(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="unread-id" value="1" /><br />
<input id="unread-id" value="2" /><br />
<input id="unread-id" value="3" /><br />
<input id="unread-id" value="4" /><br />
When inside the click function - the this element is the element you just clicked. You can use that in order to get the value that you need.

jQuery if element id exists add class to the same element

I am trying to addClass to an input if it exists and trigger a click else addClass to different element and trigger a click on it in jQuery but I am having some problems and tried different ways but with no luck.
This is the html:
<td>
<input type="radio" name="shipping_method" value="free.free" id="free.free" />
<label for="free.free">Free</label>
<input type="radio" name="shipping_method" value="flat.flat" id="flat.flat" />
<label for="flat.flat">Payed</label>
</td>
and my script :
<script language="Javascript" type="text/javascript">
$(document).ready(function(){
if($('#free.free').length > 0) {
$('#free.free').addClass('sgcheck');
$('.sgcheck').trigger('click');
}
else {
$('#flat.flat').addClass('sgcheck');
$('.sgcheck').trigger('click');
}
});
</script>
You need to escape dot character in id selector with double \\:
$('#free\\.free').length
otherwise #free.free selector means element with id free and class name free, which your HTML obviously doesn't have.

Check which checkboxes is checked

I have read this post and this post and others but i didnt get it to work in my code.
here is the Fiddle for better see my code on live.
this is my js
//////first code to try////
if ($('input.chek').is(':checked')) {
$('.check-addon').css('background-color','green');
}
//////second code///////
var boxes = $('input[class="chek"]:checked');
$(boxes).each(function(){
$('.check-addon').css('background-color','green');
});
this is my html
<div class="inline-container"><div class="checkboxes" >
<span class="check-addon"><input id="id1" class="chek" type="checkbox" value="1" name="id1">title1</span>
<span class="check-addon"><input id="id2" type="checkbox" class="chek" value="1" name="id2">title2</span>
<span class="check-addon"><input id="id3" type="checkbox" class="chek" value="1" name="id3">title3</span>
</div></div>
i dont know what im doing wrong here . i couldnt get the background Green Of the checked box in my code.
any help would much apreciated.
EDIT
even the answers down works in fiddle But i guess i have more problem here.
if i write html code above Normal , the js code is fired and works But im using html code inside js function like that:
function houses(){
var x ='<div class="inline-container"><div class="checkboxes" >
<span class="check-addon"><input id="id1" class="chek" type="checkbox" value="1" name="id1">title1</span>
<span class="check-addon"><input id="id2" type="checkbox" class="chek" value="1" name="id2">title2</span>
<span class="check-addon"><input id="id3" type="checkbox" class="chek" value="1" name="id3">title3</span>
</div></div>';
return x ;
}
so this function when i call it it works but when i want apply the above code on it its not working and not firing at all.
this function is Out of the Dom handler. Fiddle here
Bind the input with a on change event
$('.chek').on('change', function () {
$(this).closest('.check-addon').css('background-color',this.checked?'green':'none');
});
DEMO
Update
You need to use event-delegation on dynamically added elements
$(document).on('change','.chek',function(){
$(this).closest('.check-addon').css('background-color',this.checked?'green':'none');
});
You need to use click/change event to detect the changes on checkboxes. Use:
$('input').change(function(){
if (this.checked)
$(this).parent().css('background-color','green');
else
$(this).parent().css('background-color','none');
});
Demo
You can use this:
$("input:checkbox").on("change", function(){
if($(this).prop("checked")){
$(this).parent(".check-addon").css('background-color','green');
}
else{
$(this).parent(".check-addon").css('background-color','white');
}
});
fiddle
You have to do like this :
1st Way:
$(".chek").change(function () { // will fire when checkbox checked or unchecked
if (this.checked) // check if it is checked
$(this).closest(".check-addon").css('background-color', 'green'); //find parent span and add css
else
$(this).closest(".check-addon").css('background-color','transparent');
})
FIDDLE:
http://jsfiddle.net/2u697b57
2nd Way:
More better approach is to create a css class and add/remove it on check/uncheck:
CSS:
.green
{
background-color:green;
}
JQUERY:
$(".chek").change(function () {
if (this.checked)
$(this).closest(".check-addon").addClass("green");
else
$(this).closest(".check-addon").removeClass("green");
FIDDLE:
http://jsfiddle.net/2u697b57/1/

JavaScript Toggle Checkboxes breaks if you select in certain order (Mind Blowing!)

Obviously checkboxes can be selected in whatever order you want but I'm having issues with this breaking. I cannot get checkbox C to appear when I select in the following order: A-D-C or D-A-C. If you select in order or reverse order it works fine AND it always works in Firefox for some reason. You can view this anomaly Click here for weird fiddle.
Why is this? How can I work around it?
HTML
<input type="checkbox" id="Abox" data-info-id="infoa">
<label for="Abox"> Checkbox A</label><BR>
<input type="checkbox" id="Bbox" data-info-id="infob">
<label for="Bbox"> Checkbox B</label><BR>
<input type="checkbox" id="Cbox" data-info-id="infoc">
<label for="Cbox"> Checkbox C</label><BR>
<input type="checkbox" id="Dbox" data-info-id="infod">
<label for="Dbox"> Checkbox D</label><BR>
CHECK AN ITEM ABOVE IT SHOULD APPEAR BELOW<P>
<div style="background-color:silver;">
<div id="infoa">
<input type="checkbox" id="kwd2" >
<label for="kwd2"> ALPHA</label><BR>
</div>
<div id="infob">
<input type="checkbox" id="fff1">
<label for="fff1"> BETA</label><BR>
</div>
<div id="infoc">
<input type="checkbox" id="zzz3">
<label for="zzz3"> CHARLIE</label><BR>
</div>
<div id="infod">
<input type="checkbox" id="kwd5" >
<label for="kwd5"> DELTA</label><BR>
</div>
</div>
JAVASCRIPT
document.addEventListener('change', function(e) {
var id = e.target.getAttribute('data-info-id');
var checked = e.target.checked;
if (id) {
var div = document.getElementById(id);
if (div) div.style.display = checked ? 'inline' : 'none';
alert("bang");
}
});
CSS
[id^="info"] {
display: none;
}
Weird bug, seems to have something to do with having inline -> block -> inline divs.
Changing the display to "block" instead of "inline" will do the trick though.
if (div) div.style.display = checked ? 'block' : 'none';
It looks like a Webkit (doesn't work in Safari or Chrome) bug displaying the inline divs. C's block is "displayed," it just has 0 width and height. I'm not certain what the spec says about inline divs, but they're not conventional. If you use block instead of inline it works.
(Edit deleted, it was wrong.)
Edit: this appears to be a simple browser redraw bug. You can make the inner part
<span id="infoa">ALPHA<br></span><span id="infob"></span><span id="infoc">CHARLIE</span><span id="infod">DELTA</span>
and it fails the same way. The newline before the non-displayed #infob appears to trigger #infoc's display problem. Seems like this should be reported to the Webkit people.

Get name from one element and call to another element

Disclaimer:This is a unique situation and very hackish.
I have one set of radios that are visible to users and another set that is hidden. I need to pull the name from the hidden set and assign to the visible set.
Hidden radios:
<div class="productAttributeValue">
<div class="productOptionViewRadio">
<ul>
<li>
<label>
<input type="radio" class="validation" name="attribute[139]"
value="86" checked="checked" />
<span class="name">Standard Shipping</span>
</label>
</li>
etc etc...more li's
</ul>
</div>
</div>
A visible radio:
<label>
<input type="radio" class="validation" name="PUT OTHER NAME HERE" value="86" checked="checked" />
<span class="name">Standard Shipping</span>
<p class="rl-m"><small>Earliest Date of Delivery:</small>
<small><span id="delivery-date"></span></small></p>
</label>
So, in this case, I would like the name "attribute[139]" to somehow be gotten from the hidden radio and called to the name of the visible radio. I'm thinking of something like this:
<script>
$(function() {
var name = $(".productOptionViewRadio span.name:contains('(Standard)')").attr('name');
});
</script>
I'm not too sure about the script being the right way to go about this and also not sure how I would actually get the value from the one element to populate to the other element's name field.
Thank you very much.
Update: Fiddle http://jsfiddle.net/susan999/XBcaF/
Try
$('label input[type=radio]').attr('name',
$('.productOptionViewRadio input[type=radio]').attr('name'));
http://jsfiddle.net/XBcaF/5/
Try this
$('input:radio.validation:visible').attr('name',function(){
return $('input:radio.validation:hidden').attr('name')
})
Could improve the selectors if know more about parent classes of visible radios, or what elements are actualy being set as hidden
You can try something like this:
var checkboxCount = 0;
$("#visibleCheckboxes").find("input[type=checkbox]").each(function(){
$($("#hiddenCheckboxes").find("input[type=checkbox]").get(checkboxCount)).attr('name', $(this).attr('name'));
checkboxCount++;
});
I've prepared a Fiddle for you: http://jsfiddle.net/MJNeY/1/

Categories

Resources