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/
Related
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.
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.
I have a file selector that populates a div with a thumbnail based on the file. Now I have multiple buttons and divs that contain the same class names. What I am using for each time the primary button is selected is, var thisButton = $(event.target); which translates to:
var appendThis = thisButton.closest('.insurance').find(".attachmentCont");
appendThis.append('<div class="singleImg"><img src="'+attachment.url+'" width="100px"/><input type="hidden" class="fileURL" value="'+attachment.id+'"/><span class="removeImg remove"> X </span></div>');
$(".removeImg").bind('click', function(){
$(this).parent().remove();
});
The appenThis equals the button which is within a div containing another div attachmentCont Both the button and div are within a parent div which is div.insurance There are multiple div.insurance containers. My issue is when using thisButton.closest('.insurance').find(".attachmentCont"); it always focuses on the .attachmentCont div that was first selected. So if I selected section 1, the image populates. If I select section 2, section 1 still gets that image when the div.attachmentCont within section 2 should of gotten the append() too.
Suggestions or Thoughts?
HTML EXAMPLE:
<div class="notes-section insurance">
<span><b>General </b></span><textarea style="width:97%;" rows="5" cols="50" class="insurance-description fields contractor_insurance_description" placeholder="...."></textarea>
<input type="date" class="expiration-date" placeholder="Expiration Date">
<br>
<span>Your</span>
<div class="attachmentCont">
</div>
<br>
<input type="button" class="upload_image_button" value="Attach Documents" style="width:150px;">
</div>
Here was the issue:
My blindness did not see that the function that contains the selected button was not in any way associated with the function that appended the data. Because of this all I had to do was move my var thisButton outside into the parent class.
Thank you everyone for you're time.
Solutions:
var thisButton
$('.upload_image_button').on('click', function( event ){
thisButton = $(event.target);
event.preventDefault();
});
....
function...({
var appendThis = thisButton.closest('.insurance').find(".attachmentCont");
appendThis.append('<div class="singleImg"><img src="'+attachment.url+'" width="100px"/><input type="hidden" class="fileURL" value="'+attachment.id+'"/><span class="removeImg remove"> X </span></div>');
$(".removeImg").bind('click', function(){
$(this).parent().remove();
});
});
Im having trouble having code onchange inside onchange event.
some works and some dont work due to that.
<script>
$(document).on('change', '.sellkop', function() { // this is radio button
if ($("#rs").is(':checked')) {
$("#text_container").after(price_option());
};
if ($("#rk").is(':checked')) {
$("#price_container").remove();
$("#licensenumber_c").css({"display": 'none'
});
};
});
$('#category_group').on('change', function() { // this is select options
if ($(this).val() == 101) {
$("#underKategory").css({"display": 'none'});
$("#modelcontainer").remove();
$(".toolimage").css({ "display": 'block'});
$('.sellkop').on('change', function() { // this is radio button
if ($("#rs").is(':checked')) {
$("#licensenumber_c").css({"display": 'block'});
$(".toolimage").css({"display": 'block' });
} else {
$(".toolimage").css({"display": 'none'});
}
});
} else {
$(".bilar").remove();
$(".toolimage").css({ "display": 'none'});
}
if ($(this).val() == 102) {
$(".houses_container").remove();
$(".toolimage").css({"display": 'none'});
$("#underKategory").css({"display": 'inline-block'});
$("#modelcontainer").remove();
}
///............many other values continue
});
</script>
i know there is better way to manage this code and simplify it , how can i do it ?
EDIT:
what i want is : if i select an option , then get values to that option, then under this category option there is radio buttons , then every check button i need to get some data displayed or removed
here is a fiddle there looks my problem by jumping from categories when i select buy or sell , so
if i select category-->check buy -->then select others . i dont get same result as if i select directly cars ---> buy
I have never resorted to even two answers before (let alone three), but based on all the comments, and in a desire to keep things simple another solution is to data-drive the visibility of other items based on selections, using data- attributes to store the selectors on the options and radio buttons.
JSFiddle: http://jsfiddle.net/TrueBlueAussie/4s5rwce2/28/
e.g the HTML for the select becomes
<select name="category_group" id="category_group">
<option value="0">choose category</option>
<option value='101' id='cat101' data-show="#sellbuy,.cars,.toolimage,#licenscontainer">cars</option>
<option value='102' id='cat102' data-show="#sellbuy,#underKategory">others</option>
</select>
and the radio buttons like this:
<input id='rs' type='radio' class='radio sellkop' value='s' name='type' checked='checked' data-show="#price_container,.cars,.toolimage"/>
The code becomes very simple then, simply applying the filters specified in the selected items.
$(document).on('change', '.sellkop', function () { // this is radio button
// Hide defaults
$("#price_container,.cars,.toolimage").hide();
// Show the items desired by the selected radio button
$($(this).data("show")).show();
});
$('#category_group').on('change', function () { // this is select options
// Get the various possible data options and decide what to show/hide based on those
var $this = $(this);
var value = $this.val();
// Get the selected option
var $li = $('option[value='+ value+']', $this);
// Hide all the defaults first
$('#licenscontainer,.cars,.toolimage,.sell,#underKategory').hide();
// Now show any desired elements
$($li.data('show')).show();
// Fire change event on the radio buttons to ensure they change
$('.sellkop:checked').trigger('change');
});
This is a very generic solution that will allow very complex forms to turn on/off other elements as required. You can add data-hide attributes and do something similar for those too if required.
Note: This was an attempt to fix the existing style of coding. I have posted an alternate answer showing a far simpler method using hide/show only.
A few problems.
If you must nest handlers, simply turn them off before you turn them on. Otherwise you are adding them more than once and all the previously recorded ones will fire as well.
Your HTML strings are invalid (missing closing </div>)
You can simply use hide() and show() instead of all the css settings. You should use css styling for any specific element styling requirements (e.g. based on classes).
You need to replace specific divs, rather than keep using after, or you progressively add more html. For now I have use html to replace the content of the #text_container div.
HTML in strings is a maintenance nightmare (as your example with missing </div> shows). Instead use templates to avoid the editing problems. I use dummy script blocks with type="text/template" to avoid the sort of problems you have found. That type means the browser simply ignores the templates.
JSFiddle: http://jsfiddle.net/TrueBlueAussie/4s5rwce2/17/
HTML (with templates)
<script id="saljkop">
<div class='sex sell' id='sellbuy' >
<label ><input id='rs' type='radio' class='radio sellkop' value='s' name='type' checked='checked'/> Sell </label>
<label ><input id='rk' type='radio' class='radio sellkop' value='k' name='type'/>buy</label>
</div>
</script>
<script id="price_option">
<div class="container" id = "price_container">
<div>
<label><input class="price_option" name="price_opt" value="1" type="radio"/> Fix </label>
<label class="css-label"><input class="price_option" name="price_opt" value="2" type="radio"/> offer </label>
</div>
</div>
</script>
<script id="cars">
<div class="cars" >
<div id="licenscontainer" ><div id="licensenumber_c">
<input id="licensenumber" placeholder="Registrer number" type="text" value="" />
</div>
</div>
</div>
</script>
<div id="categories">
<select name="category_group" id="category_group">
<option value="0">choose category</option>
<option value='101' id='cat101'>cars</option>
<option value='102' id='cat102'>others</option>
</select>
</div>
<div id="underKategory">sthis is subcategory</div>
<div id="toolimage1" class="toolimage">dddddd</div>
<div id="text_container" class="text_container">textttttt</div>
New jQuery code:
$(document).on('change', '.sellkop', function () { // this is radio button
console.log('.sellkop change');
if ($("#rs").is(':checked')) {
$("#text_container").html($('#price_option').html());
};
if ($("#rk").is(':checked')) {
$("#price_container").remove();
$("#licensenumber_c").hide();
};
});
$('#category_group').on('change', function () { // this is select options
if ($(this).val() == 101) {
$(".sell").remove();
$("#categories").after($('#saljkop').html());
$("#sellbuy").after($('#cars').html());
$("#text_container").html($('#price_option').html());
$("#underKategory").hide();
$(".toolimage").show();
$('.sellkop').off('change').on('change', function () { // this is radio button
if ($("#rs").is(':checked')) {
$("#licensenumber_c").show();
$(".toolimage").show();
} else {
$(".toolimage").hide();
}
});
} else {
$(".cars").remove();
$(".toolimage").hide();
}
if ($(this).val() == 102) {
$(".sell").remove();
$("#categories").after($('#saljkop').html());
$("#text_container").html($('#price_option').html());
$(".toolimage").hide();
$("#underKategory").show();
}
///............many other values continue
});
Now if you prefer to not nest handlers (recommended), just add to your existing delegated event handler for the radio buttons:
$(document).on('change', '.sellkop', function () { // this is radio button
console.log('.sellkop change');
if ($("#rs").is(':checked')) {
$("#text_container").html($('#price_option').html());
$("#licensenumber_c").show();
$(".toolimage").show();
};
if ($("#rk").is(':checked')) {
$("#price_container").remove();
$("#licensenumber_c").hide();
$(".toolimage").hide();
};
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/4s5rwce2/20/
Note: This was a second answer, hoping to simplify the overall problem to one of hiding/showing existing elements. I have posted a third(!) answer that takes it to an even simpler scenario using data- attributes to provide the filter selections.
I am adding a second answer as this is a complete re-write. The other answer tried to fix the existing way of adding elements dynamically. I now think that was simply a bad approach.
The basic principal with this one is to have very simple HTML with the required elements all present and simply hide/show the ones you need/ Then the selected values are retained:
This uses the multi-structure to effectively hide.show the licence field based on two separate conditions.
JSFiddle: http://jsfiddle.net/TrueBlueAussie/4s5rwce2/23/
Html (all element s present, just the ones you do not need hidden):
<div id="categories">
<select name="category_group" id="category_group">
<option value="0">choose category</option>
<option value='101' id='cat101'>cars</option>
<option value='102' id='cat102'>others</option>
</select>
<div class='sex sell' id='sellbuy' style="display: none">
<label>
<input id='rs' type='radio' class='radio sellkop' value='s' name='type' checked='checked' />Sell</label>
<label>
<input id='rk' type='radio' class='radio sellkop' value='k' name='type' />buy</label>
</div>
<div class="cars" style="display: none">
<div id="licenscontainer">
<div id="licensenumber_c">
<input id="licensenumber" placeholder="Registrer number" type="text" value="" />
</div>
</div>
</div>
</div>
<div id="underKategory">sthis is subcategory</div>
<div id="toolimage1" class="toolimage">dddddd</div>
<div id="text_container" class="text_container">
<div class="container" id="price_container" style="display: none">
<div>
<label>
<input class="price_option" name="price_opt" value="1" type="radio" />Fix</label>
<label class="css-label">
<input class="price_option" name="price_opt" value="2" type="radio" />offer</label>
</div>
</div>
</div>
jQuery:
$(document).on('change', '.sellkop', function () { // this is radio button
if ($("#rs").is(':checked')) {
$("#price_container").show();
$(".cars").show();
$(".toolimage").show();
};
if ($("#rk").is(':checked')) {
$("#price_container").hide();
$(".cars").hide();
$(".toolimage").hide();
};
});
$('#category_group').on('change', function () { // this is select options
if ($(this).val() == 101) {
$(".sell").hide();
$("#sellbuy").show();
$(".cars").show();
$("#underKategory").hide();
$(".toolimage").show();
$('#licenscontainer').show();
} else {
$('#licenscontainer').hide();
$(".cars").hide();
$(".toolimage").hide();
}
if ($(this).val() == 102) {
$(".sell").hide();
$("#sellbuy").show();
$(".toolimage").hide();
$("#underKategory").show();
$(".cars").hide();
}
$("#price_container").toggle($("#rs").is(':checked'));
///............many other values continue
});
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>