Explain something.logic in javascript? - javascript

Currently, I am quite new to javascript and I came across one of the javascript keyword (.logic). I tried to googled this keyword, but I couldn't find the answer to it. Can anyone please explain what is the meaning of it? When, why should we use it? It seem like it is create the object in a logical order or something.
Here is the snippet of the code:
var checkboxes = slice(document.querySelectorAll('.checkbox'));
for (var checkbox of checkboxes)
checkbox.logic = new Checkbox(checkbox);
***Note: I tried to learn ARIA right now. that is why I don't use the native checkbox.*
Here is the code for the HTML part:
<div class="demo">
<h2>Custom checkboxes</h2>
<div tabindex="0" class="checkbox" checked>
Tim-Tams
</div>
<div tabindex="0" class="checkbox">
Mint slices
</div>
</div>
Here is the javascript code:
function Checkbox(el) {
this.el = el;
this.el.addEventListener('keydown', this.handleKeyDown.bind(this));
this.el.addEventListener('click', this.toggle.bind(this));
// Initialize role and aria-checked state.
this.el.setAttribute('role', 'checkbox');
if (this.el.hasAttribute('checked')) {
this.el.setAttribute('aria-checked', 'true');
} else {
this.el.setAttribute('aria-checked', 'false');
}
}
Checkbox.prototype.handleKeyDown = function(e) {
switch(e.keyCode) {
case VK_ENTER:
case VK_SPACE: {
this.toggle();
break;
}
}
};
Checkbox.prototype.toggle = function() {
if (this.el.hasAttribute('checked')) {
this.el.removeAttribute('checked');
// Keep checked attribute and aria-checked in sync.
this.el.setAttribute('aria-checked', 'false');
} else {
this.el.setAttribute('checked', '');
// Keep checked attribute and aria-checked in sync.
this.el.setAttribute('aria-checked', 'true');
}
};
//HERE IS THE QUESTION PART================================
var checkboxes = slice(document.querySelectorAll('.checkbox'));
for (var checkbox of checkboxes)
checkbox.logic = new Checkbox(checkbox);

So, I'm pretty junior at prototypal inheritance, so anyone please chime in to verify/clarify my answer.
From what I understand, .logic is not a native JavaScript function or method, rather it is adding a property to an object as part of prototypal inheritance.
What this snippet of code is doing...
var checkboxes = slice(document.querySelectorAll('.checkbox'));
for (var checkbox of checkboxes)
checkbox.logic = new Checkbox(checkbox);
...is turning the custom html checkboxes into objects objects using the .slice function (these are array-like, so they can turn into objects).
In short, checkbox.logic is similar to....
var checkbox = {logic: "doing stuff with the Checkbox class that was called"};
Not a perfect metaphor but I hope that clarifies this.

Related

Using checkboxes to update UI in realtime

