Jquery how to use variable as identifier for .change() function? - javascript

right now I am a beginner in Javascript/Jquery.
I want to create a dynamic code, so that it will work when there comes some new features to the website without need to edit code.
Now i just read in some posts how to use a variable as identifier for id, but it is not working for me. So below is an example:
var category;
$('#mainCategory').change(function (event) {
checkboxID = event.target.id;
category="category"+checkboxID;
...some code...
});
$("#"+category).change(function (event) {
$('#category'+checkboxID+' :input').attr('class','' );
console.log("var: "+category);
});
So the function mainCategory always runs before the other one and category got written correct in the 2nd function, when i am using the whole expression instead of using a variable.
I hope you can help me.
the part of html code:
<form method="post" action="../php/saveTraining.php">
<section id="mainCategory" class="hidden">
<label><input type="checkbox" id="Krafttraining">Krafttraining</label>
<label><input type="checkbox" id="Joggen">Joggen</label>
</section>
<section id="categoryKrafttraining" class="hidden">
<label><input type="checkbox">Kurzhantel</label>
<label><input type="checkbox">Bankdrücken</label>
<label class="hidden"><input type="number" id="saetze">Sätze</label>
<label class="hidden"><input type="number" id="wiederholungen">Wiederholungen</label>
</section>
<input type="hidden" id="saveTraining" name="sent" value="save" class="hidden"/>
</form>
So what actually happens is that when checking a checkbox of mainCategory the checkboxes of the second section appearing.
But when I check a checkbox of the second section nothing happens.

I thought I had the solution before but I see I was wrong. I believe this should work, where you re-add the listener as the value for the var category change:
var category;
$('#mainCategory input[type="checkbox"]').change(function (event) {
checkboxID = event.target.id;
category="category"+checkboxID;
$('#' + category).find('input[type="checkbox"]').off("change").on("change", function (event) {
$('#category'+checkboxID+' :input').attr('class','' );
console.log("var: "+category);
});
});
You need to re-add the listener because new elements will be targeted as var category changes.

Related

Checkbox always cheked if property specified?

