Checkbox not unchecking visually - javascript

I have a form and within it is this:
<fieldset class="billing-address">
<legend>Billing Address</legend>
<ol>
<li class="text combi"><label for="bill-address1">Address:</label> <input size="20" value="" name="basket_order:default:bill_address1" id="bill-address1"></li>
<li class="text"><label for="bill-address2">Address:</label> <input size="20" value="" name="basket_order:default:bill_address2" id="bill-address2"></li>
<li class="text"><label for="bill-address3">Town/City:</label> <input size="20" value="" name="basket_order:default:bill_address3" id="bill-address3"></li>
<li class="text"><label for="bill-address4">Region:</label> <input size="20" value="" name="basket_order:default:bill_address4" id="bill-address4"></li>
<li class="text"><label for="bill-post-code">Post code:</label> <input size="10" value="" name="basket_order:default:bill_postcode" id="bill-post-code"></li>
</ol>
</fieldset>
For reasons too biring to go into here, I cannot get at the HTML directly and need to do things via javascript. So, I add a checkbox and label above using the following:
$('.billing-address ol').before('<input type="checkbox" id="billing-add-different" /><label for="billing-add-different">My billing address is the same as my delivery address</label>');
$('#billing-add-different').prop('checked',true).toggle(
function(){
$('.billing-address ol input, .billing-address ol select').css('background','#CCC').attr('disabled','disabled');
},
function(){
$('.billing-address ol input, .billing-address ol select').css('background','#FFF').removeAttr('disabled');
}
);
This toggles the 'disabled' attribute and background colour depending on whether it's ticked or not.
However, though the function is firing, the checkbox is still visually checked.
I've made a jsfiddle to illustrate at http://jsfiddle.net/EFQuh/. The error occurs in Firefox 8.0, not sure about others.

I don't know what is the problem (probably the toggle function), but you can simplify your code to:
$('#billing-add-different').prop('checked',true).change(function(){
$('.billing-address ol input, .billing-address ol select')
.css('background-color', this.checked ? '#CCC' : '#FFF')
.prop('disabled',this.checked);
}).change();
DEMO

You need to use the change event and check this.checked within the event's function.

Related

Bind onlick events on several links