I'm currently in the process of trying to develop a smarter UI for one of my clients. However the only code I can use to develop this 'feature', is pure JS. I have no access to the source HTML or CSS files the only access I have is the ability to inject JavaScript through an external .js file.
I'm not too familiar with JS, but I can work my way around a basic script or two.
Scenario
What we're doing is allowing users to edit PDF Templates online using a software called Core Create. The UI accessed through the browser is quite cluttered and I would like to provide an option to hide and show UI elements <textareas>/<inputs> through the use of checkboxes.
Here is a very basic JS Fiddle that I have built with the
intention of hiding and displaying UI.
The page in question
Above is a screen grab of the page I am working with, on the left you can see the UI and its composition on the right within the 'Inspect Element' tool.
I have come to the conclusion that I need to iterate through the highlighted selection and link them accordingly with seven checkboxes. The result would then be a selection of checkboxes that would hide / display the correct UI element.
The Caveat
In realizing I cannot edit or introduce new HTML I noticed the lack of on-click attributes. So I'm a bit lost on how to invoke the JavaScript I will eventually build.
My Question
With my limited knowledge of JS I don't know how I would iterate though div elements editoraccvar - editoraccvar6 picking out the ones I need to manipulate.
Due to the lack of ID's / Names (I assume it would have to be done using Parent/Child rules somehow, as the classes are widley used by the rest of the UI. I would appreciate a small example demonstrating how I could achieve this, so I can learn from it.
I should clarify, I have already added the checkboxes to the page, I just need to build the JS link between the Checkbox and the UI element I'm attempting to target. You can find all attributes linking to these checkboxes included in the JS Fiddle.
EDIT // A Working Simplified Example;
Due to some confusion I have 'frankensteined' some code together to show the final result I am after. A working example of sorts. The actual result needs to target 7 Checkboxes and 7 Divisions. I'll list thier common properties below.
// This script is already in place and constructed by the system.
// Written inside script tags and located straight after 'editopt1'.
// $(document).ready(function() {
// $('#checkboxopt1').click(function() {
// if ($('#checkboxopt1').val() == 'true') {
// $('#opt1').val('false');
// $('#checkboxopt1').val('false');
// $('#checkboxopt1').prop('checked', false);
// $('#previewrefresh').trigger('click');
// } else {
// $('#opt1').val('true');
// $('#checkboxopt1').val('true');
// $('#checkboxopt1').prop('checked', true);
// $('#previewrefresh').trigger('click');
// };
// });
// });
function exFunction() {
// Check the function is called
console.log("200 : OK");
// grab all elements with the class, .field-summernote
var uiblocks = document.querySelectorAll('.field-summernote');
for (var i = 0; i < uiblocks.length; i++) {
var current = uiblocks[i];
if (current.className.indexOf('editoraccvar') < 0) //not found: -1
return;
// check elements in the array
console.log(current);
// control the elemets in the array.
if (document.getElementById('checkboxopt1').checked) {
uiblocks[0].style.display = 'block'; // display the element
} else {
uiblocks[0].style.display = 'none'; // hide the element
}
}
};
// Trigger the collection the check, and the control.
var x = document.getElementById("checkboxopt1");
x.addEventListener("click", function() {
console.log("Opt");
exFunction();
});
.editoraccvar1 {
width: 300px;
background: #0ff;
padding: .5em;
}
.editoropt1 {
width: 300px;
background: #ff0;
padding: .5em;
}
textarea {
display: block;
width: 95%;
resize: none;
padding: .5em;
}
<!-- I'm trying to hide & show this entire division... -->
<div class="seq-box-form-field field-summernote editoraccvar1 ">
<label for="accvar1">Ground Floor Info</label>
<div class="clearfix"></div>
<textarea id="richaccvar1" name="richaccvar1" class="summernote"></textarea>
<input type="hidden" name="accvar1" id="accvar1" value="" />
</div>
<!-- Using only what the system has supplied. -->
<div class="seq-box-form-field editoropt1 ">
<label for="opt1"><span style="padding-right: 10px; vertical-align: 1px;">Ground Floor </span>
<input type="checkbox" name="checkboxopt1" id="checkboxopt1" value="true" checked="true" />
<input type="hidden" name="opt1" id="opt1" value="true" />
</label>
</div>
Divisions <div class=""></div>
* editoraccvar,
editoraccvar1,
editoraccvar2,
editoraccvar3,
editoraccvar4,
editoraccvar5,
editoraccvar6*
Checkboxes <input id=""></input>
* checkboxopt,
checkboxopt1,
checkboxopt2,
checkboxopt3,
checkboxopt4,
checkboxopt5,
checkboxopt6,*
As far as I can see, your problem boils down to link checkboxes (that seem to have been generated in some way) to "division" parts of your html that you want to hide. Plus, you have to inject javascript code in the page (so I guess the less code the better).
One approach could be as follows:
// Wrap the code in an anonymus function, to avoid clustering the global space.
(function (domElements) {
// This is the callback that will fire when a checkbox is clicked.
function clickCallback() {
// the context of this callback is the DOM element thus we can access its attributes through this.
// extract the checkNumber of the class of the element. This number is the link to the division that we want to hide/show.
var checkNumber = ((/ editoropt(\d*) /).exec(this.className))[1],
checkBox = document.getElementById('checkboxopt' + checkNumber),
division = document.querySelectorAll('.editoraccvar' + checkNumber)[0];
// Hide/show division, update checkBox state.
toggleElements(division, checkBox, window.getComputedStyle(division).display === 'none');
}
function toggleElements(division, checkBox, isShown) {
// Toggle the division (show/hide) accordingly.
division.style.display = isShown ? 'block' : 'none';
// Due to the fact that the event listener is attached to the parent of the checkBox, we need to maintain consistency manually.
checkBox.checked = isShown;
}
// Remove from the array of DOMElements those that aren't checkboxes and add a click event listener to each of them.
domElements
.filter(function (el) {
return el.className.indexOf('editoropt') !== -1;
})
.forEach(function (el) {
el.addEventListener('click', clickCallback, false);
});
// Call the function passing the dom elements with class '.seq-box-form-field' as argument. Checkboxes are contained within them. Also, transform the nodelist
// into a proper array so that methods defined in Array.prototype can be used.
})([].slice.call(document.querySelectorAll('.seq-box-form-field')));
The code is commented and (I think) quite self-explanatory. However, if you have any doubt or want me to elaborate any point further, please, let me know.
Finally, here's the working fiddle.
UPDATE
Same function (more or less) but now it accepts an array of values that will correspond to the initial state of the checkboxes:
(function (domElements, cbState) {
function clickCallback() {
toggleElements(this.className);
}
function toggleElements(className, initialShow) {
var checkNumber = ((/ editoropt(\d*) /).exec(className))[1],
checkBox = document.getElementById('checkboxopt' + checkNumber),
division = document.querySelectorAll('.editoraccvar' + checkNumber)[0],
isShown = initialShow === undefined ? window.getComputedStyle(division).display === 'none' : initialShow;
division.style.display = isShown ? 'block' : 'none';
checkBox.checked = isShown;
}
domElements
.filter(function (el) {
return el.className.indexOf('editoropt') !== -1;
})
.forEach(function (el, index) {
el.addEventListener('click', clickCallback, false);
toggleElements(el.className, cbState[index]);
});
// Initial state of the checkboxes goes in the second parameter. The index in the array correspond to the checkbox position in the page.
})([].slice.call(document.querySelectorAll('.seq-box-form-field')), [false, false]);
Here's the Fiddle to play with. Hope it helps.
The other half of your problem, not addressed in the other answer has to do with events. Generally, adding an "onclick" attribute to the actual HTML is considered bad practice. You can attach event handlers with Javascript.
var a = document.getElementById("checkboxopt1");
a.addEventListener("click", exFunction, false);
See the manual for more info about how to use this.
Looks like that you need the elements that have the class "field-summernote", but not the class "editorbdyvar".
You can use a query selector to get elements by class name using the default tools from Javascript:
var items = document.querySelectorAll('.field-summernote');
for(var i = 0; i<items.length; i++){
var current = items[i];
if( current.className.indexOf('editoraccvar') < 0) //not found: -1
return;
//now you can manipulate the current element
console.log(current);
}
well ... you should either learn javascript, DOM, HTML and CSS or hire an somebody that can do it.
in my opinion the latter would come cheaper.
if not,
here goes something to put in your script.js file.
the checkboxes must have the id="toggleTextareas" respectively id="toggleInputs".
(function isolateScope() {
tryInit();
function tryInit() {
if(document.readyState!="complete"){
setTimeout(tryInit, 100);
}else{
createUI();
init();
}
}
function createUI(){
var div=document.createElement("div");
div.className="addon-floating-toolbar"
div.style.position="fixed";
div.style.zIndex="999999";
div.style.background="#EEE";
div.style.padding="5px";
div.innerHTML='<input type="checkbox" id="toggleTextareas">toggle Textareas<br>'
+'<input type="checkbox" id="toggleInputs">toggle Inputs';
document.body.appendChild(div);
}
function init() {
var tta=document.getElementById("toggleTextareas");
var ti=document.getElementById("toggleInputs");
var textareaVisible=true;
var inputVisible=true;
tta.onclick=toggleTextareas;
ti.onclick=toggleInputs;
function toggleTextareas() {
var elms=document.querySelectorAll("textarea");
textareaVisible=!textareaVisible;
if (textareaVisible) {
show(elms);
}else{
hide(elms);
}
}
function toggleInputs() {
var elms=document.querySelectorAll("input");
inputVisible=!inputVisible;
if (inputVisible) {
show(elms);
}else{
hide(elms);
}
}
function show(collection) {
for (var i = 0; i < collection.length; i++) {
collection[i].style.display="";
}
}
function hide(collection) {
for (var i = 0; i < collection.length; i++) {
collection[i].style.display="none";
}
}
}
})();
let me know if it works,
cheers.
You can traverse all your fields and generate a checkbox that will toggle it open/close for each of your fields. Also set the checkbox label as innerText of the corresponding field.
// Block to be run
generateCheckboxes = function() {
var button = document.getElementById("generateButton");
button.parentNode.removeChild(button);
// grab all elements with the class, .field-summernote
var uiblocks = [].slice.call(document.querySelectorAll('.field-summernote')).filter(function(x) {
return x.className.indexOf('editoraccvar') >= 0
});
if (!uiblocks.length) return;
var chcontainer = document.createElement('div');
chcontainer.style.display = "inline-block";
document.body.insertBefore(chcontainer, document.body.children[0]);
uiblocks.forEach(function(x) {
var cdiv = document.createElement('div');
var clabel = document.createElement('label');
clabel.innerHTML = x.innerText.trim();
var cinput = document.createElement('input');
cinput.type = 'checkbox';
cinput.checked = true;
cinput.onchange = function(ev) {
var checked = this.checked;
x.style.display = checked ? "" : "none";
}
cdiv.appendChild(clabel);
cdiv.appendChild(cinput);
cdiv.appendChild(document.createElement('br'));
chcontainer.appendChild(cdiv);
})
};
#container {
width: 150px;
}
input {
float: left;
}
label {
width: 120px;
display: block;
float: right;
text-align: left;
}
<button onclick="generateCheckboxes()" id="generateButton">Generate Checkboxes</button>
<div id="example" class="field-summernote editoraccvar">
<br/>
<br/>
<span>Zero</span>
<br/>
<textarea></textarea>
</div>
<div id="example1" class="field-summernote editoraccvar1">
<br/>
<br/>
<span>One</span>
<br/>
<textarea></textarea>
</div>
<div id="example2" class="field-summernote">
<br/>
<br/>
<span>Two</span>
<br/>
<textarea></textarea>
</div>
Fiddle

