How do I get javascript to run more than once? - javascript

EDIT: here is a jsfiddle with all the code. https://jsfiddle.net/ypbd3fgf/2/
I'm using this simple code to add a class to a parent element in order to make the text on a selected radio button turn bold. However, it only works on page load. If you select different radio buttons, the newly selected buttons don't turn bold. I think it's because the code only runs on page load. How do I get it to update when a new radio button or checkout is selected? Thanks!
<script type="text/javascript">
$(function() {
$(".ez-selected").closest('.row').addClass("bold");
});
</script>
The is the HTML. The .ez-selected class is added to the .ez-radio div when a radio button is selected. And then removed when a different radio button is selected. When the .ez-selected class is added, the .bold class needs to be added to the .row div. When the .ez-selected class is removed the .bold class needs to be removed from the .row div.
<div class="row (bold)">
<input name="TXT870" type="hidden" value="Option 1">
<div class="col-xs-2">
<div class="ez-radio (ez-selected)">
<input class="clearBorder ez-hide" name="CAG3" onclick=
"javascript:document.additem.CAG3QF1.value='1'; CheckPreValue(this, 2, 0);"
type="radio" value="870_625_0_625">
</div><input name="CAG3QF1" type="hidden" value="0">
</div>
<div class="col-xs-7">
<span>Option 1</span> <input class="transparentField" name=
"CAG3TX1" readonly size="14" type="text" value=" - Add $5.00">
</div>
</div>
EDIT: I added the JS code below that adds and removes the .ez-selected class. This new JS that I'm trying to make will simply be adding and removing the bold class when the .ez-selected class is added and removed by this other JS code below.
(function($) {
$.fn.ezMark = function(options) {
options = options || {};
var defaultOpt = {
checkboxCls: options.checkboxCls || 'ez-checkbox',
radioCls: options.radioCls || 'ez-radio',
checkedCls: options.checkedCls || 'ez-checked',
selectedCls: options.selectedCls || 'ez-selected',
hideCls: 'ez-hide'
};
return this.each(function() {
var $this = $(this);
var wrapTag = $this.attr('type') == 'checkbox' ?
'<div class="' + defaultOpt.checkboxCls + '">' :
'<div class="' + defaultOpt.radioCls + '">';
if ($this.attr('type') == 'checkbox') {
$this.addClass(defaultOpt.hideCls).wrap(wrapTag)
.change(function() {
if ($(this).is(':checked')) {
$(this).parent().addClass(
defaultOpt.checkedCls);
} else {
$(this).parent().removeClass(
defaultOpt.checkedCls);
}
});
if ($this.is(':checked')) {
$this.parent().addClass(defaultOpt.checkedCls);
}
} else if ($this.attr('type') == 'radio') {
$this.addClass(defaultOpt.hideCls).wrap(wrapTag)
.change(function() {
$('input[name="' + $(this).attr(
'name') + '"]').each(
function() {
if ($(this).is(
':checked')) {
$(this).parent().addClass(
defaultOpt.selectedCls
);
} else {
$(this).parent().removeClass(
defaultOpt.selectedCls
);
}
});
});
if ($this.is(':checked')) {
$this.parent().addClass(defaultOpt.selectedCls);
}
}
});
}
})(jQuery);

Edit:
The new code switches to the function(){...} format and looks for a click event on an input element then checks if its a radio button and that the parent is .row then it adds the bold and ez-selected classes to the radio button and removes them from other radios.
$("input").click(function() {
if($(this).attr('type') == 'radio' && $(this).parents('.row').length > 0){
$("input").closest('.row').removeClass('bold ez-selected');
$(this).addClass('bold ez-selected');
}
})