This is driving me completely nuts. I can't figure out how to check/uncheck a checkbox through JavaScript.
I have the following in my HTML file:
<div class="form-group">
<label class="col-sm-3 control-label"></label>
<div class="col-sm-9">
<div class="checkbox">
<input id="hardhat" type="checkbox" name="hardhat" checked="false" class="flat"/> Does the employee need his own hardhat?
</div>
</div>
</div>
Which translates to this in Jade:
.form-group
label.col-sm-3.control-label
.col-sm-9
.checkbox
input#hardhat(type='checkbox', name='hardhat', class='flat', checked='false')
| Does the employee need his own hardhat?
Having the checked property in HTML will ALWAYS open the window with the checkbox checked. The only way to uncheck the checkbox is to remove the checked property. What am I missing?
Because of this, nothing I do in JavaScript to check/uncheck the checkbox works :(. I was trying this:
var $modal = $('#editJob');
$modal.find('input#hardhat')['checked']=true;
Any help would be greatly appreciated!
EDIT:
function showJobInfo(event) {
document.getElementById('editJob').style.display = "block";
document.getElementById('editJob').style.visibility = "visible";
// Prevent Link from Firing
event.preventDefault();
// Retrieve job title from link rel attribute
var thisJobTitle = $(this).attr('rel');
// Get Index of object based on id value
var arrayPosition = userJoblistData.map(function(arrayItem) { return arrayItem.title; }).indexOf(thisJobTitle);
// Get our Job Object
var thisJobObject = userJoblistData[arrayPosition];
// Populate the edit job popup window
var $modal = $('#editJob');
$modal.find('input#jobTitle').val(thisJobObject.title);
$modal.find('input#payRate').val(thisJobObject.payrate);
$modal.find('input#startDate').val(thisJobObject.durationstart);
$modal.find('input#endDate').val(thisJobObject.durationend);
$modal.find('input#workingHours').val(thisJobObject.workinghrs);
$modal.find('input#location').val(thisJobObject.location);
$('#hardhat').prop('checked', false);
}
I do not understand what is the problem. If you want always checked, add checked="true" html attribute.
https://jsfiddle.net/yw3obrrt/
<input id="hardhat" type="checkbox" name="hardhat" checked="true" class="flat"/>
Check in jade that checked='true'
input#hardhat(type='checkbox', name='hardhat', class='flat', checked='true')
| Does the employee need his own hardhat?
For test, not use F5 because remember your selection.
If not works.. try with jquery and use
$(document).ready(function (){
$("#hardhat").attr("checked",true);
});
https://jsfiddle.net/yw3obrrt/1/
In your example!!
$('#hardhat').prop('checked', false);
This line, unchecked checkbox!
Change to
$('#hardhat').attr('checked', true); // attr or prop
or comment this and add checked="true" in the html input!

Condtionally disable button by Radio and Checkbox

I would like to conditionally disable a button based on a radio and checkbox combination. The radio will have two options, the first is checked by default. If the user selects the second option then I would like to disable a button until at least one checkbox has been checked.
I have searched at length on CodePen and Stack Overflow but cannot find a solution that works with my conditionals. The results I did find were close but I couldn't adapt them to my needs as I am a Javascript novice.
I am using JQuery, if that helps.
If needed:
http://codepen.io/traceofwind/pen/EVNxZj
<form>
<div id="input-option1">First option: (required)
<input type="radio" name="required" id="required" value="1" checked="checked">Yes
<input type="radio" name="required" id="required" value="2">No
<div>
<div id="input-option2">Optionals:
<input type="checkbox" name="optionals" id="optionals" value="2a">Optional 1
<input type="checkbox" name="optionals" id="optionals" value="2b">Optional 2
<div>
<div id="input-option3">Extras:
<input type="checkbox" name="extra" id="extra" value="3">Extra 1
<div>
<button type="button" id="btn">Add to Cart</button>
</form>
(Please excuse the code, it is in short hand for example!)
The form element IDs are somewhat fixed. The IDs are generated by OpenCart so I believe the naming convention is set by group, rather than unique. I cannot use IDs such as radio_ID_1 and radio_ID_2, for example; this is an OpenCart framework facet and not a personal choice.
Finally, in pseudo code I am hoping someone can suggest a JQuery / javascript solution along the lines of:
if radio = '2' then
if checkboxes = unchecked then
btn = disabled
else
btn = enabled
end if
end if
Here is a quick solution and I hope that's what you were after.
$(function() {
var $form = $("#form1");
var $btn = $form.find("#btn");
var $radios = $form.find(":radio");
var $checks = $form.find(":checkbox[name='optionals']");
$radios.add($checks).on("change", function() {
var radioVal = $radios.filter(":checked").val();
$btn.prop("disabled", true);
if (radioVal == 2) {
$btn.prop("disabled", !$checks.filter(":checked").length >= 1);
} else {
$btn.prop("disabled", !radioVal);
}
});
});
Here is a demo with the above + your HTML.
Note: Remove all the IDs except the form ID, button ID (since they're used in the demo) as you can't have duplicate IDs in an HTML document. an ID is meant to identify a unique piece of content. If the idea is to style those elements, then use classes.
If you foresee a lot of JavaScript development in your future, then I would highly recommend the JavaScript courses made available by Udacity. Although the full course content is only available for a fee, the most important part of the course materials--the videos and integrated questions--are free.
However, if you don't plan to do a lot of JavaScript development in the future and just need a quick solution so you can move on, here's how to accomplish what you are trying to accomplish:
$(document).ready(function(){
$('form').on('click', 'input[type="radio"]', function(){
conditionallyToggleButton();
});
$('form').on('click', 'input[type="checkbox"]', function(){
conditionallyToggleButton();
});
});
function conditionallyToggleButton()
{
if (shouldDisableButton())
{
disableButton();
}
else
{
enableButton();
}
}
function shouldDisableButton()
{
if ($('div#input-option1 input:checked').val() == 2
&& !$('form input[type="checkbox"]:checked').length)
{
return true;
}
return false;
}
function disableButton()
{
$('button').prop('disabled', true);
}
function enableButton()
{
$('button').prop('disabled', false);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div id="input-option1">First option: (required)
<input type="radio" name="required" id="required" value="1" checked="checked">Yes
<input type="radio" name="required" id="required" value="2">No
<div>
<div id="input-option2">Optionals:
<input type="checkbox" name="optionals" id="optionals" value="2a">Optional 1
<input type="checkbox" name="optionals" id="optionals" value="2b">Optional 2
<div>
<div id="input-option3">Extras:
<input type="checkbox" name="extra" id="extra" value="3">Extra 1
<div>
<button type="button" id="btn">Add to Cart</button>
</form>
Note that the JavaScript code above is a quick-and-dirty solution. To do it right, you would probably want to create a JavaScript class representing the add to cart form that manages the behavior of the form elements and which caches the jQuery-wrapped form elements in properties.

copy label text to input

I have tried several ways to achieve this, but somehow nothing works for this.
How can I copy the "label text" of respective Radio Button, which is selected by user into the input field (Result Box) in real time?
HTML -
<ul class="gfield_radio" id="input_4_4">
Radio Buttons:
<br />
<li class="gchoice_4_0">
<input name="input_4" type="radio" value="2" id="choice_4_0" class="radio_s" tabindex="4">
<label for="choice_4_0">Hi</label>
</li>
<li class="gchoice_4_1">
<input name="input_4" type="radio" value="4" id="choice_4_1" class="radio_s" tabindex="5">
<label for="choice_4_1">Hello</label>
</li>
<li class="gchoice_4_2">
<input name="input_4" type="radio" value="3" id="choice_4_2" class="radio_s" tabindex="6">
<label for="choice_4_2">Aloha</label>
</li>
</ul>
<br />
<div class="ginput_container">
Result Box:
<br />
<input name="input_3" id="input_4_3" type="text" value="" class="medium" tabindex="3">
</div>
My attempts:
$('input').change(function() {
if (this.checked) {
var response = $('label[for="' + this.id + '"]').html();
alert(response);
}
// also this:
// if ($("input[type='radio'].radio_s").is(':checked')) {
// var card_type = $("input[type='radio'].radio_s:checked").val();
// alert('card_type');
// }
});
You need to traverse the DOM from the radio which was clicked to find the nearest label element.
$('.radio_s').change(function() {
$('#input_4_3').val($(this).closest('li').find('label').text());
});
Example fiddle
You could also use $(this).next('label') however, that relies on the position of the label element not changing. My first example means the label can be anywhere within the same li as the radio button and it will work.
Try this:
$('.radio_s').click(function() {
$("#input_4_3").val($("input:checked" ).next().text());
});
Demo: http://jsfiddle.net/WQyEw/3/
This is a slightly tricky question to answer well. The structure of your HTML implies that there may be more than one of these structures on the page. So you may have more than one set of radio buttons with a corresponding checkbox.
I have put some working code into a jsFiddle.
I made one change: all the code you had in your question is now in <div class="container">. You would need as many of these as you had groups of radio buttons and checkboxes.
You can then have jQuery code like this:
$('ul.gfield_radio').on('change', 'input[type="radio"]', function () {
var label = $('label[for="' + this.id + '"]');
$(this).closest('.container').find('input.medium').val(label.text());
});
This code is not tied to the id values in this particular bit of HTML, but would work as many times as necessary throughout the page.
Why to depend on third party library when you can achieve it with plain javascript:
<script>
document.addEventListener('DOMContentLoaded', function () {
var a = document.getElementsByName('input_4');
for (var i = 0; i < a.length; i++) {
document.getElementsByName('input_4')[i].addEventListener('change', function () {
showValue(this);
}, false);
}
}, false);
function showValue(element) {
alert(element.parentNode.getElementsByTagName('label')[0].innerHTML)
}
</script>

counting checkboxes after click using jQuery

I need to count the number of checkboxes in a form that are 'checked' AFTER being clicked and BEFORE the form is submitted. I have a javascript function that is called when a box is clicked which changes some values in the form dynamically. But it is returning the counts and values which are present at the time the box is clicked.
As my code is now, I have an onClick event handler on a enclosing the checkbox and label:
<div class="part" style="padding-right: 30px" onClick="runThis()">
<input id="checkbox_2" name="dog" type="checkbox" class='topdog' checked='checked' value="2" />
<label for="checkbox_2">Snoopy (Top Dog)</label>
</div>
...
function runThis() {
var dogsSelected = jQuery("input[name='dog']:checked");
var numSelected = dogsSelected.length;
alert("numSelected: " + numSelected);
}
I am sure there is a simple solution or I am approaching this incorrectly.
Any tips/advice are appreciated.
Are there any JavaScript errors? I found that if you take that runThis() function out of $(document).ready it works properly.
You might also consider removing that onClick= attribute in favor of jQuery event handlers:
$("input[name='dog']").on('click',function(e) {
var dogsSelected = $("input[name='dog']:checked");
var numSelected = dogsSelected.length;
alert("numSelected: " + numSelected);
});
http://jsfiddle.net/mblase75/xsWDn/
If so, you should try to change it to react on mouse up, you should get a different result.
You are probably activating the event before the changes has been made to the dom three.
Edit:
nevermind it says onclick triggers in the question. my bad for not reading.
Try changing it to : onmouseup, i guess that should do the trick:
<div class="part" style="padding-right: 30px" onmouseup="runThis()">
<input id="checkbox_2" name="dog" type="checkbox" class='topdog' checked='checked' value="2" />
<label for="checkbox_2">Snoopy (Top Dog)</label>
You can use the 'change' event:
$("input[name='dog']").on('change', runThis);
function runThis() {
var dogsSelected = jQuery("input[name='dog']:checked");
var numSelected = dogsSelected.length;
alert("numSelected: " + numSelected);
}​
http://api.jquery.com/change/

trouble with jquery and traversing the DOM to select the appropriate elements

Hello guys i have the below html for a number of products on my website,
it displays a line with product title, price, qty wanted and a checkbox called buy.
qty input is disabled at the moment.
So what i want to do is,
if the checkbox is clicked i want the input qty to set to 1 and i want it to become enabled.
I seem to be having some trouble doing this. Could any one help
Now i can have multiple product i.e there will be multiple table-products divs within my html page.
i have tried using jQuery to change the details but i dont seem to be able to get access to certain elements.
so basically for each table-product i would like to put a click listener on the check box that will set the value of the input-text i.e qty text field.
so of the below there could be 20 on a page.
<div class="table-products">
<div class="table-top-title">
My Spelling Workbook F
</div>
<div class="table-top-price">
<div class="price-box">
<span class="regular-price" id="product-price-1"><span class="price">€6.95</span></span>
</div>
</div>
<div class="table-top-qty">
<fieldset class="add-to-cart-box">
<input type="hidden" name="products[]" value="1"> <legend>Add Items to Cart</legend> <span class="qty-box"><label for="qty1">Qty:</label> <input name="qty1" disabled="disabled" value="0" type="text" class="input-text qty" id="qty1" maxlength="12"></span>
</fieldset>
</div>
<div class="table-top-details">
<input type="checkbox" name="buyMe" value="buy" class="add-checkbox">
</div>
<div style="clear:both;"></div>
</div>
here is the javascript i have tried
jQuery(document).ready(function() {
console.log('hello');
var thischeck;
jQuery(".table-products").ready(function(e) {
//var catTable = jQuery(this);
var qtyInput = jQuery(this).children('.input-text');
jQuery('.add-checkbox').click(function() {
console.log(jQuery(this).html());
thischeck = jQuery(this);
if (thischeck.is(':checked'))
{
jQuery(qtyInput).first().val('1');
jQuery(qtyInput).first().prop('disabled', false);
} else {
}
});
});
// Handler for .ready() called.
});
Not the most direct method, but this should work.
jQuery(document).ready(function() {
jQuery('.add-checkbox').on('click', function() {
jQuery(this)
.parents('.table-products')
.find('input.input-text')
.val('1')
.removeAttr('disabled');
});
});
use
jQuery('.add-checkbox').change(function() {
the problem is one the one hand that you observe click and not change, so use change rather as it really triggers after the state change
var qtyInput = jQuery(this).children('.input-text');
another thing is that the input is no direct child of .table-products
see this fiddle
jQuery('input:checkbox.add-checkbox').on('change', function() {
jQuery(this)
.parent()
.prev('div.table-top-qty')
.find('fieldset input:disabled.qty')
.val(this.checked | 0)
.attr('disabled', !this.checked);
});
This should get you started in the right direction. Based on jQuery 1.7.2 (I saw your prop call and am guessing that's what you're using).
$(document).ready(function() {
var thischeck;
$('.table-products').on('click', '.add-checkbox', function() {
var qtyInput = $(this).parents('.table-products').find('.input-text');
thischeck = $(this);
if (thischeck.prop('checked')) {
$(qtyInput).val('1').prop('disabled', false);
} else {
$(qtyInput).val('0').prop('disabled', true);
}
});
});
Removing the property for some reason tends to prevent it from being re-added. This works with multiple tables. For your conflict, just replace the $'s with jQuery.
Here's the fiddle: http://jsfiddle.net/KqtS7/5/

Categories