$(this) acts like both event and <div>

I'm a long-time procedural programmer now assigned to a web-app and studying jquery from a book. The exercise is to run some code on one div selected from a row of 4 <div>s using .each(). I attempted to store the div object that was clicked, then match it as the .each looped thru the 4 divs.
My following code works after trial and error, but the same $(this) seems to sometimes point to a div object, and sometimes to an event object.
How do you explain that behavior?
I understand that .context is deprecated. I tried .target but that didn't seem to work. Is there something else that I should be using?
My primary interest is to understand what is going on (question 1), so if you can provide an explanation and not just an alternative solution (question 2), I'd really appreciate it. Thank you in advance. Here are the code snippets:
<body>
<div id="header">
<h2>Jump for Joy Sale</h2>
</div>
<div id="main">
<div class="guess_box"><img src="images/jump1.jpg"/></div>
<div class="guess_box"><img src="images/jump2.jpg"/></div>
<div class="guess_box"><img src="images/jump3.jpg"/></div>
<div class="guess_box"><img src="images/jump4.jpg"/></div>
</div>
<script src="scripts/jquery-1.6.2.min.js"></script>
<script src="scripts/my_script.js"></script>
</body>
Jscript
$(document).ready(function()
{
$(".guess_box").click(checkForCode);
function checkForCode()
{
var code_box = 2;
var discount_code = getRandomNum(1,100);
var clicked = $(this); // debugger says clicked is an event object
var iteration = 0;
$(".guess_box").each(function()
{
if ($(this).context === $(clicked).context) //act like event objs
{
if (iteration === code_box)
{
// clicked on correct box
$(this).addClass("discount"); //same $(this) acts like <div>
discount_msg = "<p>Your Code: CODE"+ discount_code +"</p>";
return(false);
}
}
else
{
if (iteration === code_box)
{
// if wrong box clicked, highlight the right one
$(this).addClass("no_discount");
discount_msg = "<p>Sorry, no discount this time</p>";
return(false);
}
}
iteration += 1;
});
$(".guess_box").unbind();
$(this).append(discount_msg); // don't worry about this line
} //checkForCode
}); //ready
The context of this depends on where and how it's used. if your function is called by an an event it will refer to the target of the event, otherwise it will refer to the object being called upon.
What youre seeing in your console is not this, or an event object, it's a jQuery object. If you want to inspect this you need to remove the jQuery wrapper function.
console.log(this);
Event example..
<div>click me</div>
$("div").click(function(){
// referring to the div itself
$(this).text("you clicked me");
// Note you can do it without jQuery as well
// this.innerHTML = "you clicked me";
});
object example
function something(){
this.something = "something";
this.doAThing = function(){
this.something = "something new";
}
}
var thing = new something();
thing.doAThing();
alert(thing.something);
Thanks to those that responded. As Pamblam indicated, I was confusing this and $(this). I replaced 2 lines in my code and it makes more sense:
clicked = $(this) becomes clicked = this
if ($(this).context === $(clicked).context) becomes
if (this === clicked)

