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

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

Related

javascript/html - change color of checkbox text when box if checked by user

I'm trying to change the color of my checkbox text label when the user checks the box and clicks the toggle button. I looked up other examples and tried to make my own solution below but it doesn't work when I check the boxes I want to check and click the button. I was wondering why?
function addItem() {
var input = document.getElementById("textbox");
var wrapper = document.getElementById("checklist_items");
if (input.value.trim() != "") {
var new_element = document.createElement("DIV");
new_element.innerHTML = '<input type="checkbox"> ' + input.value;
wrapper.appendChild(new_element);
document.getElementById('textbox').value = '';
} else {
alert("You must enter at least 1 character.");
}
}
function toggleItem() {
var chkbx = document.querySelectorAll('checklist_items');
if (chkbx.checked) {
document.getElementById('checklist_items').style.color = "red";
} else {
document.getElementById("checklist_items").style.backgroundColor = "transparent";
}
}
<html>
<head>
<title>Checklist</title>
</head>
<body>
<div><h1>My to-do list</h1></div><br />
<div id ="myCheckList">Enter an item:</div>
<div>Type something: <input type="text" id="textbox"></input></div>
<input type="button" id="addBut" value = "Add item" onclick="addItem()"/>
<input type="button" id="toggleBut" value = "Toggle highlight" onclick="toggleItem()"/>
<script src="addHandler.js"></script>
<div id="checklist_items"></div>
</body>
</html>
How my program works is the user enters a bunch of text in the textbox and clicks the add button, which creates a checkbox for their input. I want the name of their input beside the checkbox to change colors when I check it and click the toggle button.
var chkbx = document.querySelectorAll('checklist_items') needs to be var chkbx = document.querySelectorAll('#checklist_items') or var chkbx = document.getElementById('checklist_items').
querySelectorAll takes CSS selectors as arguments, which are either html elements or class or id names with the corresponding prefix. IDs have the prefix # and classes have the prefix .
Using JQuery:
$(".your_checkbox_class").change(function () {
if ($(this).is(':checked')) {
$(this).css("background-color","your_color_here");
}
};
EDIT:
You should also give this checkbox class or id
EDIT 2:
document.getElementById('checklist_items').style.color = "red";
means that font color will change but checkbox has no text

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');

If an input has a value, specific radio button should be checked

I want to check if an input (name="companyname") has a value and if so, it should check a radio button (id="Zakelijk"). If it does not have any value, it should check the other radio button (id="Particulier").
See my current code:
<script type="text/javascript">
function ShowHideDiv() {
var chkYes = document.getElementById("Zakelijk");
var dvPassport1 = document.getElementById("checkzakelijk");
var dvPassport2 = document.getElementById("checkzakelijk1");
var dvPassport3 = document.getElementById("checkzakelijk2");
var display = chkYes.checked ? "block" : "none";
dvPassport1.style.display = display;
dvPassport2.style.display = display;
dvPassport3.style.display = display;
}
</script>
<div class="col-md-12 check-business">
<div class="form-group form-group-xl">
<label for="Particulier"><input type="radio" id="Particulier"checked="checked" name="checkzakelijk" onclick="ShowHideDiv()" />Particulier</label>
<label for="Zakelijk"><input type="radio" id="Zakelijk" name="checkzakelijk" onclick="ShowHideDiv()" />Bedrijf</label>
</div>
</div>
<div class="col-md-12" id="checkzakelijk" style="display:none;">
<div class="form-group">
<label for="inputCompanyName" class="control-label">{$LANG.clientareacompanyname}</label>
<input type="text" name="companyname" id="inputCompanyName" value="{$clientcompanyname}"{if in_array('companyname', $uneditablefields)} disabled="disabled"{/if} class="form-control" />
</div>
</div>
There are other ways, but this should get you going:
$(function() {
if (($("#inputCompanyName").val() || "") != "")
{
$("#Zakelijk").prop("checked", true)
} else {
$("#Particulier").prop("checked", true)
}
});
This is based on your html where the input name='companyname' also has id 'inputCompanyName' and will clear the other radio because they have the same name=
Edit Working jsfiddle: https://jsfiddle.net/76x42os0/4
change input value in the code box (top left) and click run.
Update: Updated the fiddle to the indicated jquery version 3.1.0 and found the newer version of jquery needs id= to match #, while before it matched on name=
If you want to check it when the input is changed you can do
$("input[name='companyname']").change(function(){
var hasValue = $(this).val() === "";
$("#Zakelijk").prop("checked", hasValue);
$("#Particulier").prop("checked", !hasValue);
})
you can optimize the code, but this is more readable.
In case you need the solution in Javascript
if(document.getElementById("inputCompanyName").value !== ""){
document.getElementById("Zakelijk").checked = true;
document.getElementById("Particulier").checked = false;
}
else{
document.getElementById("Particulier").checked = true;
document.getElementById("Zakelijk").checked = false;
}
Here's a working example of what you're after (albeit without your HTML ids/layout in mind, but you can simply change the IDs within).
$("#text-box").on('change', function(){
if($(this).val() != ""){
$('#rd1').prop("checked", true)
}else{
$('#rd2').prop("checked", true)
}
});
https://jsfiddle.net/bm18hmLa/3/
It hooks into the changed event, so it would occur every time the text-box value has been changed.
After thought:
Changing
$("#text-box").on('change', function(){
to
$("#text-box").on('input', function(){
makes it a little "nicer" in terms of responsiveness.
https://jsfiddle.net/bm18hmLa/5/
and here's a version with your ID names too.
https://jsfiddle.net/bm18hmLa/6/

How do I get javascript to run more than once?

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>

Filtering data using textbox and checkboxes simultaneously with jQuery?

I wanted to filter my attractions stored in paragraphs by following using jQuery with:
Textbox, where I put substring the attraction starts with
Checkboxes, which should show only attractions with certain categories. When you tick multiple boxes, it should show items which have any of listed categories.
I have done that, but these filters don't work simultaneously. One filter overrides results of another, because they work on whole list and invoke show() and hide() on whole list separately.
Html:
<h3>Search:</h3>
<div>
<input type="text" id="search-box" class="form-control" placeholder="Search">
</div>
<h3>Categories:</h3>
<div id="options" class="checkbox">
<label>
<input type="checkbox" rel="club">Club</label>
<label>
<input type="checkbox" rel="other">Other</label>
</div>
<div id="attractions" style="font-size: x-large">
<p class="club" style="display: block;">Cocomo
</p>
<p class="club" style="display: block;">Princess
</p>
<p class="club" style="display: block;">Le Secret
</p>
<p class="other" style="display: block;">Wyspa piasek
</p>
<p class="other" style="display: block;">C# Operational Base
</p>
</div>
Javascript:
$('div.checkbox').delegate('input[type=checkbox]', 'change', function() {
var $lis = $('#attractions > p').hide();
var $checked = $('input:checked');
if ($checked.length) {
($checked).each(function() {
$lis.filter('.' + $(this).attr('rel')).show();
}).find('input:checkbox').change();
} else {
$lis.show();
}
});
$('#search-box').keyup(function() {
var valThis = this.value.toLowerCase();
$('div#attractions > p').each(function() {
var text = $(this).text(),
textL = text.toLowerCase();
(textL.indexOf(valThis) === 0) ? $(this).show(): $(this).hide();
});
});
I suppose there must be some way to achieve simultaneous results. I'd be grateful for showing me right direction, maybe even suggesting to drop this code and use some filter plug-in?
I think this solves your problem in a clean and clear way. Explanations are in the comments.
//Triger filterAttractions when something changes.
$("#search-box, #options input").change(filterAttractions);
$("#search-box").keyup(filterAttractions);
function filterAttractions() {
//Get the text of the textbox.
var searchtext = $("#search-box").val();
//Get an array with the rel attributes of the checked checkboxes.
var categories = $("#options input:checked").map(function() {
return $(this).attr("rel");
}).get();
//Perform this once for every attraction.
$("#attractions p").each(function() {
var attraction = $(this);
//See if it has any of the checked categories.
var category = false;
for(i=0; i<categories.length; i++)
if(attraction.hasClass(categories[i]))
category = true;
//See if it starts with the right text.
var text = attraction.text().indexOf(searchtext) === 0
//Show or hide the attraction depending on the result.
attraction.toggle(category && text);
});
}
Fiddle.

Categories

Resources