your code should look somewhat like this:
<script type="text/javascript">
$(function() {
$("input[type='radio']").click(function(e) {
var targ = e.target
$("div[class='row'][class='bold']).removeClass('bold');
$(targ).parents('div[class="row"]').addClass('bold');
})
$(".ez-selected").closest('.row').addClass("bold");
});
</script>

Related

Reveal additional info based on two (out of three) checkboxes JavaScript

I'm new at Javascript and I'm trying to reveal additional info only if any 2 out of 3 checkboxes are checked.
Here is my code so far (I'm trying to enter my code in the question but It's not working, sorry. I also may have made it more complicated then necessary, sorry again). I did place my code in the Demo.
<script>
var checkboxes;
window.addEvent('domready', function() {
var i, checkbox, textarea, div, textbox;
checkboxes = {};
// link the checkboxes and textarea ids here
checkboxes['checkbox_1'] = 'textarea_1';
checkboxes['checkbox_2'] = 'textarea_2';
checkboxes['checkbox_3'] = 'textarea_3';
for ( i in checkboxes ) {
checkbox = $(i);
textbox = $(checkboxes[i]);
div = $(textbox.id + '_container_div');
div.dissolve();
showHide(i);
addEventToCheckbox(checkbox);
}
function addEventToCheckbox(checkbox) {
checkbox.addEvent('click', function(event) {
showHide(event.target.id);
});
}
});
function showHide(id) {
var checkbox, textarea, div;
if(typeof id == 'undefined') {
return;
}
checkbox = $(id);
textarea = checkboxes[id];
div = $(textarea + '_container_div');
textarea = $(textarea);
if(checkbox.checked) {
div.setStyle('display', 'block');
//div.reveal();
div.setStyle('display', 'block');
textarea.disabled = false;
} else {
div.setStyle('display', 'none');
//div.dissolve();
textarea.value = '';
textarea.disabled = true;
}
}
<label for="choice-positive">
<script type="text/javascript">
function validate(f){
f = f.elements;
for (var c = 0, i = f.length - 1; i > -1; --i)
if (f[i].name && /^colors\[\d+\]$/.test(f[i].name) && f[i].checked) ++c;
return c <= 1;
};
</script>
<label>
<h4><div style="text-align: left"><font color="black">
<input type="checkbox" name="colors[2]" value="address" id="address">Full Address
<br>
<label>
<input type="checkbox" name="colors[3]" value="phone" id="phone">Phone Number <br>
<label>
<input type="checkbox" name="colors[4]" value="account" id="account">Account Number <br>
</form>
<div class="reveal-if-active">
<h2><p style = "text-decoration:underline;"><font color="green">Receive the 2 following
pieces of info:</h2></p>
</style>
Sorry i wasn't able to exactly use the code you provided but tried to change just enough to get it working.
I've uploaded a possible solution to JSFiddle - you essentially can add event listeners to the checkboxes that recheck when clicked how many are selected and show/hide via removing/adding a class e.g. additionalContactBox.classList.remove('reveal-if-active');

How would I find the label's child? (HTML + JS)

How would I make JS find the child with the class of "money"? I have it coded so that it will find the radio button when clicked. Once it's clicked it will return that radio button and id. But I also need to find the "money" class.
HTML:
<div class="col-sm-4 col-md-2">
<input name="STORAGE" type="radio" id="STORAGE2">
<label class="radio" for="STORAGE2">
<center>
<img src="../images/Parts/Western_Digital_Caviar_Blue_320GB.png" class="comp-img"><br><br>
<p>500GB Western Digital WD5000AAKX 3.5" 7200RPM HDD</p>
<p class="money">+$55</p> <!--THIS IS THE CLASS I AM TRYING TO GET-->
</center>
</label>
</div>
JS:
$(function(){
var cpu = "";
//Controling radio buttons
$('radio').on('click'), function(){
var clickedID = $(this).attr("id");
if (clickedID.substring(1,3) == "CPU") {
if (cpu == "") {
cpu = clickedID;
} else {
}
}
}
});
if your label's for attribute is the value of the radio ID then you can do like this
var el = $('label[for='+clickedID +']').find('.money');
use the jQuery find function $(this).find(".money");
Your syntax is off a little bit, but this should work:
EDIT:
As #empiric has noted, .money is not a child of $('radio'), it is a child $('.radio'), which is not the intended click target.
$('.radio').on('click', function(){
var $this = $(this);
var clickedID = $this.attr("for");
// Child .money element (put this wherever you need it)
var childMoneyEl = $this.find('.money')
if (clickedID.substring(1,3) == "CPU") {
if (cpu == "") {
cpu = clickedID;
}else{
}
}
});

Kendo Listview, added checkboxes, added a select all, will check and uncheck all once, will not check all again.

I would like some help with this. I have a Kendo Listview:
<form id="frmChk">
#(Html.Kendo().ListView<thieme_ws3.Models.QaTestModel>(Model)
.Name("testList")
.TagName("fieldset")
.HtmlAttributes(new { #class = "panel panel-primary panel-body" })
.ClientTemplateId("template")
)
<br />
</form>
Where I have added checkboxes to the information brought in:
<script type="text/x-kendo-tmpl" id="template">
<div class="col-md-5">
#Html.CheckBox("cb_#:Id#", new { #class = ".item", id = "cb_#:Id#" }) #=Name#
</div>
</script>
I have added a select all checkbox:
<label id="checkAll" class="checkbox">
<input type="checkbox" id="all" name="all" /> Select all
</label>
And added this to fire it:
$('#all').on('click', function (e) {
//alert("I'm clicked!" + this.checked);
var testList = $("#testList").data("kendoListView");
var dataItems = testList.dataItems();
//do thought to wrap the loop in a do while, caused the browser to stop
{
for (i = 0; i <= dataItems.length - 1; i++) {
//alert(dataItems[i].id);
var cb = $("#cb_" + dataItems[i].Id);
if (this.checked) {
cb.attr("checked", "checked");
}
else {
(cb.removeAttr("checked"));
}
}
}
})
It will work once, checking all boxes and unchecking all boxes but when I check the select all again, it will not select the others. I am certain it is something small I am overlooking, please help.
Try this instead (assuming the checkboxes are descendants of #testlist):
$('#all').on('change', function (e) {
var isChecked = $(this).prop('checked');
$("#testList").find('input[type="checkbox"]').prop('checked', isChecked);
})

jquery enable disable link based on checkbox

I need to disable/enable "a.href" links based on checkboxes being checked. I have a list of checkboxes (2 columns). When at least one checkbox in a column "install" is checked, "Install" link should be enabled, otherwise disabled. When at least one checkbox is checked in column "Remove", a link with the same class name should be enabled, otherwise disabled.
I've tried with this but not sure if this is correct, it doesn't work:
function refleshCheckboxes() {
if ($("input:checked").length > 0) {
$("input:checked").each(function(index, e) {
var css = $(e).attr('class').split(' ').slice(-1);
$("div.markActions a").each(function (index, e) {
$(e).removeClass("disablelink").hasClass(css);
});
});
}
else {
$("div.markActions a").addClass("disablelink");
}
}
$("div.markActions a")
- this is where a.href links are (inside this div)
checkboxes have the same class name as the a.href links. So I would like to get the class name of checkbox and match that class with the class of the a.href link.
Checkbox:
<input type="checkbox" value="2" class="checkbox install">
Link:
<a class="iconDiskPlus install disablelink" href="#">Install</a>
I figured it out:
function refleshCheckboxes() {
if ($("input.checkbox:checked").length > 0) {
var arr = new Array(".install", ".uninstalled", ".enabled", ".disabled", ".download", ".remove");
for (i = 0; i < arr.length; i++) {
if ($("input.checkbox:checked").is(arr[i])) {
$(".markActions a" + arr[i]).removeClass("disablelink");
} else {
$(".markActions a" + arr[i]).addClass("disablelink");
}
};
}
else {
$("div.markActions a").addClass("disablelink");
}
}
Try the below one.
​
$(function(){
$('input.install').click(function(){
var install_link = $('a.install');
if($('input.install:checked').length !=0){
install_link.addClass('enablelink').text('install enabled');
}
else{
install_link.addClass('disablelink').text('install disabled');
}
});
});​
Check out js fiddle for demo
You can set an onclick event to a checkbox like this:
<input id="someId" type="checkbox" value="2" class="checkbox install" onclick="myFunction()">
in your js file define a function:
function myFunction(){
var checkBox = document.getElementById("someId");
if(checkBox.checked == true){
//you have to give an id attribute to the object
// which you want to hide
var hideIt = document.getElementById("id");
hideIt.style.visibility = "none";
}
}

How to hide the parent of an unchecked checkbox?

I have a set of random/dynamic generated div checkboxes:
<div>A1 <input type='checkbox' name='A[]' value='A1'> </div>
<div>A2 <input type='checkbox' name='A[]' value='A2'> </div>
<div>A3 <input type='checkbox' name='A[]' value='A3'> </div>
<div>B1 <input type='checkbox' name='B[]' value='B1'> </div>
<div>B2 <input type='checkbox' name='B[]' value='B2'> </div>
<div>C1 <input type='checkbox' name='C[]' value='C1'> </div>
What I am trying to do is when the user:
checks any A then the others will hide (entire div) but all A will still show.
unchecks a checkbox, then all A, B, C will show again.
This is because I am preventing the user from checking a mix of options.
PS:
You can provide a solution that might need me to modify the generated output of checkboxes.
try this fiddle
$("input[type=checkbox]").on("change", function() {
var thisName = $(this).attr("name");
if($(this).is(':checked')){
$(':checkbox').parent().hide();
$('input:checkbox[name|="'+thisName+'"]').parent().show();
} else {
$(':checkbox').parent().show();
}
});​
Try this one,
$('input:checkbox').click(function(){
if($(this).attr('checked') == 'checked'){
$('input:checkbox').parent('div').hide();
$('input:checkbox[name="'+$(this).attr('name')+'"]').parent('div').show();
}else{
if(!$('input:checkbox[checked="checked"]').length){
$('input:checkbox').parent('div').show();
}
}
})
​
Demo: http://jsfiddle.net/muthkum/uRd3e/3/
You can use some JQuery traversing to hide the non-matching elements:
// add the event handler
$("input[type=checkbox]").on("change", function() {
// get whether checked or unchecked
var checked = $(this).prop("checked") === true;
// get the name of the clicked element (eg, "A[]")
var thisName = $(this).prop("name");
// get the name of the clicked element (eg, "A[]")
var thisName = $(this).prop("name");
// get the grandparent element
$(this).parent().parent()
// get all the checkboxes
.find("input[type=checkbox]")
// filter to only the ones that don't match the current name
.filter(function(i, e) { return e.name != thisName; })
// hide or display them
.css("display", checked ? "none" : "");
});
you can simple do it like this
$('input[type=checkbox]').change(function () {
if ($(this).attr('checked')) {
var Name = $(this).prop("name");
$('div').filter(function(){
return $(this).find('input[type=checkbox]').prop("name") != Name;
}).hide();
}
else
{
$('input[type=checkbox]').attr('checked',false);
$('input[type=checkbox]').parent('div').show();
}
});​
Live Demo
Try code bellow:
$(":checkbox").click(function() {
var identifier = $(this).val().substring(0, 1);
$("input[type='checkbox']").each(function() {
if ($(this).val().indexOf(identifier) != -1) {
$(this).parent().show();
} else {
$(this).parent().hide();
}
});
if ($("input:checked").length == 0) {
$("input[type='checkbox']").parent().show();
}
});
You can try on jsFiddle
This will hide all other checkbox types when FIRST of a type is checked and show all the other checkbox types when ALL of the checked box type are unchecked:
$("input:checkbox").on("change", function() {
// get the name attribute
var nameAttr = $(this).prop("name");
// check how many checkbox inputs of that name attribute are checked
var checkedLength = $("input:checkbox[name=\"" + nameAttr + "\"]:checked").length;
// if 0, display other checkbox inputs, else if 1 hide all of the rest
if(checkedLength == 0) {
$("input:checkbox[name!=\"" + nameAttr + "\"]").parent().show();
}else if(checkedLength == 1) {
$("input:checkbox[name!=\"" + nameAttr + "\"]").parent().hide();
}
});
Overwhelmed by choice! Here's a plain JS version that just disables members of the non–selected groups.
I think that's better than hiding them so users can see the other options after they've selected one. Otherwise, to see the other options again, they must deselect all checkboxes in the group.
Note that div is a parent of the inputs, the listener passes a reference to the element and the related event object, modify as required.
<script>
function doStuff(div, evt) {
var checked, el, group, j, inputs, name, re;
var t = evt.target || evt.srcElement;
if (t.nodeName && t.nodeName.toLowerCase() == 'input' && t.type == 'checkbox') {
inputs = div.getElementsByTagName('input');
name = t.name;
// Set checked to true if any input with this name is checked
group = document.getElementsByName(name);
j = group.length;
while (j-- && !checked) {
checked = group[j].checked;
}
// Loop over inputs, hide or show depending on tests
for (var i=0, iLen=inputs.length; i<iLen; i++) {
el = inputs[i];
// If name doesn't match, disable
el.disabled = checked? (el.name != name) : false;
}
}
}
</script>
<div onclick="doStuff(this, event)">
<div>A1 <input type='checkbox' name='A[]' value='A1'></div>
<div>A2 <input type='checkbox' name='A[]' value='A2'></div>
<div>A3 <input type='checkbox' name='A[]' value='A3'></div>
<div>B1 <input type='checkbox' name='B[]' value='B1'></div>
<div>B2 <input type='checkbox' name='B[]' value='B2'></div>
<div>C1 <input type='checkbox' name='C[]' value='C1'></div>
</div>
Thanks guys, especially dbaseman (get me ideal) :
ok, Here is my code after referring from you all.
$("input[type=checkbox]").on("click", function() {
var sta = $(this).is(":checked"); sta=(sta==true?1:0);
if(sta==1){
var thisName = $(this).prop("name"); thisName=thisName.replace("[]","");
$("div input[type=checkbox]:not([name^=" + thisName + "])").parent().hide();
}else{
var num = $("[type=checkbox]:checked").length;
if(num==0){
$("div input[type=checkbox]").parent().show();
}
}
});
so far code able is performing as what i need.
Ps: i am still weak on jquery travelling part
Ps: Edited on re-opening all checkboxes part
Thanks once again!

Categories

Resources