Optimizing code to define variables only once, code only works when the vars are in change function and for the code outside change I redefine?

Pretty sure I know the solution... would write .on('change','load', function(){}
correct? <-- Tested didn't work? so I am up to your solutions :)
Sushanth -- && adeneo both came up with great solutions, this is a good lesson in optimizing code... It's gonna be hard to choose which answer to go with, but I know this is going to help me rethink how I write... I dont know what I do without this forum, id have to learn this stuff in college.
This is purely a question out of curiosity and bettering my skills, as well as giving you guys a chance to display your knowledge on jQuery. Also to prevent any sloppy writing.
I have a radio based switch box, the markup looks like this, the id's and on/off values are generated by the values in my array with PHP...
<span class="toggle-bg">//This color is the background of the toggle, I need jQuery to change this color based on the state on/off
<input type="radio" value="on" id="_moon_page_header_area1" name="_moon_page_header_area">//this is my on value generated by the array
<input type="hidden" value="_moon_page_header_area" class="switch-id-value">// I create this input because I have multiple checkboxes that have the ID _moon_ARRAYVALUE_area1
<input type="radio" value="off" id="_moon_page_header_area2" name="_moon_page_header_area">// off value
<input type="hidden" value="_moon_page_header_area" class="switch-id-value">//_moon_ARRAYVALUE_area2
<span class="switch"></span>// the switch button that changes
</span>
Hope that makes sense and the comments are clear
Here is the jQuery
var value = $('.toggle-bg input.switch-id-value').val()
var moon1 = $('#'+value+'1').is(':checked');
var moon2 = $('#'+value+'2').is(':checked');
var static_slide = $('._moon_staticarea_height');
var toggle = $('.toggle-bg');
if(moon1){
toggle.css({'background-color': '#46b692'});
static_slide.hide()
} else
if (moon2){
toggle.css({'background-color': '#333'});
static_slide.show()
}
$('.toggle-bg').change(function () {
var value = $('.toggle-bg input.switch-id-value').val()
var moon1 = $('#'+value+'1').is(':checked');
var moon2 = $('#'+value+'2').is(':checked');
var static_slide = $('._moon_staticarea_height');
var toggle = $('.toggle-bg');
if(moon1){
toggle.css({'background-color': '#46b692'});
static_slide.slideUp()
} else
if (moon2){
toggle.css({'background-color': '#333'});
static_slide.slideDown()
}
});
it looks longer than it really is, its just repeating it self, one is on load so that it gives the correct color on load of the page, and then inside the change function we need to change colors..
How do I write it so I only have to use variables one time (so its cleaner) is there a better way to optimize it... Just NOW thinking after writing this I could put it in one function .on('load', 'change', function() {}
I just now thought of that, but I wrote all this so I am going to see what others think...
You'd do that by having the function in the change event handler, and on the end you chain on a trigger('change') to make it work on pageload :
$('.toggle-bg').on('change', function () {
var value = $('.toggle-bg input.switch-id-value').val(),
moon1 = $('#' + value + '1').is(':checked'),
slider = $('._moon_staticarea_height'),
toggle = $('.toggle-bg');
toggle.css('background-color', (moon1 ? '#46b692' : '#333'));
slider[moon1?'slideUp':'slideDown']();
}).trigger('change');
As radiobuttons can't be unchecked, it's either moon1 or moon2, which means checking one of them should be enough.
.on('change','load',
supposed to be
// Remove the comma separator if you want to bind the same handler to
// multiple events.
.on('change load',
And you can remove the one separately written out and enclose it in a function (if multiple instances of the class toggle-bg)
or just trigger the change event.(If there is a single instance of a class)
This will just run the same functionality when the page loads.
var toggle = $('.toggle-bg');
toggle.change(function () {
var value = $('input.switch-id-value', this).val(),
moon1 = $('#' + value + '1').is(':checked'),
moon2 = $('#' + value + '2').is(':checked'),
static_slide = $('._moon_staticarea_height');
if (moon1) {
toggle.css({
'background-color': '#46b692'
});
static_slide.slideUp()
} else if (moon2) {
toggle.css({
'background-color': '#333'
});
static_slide.slideDown()
}
}).change();

How to migrate a .change function from jQuery to plain Javascript

I'm not a JS expert but i think what i'm trying to do is pretty simple (at least in jQuery)
I've got 3 select
<select id="faq" class="onchance_fill">...</select>
<select id="pages" class="onchance_fill">...</select>
<select id="faq" class="onchance_fill">...</select>
and an input (it's a tinyMCE one in advlink plugin)
<input type="text" onchange="selectByValue(this.form,'linklisthref',this.value);" value="" class="mceFocus" name="href" id="href" style="width: 260px;">
I want that each time i change a value in one of the 3 select, that this value of the option, will be placed in the input.
In Jquery, it would be something like :
$('.ajax_onchance_fill').change(function() {
data = $('.ajax_onchance_fill').val();
$('#href').text(data);
});
But i can't use it. So what is the equivalent in plain Javascript ?
Thanks
I would advice you keep using Jquery as it speeds up this kind of thing but in pure JavaScript i think what you want looks something like this...
<script type="text/javascript">
function load() {
var elements = document.getElementsByClassName('onchance_fill');
for(e in elements){
elements[e].onchange = function(){
document.getElementById('href').value = this.value;
}
}
}
</script>
document.getElementsByClassName("ajax_onchance_fill").onchange = function() {
getElementById('href').value = this.options[this.selectedIndex].text;
};
Though I am not sure exactly if it'll work since getElementsByClassName returns more than 1 element.
Try this:
$('.ajax_onchance_fill').change(function() {
var data = $(this).val();
$('#mytextboxid').val(data);
});
Okay, so I realize this thread is well over 8 years old, so this answer isn't so much for the OP (who probably figured it out long ago) as it is for someone else who might be curious about this particular topic.
All that said, here's a relatively simple and reliable way you could pull it off in vanilla JS:
/**
* Since we need to listen to all three ajax_onchance_fill elements,
* we'll use event delegation.
*
*/
const targetLink = document.getElementById('href');
document.addEventListener('change', function(e) {
if (!!Element.prototype.matches) { // Let's make sure that matches method is supported...
if (e.target.matches('.ajax_onchance_fill')) {
targetLink.textContent = e.target.value;
}
} else { // and if not, we'll just use classList.contains...
if (e.target.classList.contains('ajax_onchance_fill')) {
targetLink.textContent = e.target.value;
}
}
});

How to turn this into a global javascript function effecting all values

This code loads via jQuery a page based onclick events of checkboxes.
function product_analysis(address, box) {
if (box.checked) {
$('#product_' + box.alt).load(address);
} else {
$('#product_' + box.alt).load('http://www.divethegap.com/update/blank2.html');
}
document.getElementById('product_quantity_PRI_' + box.alt).value = box.value;
};
With the onclick event looking as follows onclick="product_analysis('http://www.samedomain.blahblahblah', this)
What I need is that for all checkboxes that are already ticked on page load to have this function applied to them all. I am reasonably confident with javaScript but when it comes to objects and arrays I get lost.
Many Thanks,
You can use this code to find all the checkboxes that are currently checked:
$(':checkbox:checked')
If you then want to do something to all of them, you can use the each function like this:
$(':checkbox:checked').each(function() {
// alerts the checkbox for example
// "this" referes to the checkbox, one after the other
alert(this);
})
Or to do what you asked for ("for all checkboxes that are already ticked on page load to have this function applied to them all"):
$(':checkbox:checked').each(function() {
product_analysis("someaddress", this);
})
EDIT: To address the second issue (not a part of the original question, but to the comments below):
I will assume that you have fields like this in your markup. Use some meaningful IDs rather than my stupid examples of course.
<input type="checkbox" id="foo" />
<input type="checkbox" id="bar" />
<input type="checkbox" id="baz" />
Then you'll put the following in your JS:
var addresses = {
foo: 'some_address',
bar: 'some_other_address',
baz: 'yet_another_one'
};
$(':checkbox:checked').each(function() {
product_analysis(addresses[this.id], this);
})
That will invoke product_analysis with the address that corresponds to the ID of the checkbox.
EDIT (again):
There is actually a way to add meta-data directly to the html-tags that I wasn't aware of. You can add attributes prefixed by "data-" to your tag, like this:
<input type="checkbox" data-address="someaddress" data-foo="something else" data-bar="more data!" />
You can read more about it on John Resigs blog.
this is required script
$().ready(function(){
var box, address;
$(":checkbox").each(function(){
box = this;
if (box.checked) {
address = ""; //you can set address either in hidden fields or in metadata
$('#product_' + box.alt).load(address);
}
else {
$('#product_' + box.alt).load('http://www.divethegap.com/update/blank2.html');
}
document.getElementById('product_quantity_PRI_' + box.alt).value = box.value;
});
});
You need to check how many number of check is checked and then invoke your code.
var checkLength = checkObj.length;
for(var i = 0; i < checkLength ; i++) {
if(radioObj[i].checked) {
}
// here your code base on check box status
}
If you have a class called as "selected" when the check box are checked, you could do something like this
$('.selected').function(element){product_analysis(address, element)};
Thanks chaps for all your help here is I I got it. Jakob will probably consider this a hack but it is a data driven site and based on my limited technical knowledge can't be tasked with modifying a JS file every time we add a new product.
function product_analysis_global() {
$(':checkbox:checked').each(function() {
$('#product_' + this.alt).load(this.title);
});
}
function product_analysis(box) {
if (box.checked) {
$('#product_' + box.alt).load(box.title);
}
else {
$('#product_' + box.alt).load('http://www.divethegap.com/update/blank2.html');
}
document.getElementById('product_quantity_PRI_' + box.alt).value = box.value;
};

Categories

Resources