I am currently working on a solution for an application that is written in PHP, but needs a JS solution for a preview link and I am stuck with binding onclick-events on the links. The HTML is given and may not be changed. (so no adding of classes and stuff, even though that would be easier)
My initial thought was to just get each of the li and perform a callable that sets the event and defines the rules for what happens, when the link is clicked.
I am unsure what is the best possible solution to get the values of the two Inputs, belonging to the preview link, as while I was running the code mentioned above on what ever link I clicked, the last item was logged.
So basically this is 2 questions in one:
1. how to properly bind the click events.
2. how to best acces the inputs belonging to the link
var items = $('div.foobar').find('li');
items.each(function() {
this = $(this);
url = lo_this.find('a').attr('href');
this.find('a').click(function(event) {
event.preventDefault();
console.log(this)
/** here is the point, where I got stuck **/
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="foobar">
<li>
Link
<div class="justaname">
<input type="text" name="somenamewith[ID][foo]" value="">
<input type="text" name="somenamewith[ID][bar]" maxlength="50" value="">
</div>
</li>
<li>
Link
<div class="justaname">
<input type="text" name="somenamewith[OTHERID][foo]" value="">
<input type="text" name="somenamewith[OTHERID][bar]" maxlength="50" value="">
</div>
</li>
</div>
You mean this?
Assuming your inputs are in the same LI as the anchor
Ignoring the ID of the anchor and just getting the inputs in the same LI
Other code is needed if you want to use the ID of the link to access the named links
$('div.foobar li a').on("click",function(e) {
e.preventDefault();
$(this).closest("li").find("input").each(function() {
console.log(this.name,this.value)
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="foobar">
<li>
Link
<div class="justaname">
<input type="text" name="somenamewith[ID][foo]" value="">
<input type="text" name="somenamewith[ID][bar]" maxlength="50" value="">
</div>
</li>
<li>
Link
<div class="justaname">
<input type="text" name="somenamewith[OTHERID][foo]" value="">
<input type="text" name="somenamewith[OTHERID][bar]" maxlength="50" value="">
</div>
</li>
</div>
You can do this to bind click events to your links and then do whatever with the input elements contained by the div after the clicked link:
$('.foobar li a').on('click',function(event){
event.preventDefault();
$(this).next().find('input').each(function(){
//Whatever you want to do for each input
});
});

Javascript : Change button text according to hidden variable value

i have hidden variable with default value "on" , i want to change the text of another button from Disable to Enable according to this hidden value , if the hidden field value is "on" the button text is "Disable" and vice verse . i have tried but my solution doesn't work
hidden field
<input name="hiddenV" type="hidden" id="hiddenValue<%=ud.getUserId()%>" value="on" />
button
<input type="button" id="delUserButton<%=ud.getUserId()%>" onclick="openDelDiv(<%=ud.getUserId()%>, '<%=ud.getUserName()%>'); change(this.id);" value="Disable"/>
js function
function change(btn) {
var hiddenValue = document.getElementsByName("hiddenV")[0];
var disButton = document.getElementById(btn);
if (hiddenValue.value === "on")
disButton.value = "Disable";
else
disButton.value = "Enable";
}
OpendelDev() : it's a popup dialog like ( are you sure you want to disable this user) with ok button that causes the page to reload
function openDelDiv(userId, userName) {
$("#userId_delete").val(userId);
$("#userName_delete").text(userName);
$("#delUserDiv").bPopup();
}
but put in mind that the button is placed in for loop inside a jsp page so the id for every button will be different
I think you are actually faking a <input type="radio"/> here.
The goal is then to have an input for each possible value, along with a list of buttons to toggle them. Then, all you have to do is show the buttons you want (ie: show "enable" button if status "disabled" is checked and vice-versa).
<input type="radio" class="input-field" name="status" value="enabled" checked="checked" id="a"/>
<input type="radio" class="input-field" name="status" value="disabled" id="b"/>
<ul class="buttons">
<li>
<label class="enabling" for="a">
<button>Enable</span>
</label>
</li>
<li>
<label class="disabling" for="b">
<span>Disable</span>
</label>
</li>
</ul>
In CSS:
.input-field[value="enabled"]:checked ~ ul.buttons label.enabling,
.input-field[value="disabled"]:checked ~ ul.buttons label.disabling {
display: none;
}
(not actually run & tested, but the spirit is there)

jquery in yii: Detecting radiobutton losing check mark (checked state)

Given the following code (yes, i know it is perhaps irrelevant in yii, but I added the tag so I update the question with the actual generated html):
<script>
$(function(){
$('#widgetId-form input[name="valueType"]').change(function(){
if ($(this).is(":checked"))
{
console.log("habilitando "+$(this).data("class"));
$("."+$(this).data("class")).prop("disabled", false);
}
else
{
console.log("deshabilitando "+$(this).data("class"));
$("."+$(this).data("class")).prop("disabled", true);
}
}).change();
});
</script>
<div id="widgetId-dialog">
<form id="widgetId-form" action="/support/test" method="post">
<div>
<input id="valueType-single" value="single" data-class="singleValueField" checked="checked" type="radio" name="valueType" />
<label for="single">Valor simple</label>
<input size="6" class="singleValueField" type="text" value="" name="singleValue" id="singleValue" />
</div>
<div>
<input id="valueType-range" value="range" data-class="rangeValueField" type="radio" name="valueType" />
<label for="range">Rango (inicio:fin:intervalo)</label>
<input size="6" class="rangeValueField" type="text" value="" name="rangeValue_start" id="rangeValue_start" />:<input size="6" class="rangeValueField" type="text" value="" name="rangeValue_end" id="rangeValue_end" />:<input size="6" class="rangeValueField" type="text" value="" name="rangeValue_interval" id="rangeValue_interval" />
</div>
</form>
</div>
It doesn't trigger change() when a radio becomes unchecked. This implies: controls are disabled only on initialization (.ready()). change() is not triggered individually by controls losing the checkmark.
Question: how can I detect when a radio button loses the checkmark?
This is a conceptional problem. The radio buttons are seen somehow like one element. For closer information look at Why does jQuery .change() not fire on radio buttons deselected as a result of a namesake being selected?.
So the change-event will always only fire on the newly selected element and not on the deselected radios. You could fix your code like this:
$(function(){
$('#widgetId-form input[name="valueType"]').change(function(){
//could be also hardcoded :
$('input[name="' + $(this).attr("name") + '"]').each(function(){
if ($(this).is(":checked"))
{
console.log("habilitando "+$(this).data("class"));
$("."+$(this).data("class")).prop("disabled", false);
}
else
{
console.log("deshabilitando "+$(this).data("class"));
$("."+$(this).data("class")).prop("disabled", true);
}
});
});
$('#widgetId-form input[name="valueType"]:first').change();
});
You can check it at http://jsfiddle.net/jg6CC/. Greets another Luis M. ;)

Check Box Disablement On Page Reload Jscript

When I select the boxes, I want the text fields to become editable. At first it works but if I reload the page with the boxes checked, it will do the opposite of what it is supposed to do (i.e. after page is reloaded, when the boxes aren't checked, the text fields are editable; when checked, they become un-editable)
<table>
<tr>
<td>
<input type="checkbox" name="Download_Limit" value="download" class="checkme"/>Download Limit
<br/>
<input type="text" name="download" class="text required" id="Download_Input" size="3">
<label class="description" for="Expire">Downloads</label>
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="Time_Limit" value="time" class="checkme"/>Time Limit
<br/>
<input type="text" name="time" class="text required" id="Time_Input" size="3">
<label class="description" for="Expire">Hours</label>
</td>
</tr>
My Javascript
$('.checkme').attr('checked', false);
$('.checkme').click(function(){
if($('input[name='+ $(this).attr('value')+']').attr('disabled') == false){
$('input[name='+ $(this).attr('value')+']').attr('disabled', true);
}else{
$('input[name='+ $(this).attr('value')+']').attr('disabled', false);
}
});
Here is what I would do. First, setup all the default values that you want:
// Set default page values on load...
$('.checkme').prop('checked', false);
$('input[type="text"]').prop('disabled', true).val('');
// Then setup events...
$('.checkme').on('click', function () {
var $this = $(this);
if($('input[name='+ $this.val() +']').prop('disabled')){
$('input[name='+ $this.val()+']').prop('disabled', false);
} else {
$('input[name='+ $this.val()+']').prop('disabled', true);
}
});
We've changed a few things up here. Let me explain.
First, we've changed .attr('checked'...) and .attr('disabled'...) to use .prop() instead. checked and disabled are properties not attributes.
We're now attaching the event using .on(). This is just the method I prefer, however simply doing .click() will work as well.
We're saving off the element into a local variable $this first thing. This keeps jQuery from having to re-traverse the DOM multiple times within the same function.
I've simplified .attr('value') to the shorthand .val().
Lastly, we've simplified your if statement by removing the negative condition and allowing JavaScript to use the truthy/falsy conditionals.
Fiddle
A Few Other Notes:
I know it is a traditional method of page layout, but I highly discourage using tables to position elements. It is not the appropriate use of tables and results in a page layout that is not semantically correct. Check out the <div> and <span> elements to layout your code and try styling it to appear the way you want with CSS.
Also, it appears you are formatting your HTML in the XHTML syntax. That is perfectly fine, however I recommend that you be consistent when closing tags. Two of your <input /> element tags are not closed properly.
// This...
<input type="text" name="download" class="text required" id="Download_Input" size="3">
// Should be this...
<input type="text" name="download" class="text required" id="Download_Input" size="3" />
// And this...
<input type="text" name="time" class="text required" id="Time_Input" size="3">
// Should be this...
<input type="text" name="time" class="text required" id="Time_Input" size="3" />
Make sure you are consistent in your methods of markup. Inconsistencies such as this will result in an invalid markup.
Finally, I do not believe that you can have <tr> elements nested directly inside of a <table> element. I believe they have to be inside of a <thead>, <tbody> or <tfoot> element. Again, leaving out elements such as these results in invalid markup.
Try this DEMO . I think it's more elegant.
$('.checkme').click(function() {
var input = $(this).closest('td').find('input[type="text"]');
if (input.is(':disabled')){
input.attr('disabled', false);
}else{
input.attr('disabled', true);
}
});
Also, your input type="text" mark up should be disabled as follows:
<input type="text" disabled="disabled" name="time" class="text required" id="Time_Input" size="3" />

CSS is not changing through calling JS in HTML

my JS code is bellow:
// JavaScript Document
function bubbleColor() {
if($("#Checkbox1").is(":checked") && $("#Checkbox2").is(":checked"))
{
$(".bubble").css("background-color", "red");
}
}
var el = document.getElementById(".bubble");
el.onclick = bubbleColor;
And my targeted HTML:
<div id="circle" class="bubble">
<p class="circle_text">
#6
</p>
</div>
<br/><br/>
<input type="checkbox" value="1" id="Checkbox1" name="Checkbox1"/> Answer one <br/>
<input type="checkbox" value="1" id="Checkbox2" name="Checkbox2"/> Answer two <br/>
<input type="checkbox" value="1" id="Checkbox3" name="a3"/> Answer three <br/>
Desired output:
When somebody checks [selects] both the Checkbox1 and Checkbox2, the #6 background should be Red color.
Problem:
The code does not seem to work.
Any help please?
Im assuming you are using jquery (as you are changing css with jquery)
The behaviour you describe in your question implies that changing the checkbox should trigger a verification, so why do you attach the bubbleColor function to clicking on the .bubble div?
Try something like this:
// Alternatively you could use a class to select the checkboxes
$("input[type='checkbox']").change(bubbleColor);
Ofcourse ideally you should change your function to remove the red color if you uncheck the boxes:
function bubbleColor() {
if ($("#Checkbox1").is(":checked") && $("#Checkbox2").is(":checked")) {
$(".bubble").css("background-color", "red");
} else {
$(".bubble").css("background-color", "transparent");
}
}
Fiddle: http://jsfiddle.net/sQCcF/2/
Edit:
If what you want is to ensure user only selects 1 option then you should use radio buttons instead of checkboxes, as that is the default behavior:
<input type="radio" name="inputname" value="1"/>
<input type="radio" name="inputname" value="2"/>
<input type="radio" name="inputname" value="3"/>
The name has to be the same for the inputs, but each one will have a different value, selecting one will automatically unselect the other.
Problem is at
var el = document.getElementById(".bubble");
You are selecting element with ID of .bubble (bubble is a class)
Change it to and check :
var el = document.getElementById("circle");
First of all you attach an event handler for the click event on div with class "bubble".
Then, you use document.getElementById method to select an element but you use as argument the class of that element, not the ID.
For this to work you need to attach the click event handler to checkbox elements.
Something like this:
$('input[type="checkbox"]').click(function() {
bubbleColor();
});
Replace var el = document.getElementById(".bubble");
el.onclick = bubbleColor;
with
$(".bubble").click(bubbleColor) ;
should work.
Try this code
HTML
<div id="circle" class="bubble">
<p class="circle_text">
#6
</p>
</div>
<br/><br/>
<input type="checkbox" value="1" id="Checkbox1" name="Checkbox1" class="chBox"/> Answer one <br/>
<input type="checkbox" value="1" id="Checkbox2" name="Checkbox2" class="chBox" /> Answer two <br/>
<input type="checkbox" value="1" id="Checkbox3" name="a3" class="chBox" /> Answer three <br/>
JQUERY
$(document).ready(function(){
// you can use '.chBox class or input[type='checkbox']'
$('.chBox').bind('click', function(){
if($("#Checkbox1").is(":checked") && $("#Checkbox2").is(":checked"))
{
$(".bubble").css("background-color", "red");
}else{
$(".bubble").css("background-color", "#fff");
}
});
});

Categories

Resources