I have buttons to increase/decrease quantity in a cart
<div class="product-quantity">
<button class="qtyminus">-</button>
<input type="text" name="quantity" value="1" class="qty form-control">
<button class="qtyplus">+</button>
</div>
my javascript unfortunately doesn't work can't figure out why.
$('.qtyplus').on('click', function(e) {
e.preventDefault();
var num = Number($(this).closest('.qty').val());
$(this).closest('.qty').val(++num);
});
jQuery closest searches ancestors, but in this case, you're looking for the sibling element. Try siblings instead of closest
By the way, modern browsers have built-in debugging tools. It's easy to set a breakpoint and step through you code to see what's happening, and to use the console window to test things.
You should use siblings() instead of closest() as closest() searches for ancestors while siblings() searches for siblings of an element.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="product-quantity">
<button class="qtyminus">-</button>
<input type="text" name="quantity" value="1" class="qty form-control">
<button class="qtyplus">+</button>
</div>
<script>
$('.qtyplus').on('click', function(e) {
e.preventDefault();
var num = Number($(this).siblings('.qty').val());
$(this).siblings('.qty').val(++num);
});
$('.qtyminus').on('click', function(e) {
e.preventDefault();
var num = Number($(this).siblings('.qty').val());
$(this).siblings('.qty').val(--num);
});
</script>
Your issue is because closest() looks up the DOM, yet .qty is a sibling to the clicked buttons, so you need to use siblings() instead.
Also note that you can use a single event handler for both buttons if you put a common class on them and provide the value to add in a data attribute. You can also negate the need to repeatedly select the same element by providing a function to val() which returns the new value based on its current one. Try this:
$('.amendqty').on('click', function(e) {
e.preventDefault();
var inc = $(this).data('inc');
$(this).siblings('.qty').val(function(i, v) {
return parseInt(v, 10) + inc;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="product-quantity">
<button class="amendqty" data-inc="-1">-</button>
<input type="text" name="quantity" value="1" class="qty form-control">
<button class="amendqty" data-inc="1">+</button>
</div>
Related
I am running into an issue where I can't seem to get my jQuery script to remove fields after they have been added. I have tried a few changes, but nothing has worked.
$(function() {
var dataSourceField = $('#sign-up-organization-discovery-source');
var i = $('#sign-up-organization-discovery-source p').size() + 1;
$('#sign-up-add-discovery-source').on('click', function() {
$('<p><label for="discovery-source-field"><input type="text" id="discovery-source-field" size="20" name="discoverySource" value="" placeholder="Input Value" /></label> Remove</p>').appendTo(dataSourceField);
i++;
return false;
});
$('#remScnt').on('click', function() {
if (i > 2) {
$(this).parents('p').remove();
i--;
}
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="col-md-6 col-md-offset-3">
<form action="/app/sign-up/organization" method="post">
<p>{{user.email}}</p>
<input type="hidden" name="admin" value="{{user.email}}">
<input type="hidden" name="organizationId">
<label for="sign-up-organization">Company/Organization Name</label>
<input type="text" class="form-control" id="sign-up-organization" name="organizationName" value="" placeholder="Company/Organization">
Add Another Discovery Source
<div id="sign-up-organization-discovery-source">
<input type="text" id="discovery-source-field" placeholder="Discovery Source" name="discoverySource">
</div>
<br />
<button type="submit">Submit</button>
</form>
Already have an account? Login here!
</div>
</div>
There are a couple problems here.
Firstly, an id is suppose to be unique! You are duplicating id attribute values each time you append the element.
Secondly, even if you were to use a class rather than an id, it still wouldn't work as expected because the clickable/removable a element doesn't exist in the DOM when you are attaching the event listeners.
You would either need to attach the event after appending the element, or you could use event delegation and attach the event to a common parent element that exists at the time.
Example Here
$('#sign-up-organization-discovery-source').on('click', '.remove', function() {
// ...
});
I changed Remove to: Remove.
Then I delegated the click event to the #sign-up-organization-discovery-source element.
$('##sign-up-organization-discovery-source').on('click', '#remScnt', function() {
if (i > 2) {
$(this).parents('p').remove();
i--;
}
return false;
});
I'm about lose my mind with this problem. No form of jQuery selector seems to work in dynamically finding any elements above the link. I'm trying to access an element above the link and hide it. Using things like parent(), prev(), before(), closest(), ect. will show a non-null object but it won't respond to the hide() method.
<div class="row">
<div class="col-xs-5">
<div id="test_fields">
<li id="test_input" class="string input optional stringish">
<label class="label" for="test_input">Ingredient name</label>
<input type="text" name="test_input" value="afsfasf" id="test_input">
</li>
</div>
<input type="hidden" id="recipe_recipe_ingredients_attributes_0__destroy" name="recipe[recipe_ingredients_attributes][0][_destroy]">
Remove Ingredient
</div>
</div>
function remove_fields(link)
{
$(link).prev("input[type=hidden]").val('1'); // this doesn't work
var divToHide = $(link).prev('div');
$(divToHide).hide() // this doesn't work
//$('#test_fields').hide(); //this works
}
Try replacing the link as below:
Remove Ingredient
I'm not sure. But maybe this is the problem. Because I remember that I have had problem with 'this'previously and when I replaced that, it performed the job.
you can try .closest() and .find()
function remove_fields(link) {
$(link).closest('div[class^="col-xs"]').find("input[type=hidden]").val('1');
var div_to_hide = $(link).closest('div[class^="col-xs"]').find('#test_fields');
$(div_to_hide).hide();
//$('#test_fields').hide(); //this works
}
You can't change hidden input's "value" attribute by using .val(). You need to use:
$(link).prev("input[type=hidden]").attr('value', '1');
As I'm not really sure what do you want to do with this input, I'll just let it go like this.
.prev() fn goes only one previous element in the structure. As input is a <a>'s previous element, you can't select div like that. You can use .siblings() for instance.
$(link).siblings('div').hide();
If you break the code in pieces, it gets easier.
First I took the 'Link', from it I grabbed the nearest div above it, then I picked up the input.
I did not make many changes to your code.
function remove_fields(link)
{
var $link =$(link);
var $divToHide = $link.closest('div');
$divToHide.find("input[type='hidden']").val('1');
$divToHide.hide()
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="row">
<div class="col-xs-5">
<div id="test_fields">
<li id="test_input" class="string input optional stringish">
<label class="label" for="test_input">Ingredient name</label>
<input type="text" name="test_input" value="afsfasf" id="test_input">
</li>
</div>
<input type="hidden" id="recipe_recipe_ingredients_attributes_0__destroy" name="recipe[recipe_ingredients_attributes][0][_destroy]">
Remove Ingredient
</div>
</div>
Given the following html:
<div class="product">
<span class="name">Product name</span>
<span class="price">Product price</span>
</div>
<input type="button" class="button" value="Purchase" onclick="myfunction()" />
<input type="hidden" name="p-name" value="">
<input type="hidden" name="p-price" value="">
I am trying to build a function in javascript that takes the value from span.name (span.price) and adds it to input p-name (input p-price).
How can you do that?
Apperantly http://api.jquery.com/val/ is not working as expected.
EDIT
Thanks all for answering!
I've corrected the html error you guys pointed out in the comments.
Try this:
$('.product span').each(function () {
var selector = 'input[name=p-' + this.className + ']';
$(selector).val(this.innerHTML);
});
Fiddle
You will need a button or something to fire the copying:
<input type="button" id="copy_values" value="Copy the values" />
and your javascript
$(document).ready(function(){
$("#copy_values").click(function(){
//Change the value of the input with name "p-name" to the text of the span with class .name
$('input[name="p-name"]').val($('.name').text());
$('input[name="p-price"]').val($('.price').text());
});
});
For span we use text() function instead of val()
.val() is used when we use input and .text() is used when we use span in HTML.
Reference link : http://api.jquery.com/text/
That's going to be hard to click to a HIDDEN field.
If you change input type to text, then in onclick you can write: this.value=document.getElementById('name').innerHTML; (to use this, you have to add ID with name to your )
OR, you can create a seperate button, and onclick method can be fired.
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/
I wanted to read the value entered in the text box in one of my HTML form, for this I tried jQuery val() method, but it is not working, any idea why?
HTML:
<form method="POST" id="payment-form">
<p>
<label class="card-number" for="txt_cardno"><span>Card Number:</span></label>
<input type="text" size="20" autocomplete="off" class="card-number" id="txt_cardno" name="cardno" />
</p>
<p class="submit submit-button"><a class="btn" href="#">Charge Card</a><br><a class="btn" href="#" onClick="return false">Go Back</a></p>
<div class="clear"></div>
</form>
Javascript:
$(document).ready(function() {
$(".submit").live("click", function(e) {
e.preventDefault();
var card_num = $('.card-number').val();
alert(card_num);
});
});
the jsfiddle is http://jsfiddle.net/74neK/1/
Use the id to access it (faster):
var card_num = $('#txt_cardno').val();
You've given both the <label> and the <input> the "card-number" class.
Specify the input in the selector. Otherwise .val() gives you the value of the first element found (the label).
var card_num = $('input.card-number').val();
http://jsfiddle.net/74neK/3/
If you're really concerned with micro-optimization, you should use native methods:
var card_num = (document.getElementById('txt_cardno')||{}).value;
http://jsfiddle.net/74neK/5/
Your <label>'s class is the same as your <input>'s, so jQuery is trying and failing to retrieve the value of your <label>. Instead, refer to your <input> by name or id:
$('#txt_cardno').val()
I would recommend ID regardless, because jQuery optimizes it to document.getElementById, which is much faster.
Try to use the ID to access the element:
var card_num = $('#txt_cardno').val();
http://jsfiddle.net/74neK/4/ <- Example
Select the id of your input element, as opposed to the class: http://jsfiddle.net/btgxu/