I am trying to add/subtract from a number inside a span tag. This is depenent on a checkbox. Here is the jquery I'm trying:
//If checked
var $newprice = $("#totalprice").val() + 299;
$("#totalprice").text($newprice);
//If NOT checked
var $newprice = $("#totalprice").val() - 299;
$("#totalprice").text($newprice);
If I check the box, it adds 299, but unchecked changes the number to -299.
For span you need to use text() method to get content not val(). In both case val() returns an empty string. In first case just string concatenation will be happen. In second case it will be "" - 231 which results -231, where the empty string act as 0.
So you can use text() with callback which hold index and old value, parse the old value and add or subtract value and return it for update.
//If checked
var $newprice = $("#totalprice").text(function(i,v){
return parseInt(v,10) + 299;
});
//If NOT checked
var $newprice = $("#totalprice").text(function(i,v){
return parseInt(v,10) - 299;
});
You have to do this in change event of your checkbox:
$(':checkbox').change(function() {
if (this.checked) {
//If checked
var $newprice = +$("#totalprice").text() + 299;
$("#totalprice").text($newprice);
} else {
//If NOT checked
var $newprice = +$("#totalprice").text() - 299;
$("#totalprice").text($newprice);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
<input type='checkbox'>
<span id='totalprice'>0</span>
</p>
+$("#totalprice").text() leading + would turn the text to number.
Related
how to check if the text exists in text box jquery
I need to check if the text exists in the input box,if checking text is not exist thend append new data
I have tried with below code
$(document).ready(function(){
$("#item_inv_desc").change(function(){
var item_inv_desc = $('select[name=item_inv_desc]').val();
if (item_inv_desc == 7)
{
var invoice_number = "123456789";
//I need check if text "CRN" exists in text box
var data=$('#invoice_number:contains("CRN")')
if(data)
{
//if text "CRN" exist no need to append data
}
else
{
//if not exist
$("#invoice_number").val(invoice_number+"CRN");
}
}
});
})
//Html
<input type="text" id="invoice_number" value="">
I am having problem when try to insert append value it adds extra CRN number to invoice number,I need to avoid duplicating,
Try includes() with the val() of the text box:
var data = $('#invoice_number').val().includes("CRN")
or, for older browsers, use indexOf():
var data = $('#invoice_number').val().indexOf("CRN") !== -1
Working Demo:
$(document).ready(function() {
$("#invoice_number").change(function() {
var invoice_number = "123456789";
var data = $('#invoice_number').val().includes("CRN");
if (data) {
} else {
$("#invoice_number").val(invoice_number + "CRN");
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="invoice_number" value="">
You can use regex to remove all the digits and get the text only from the value of the input text. If you want that on button click then add that block of code inside the click function:
var data = $('#invoice_number').val();
var res = data.replace(/[0-9]/g, '');
console.log(res);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="invoice_number" value="123456789CRN">
#Manjunath
var data=$('#invoice_numbe:contains("CRN")')
"r" is missing when you are checking below
var data=$('#invoice_numbe:contains("CRN")')
and use
var data=$('#invoice_number').val().indexOf("CRN");
if(data>-1){
// donot add CRN
}
I have a input checkbox that act as a category filter. I want to store only those values of input checkboxes in an array that are checked in a var checkedAttr. Then do a test if any of the already existing values match any in the array and if it does delete it. The problem I'm having is that... when an input checkbox is clicked, it will store it as many times as the $each loop goes or input checkboxes there are, in this case (three times). I also noticed when unchecking more than one, then rechecking the same one, it will add the values as many times as the $each loop goes and will somehow bypass deleting from the array. I just want to simply add (checked values) / delete (unchecked values) from the array every time the user checks or unchecks.
Here's a jsfiddle.
HTML:
<div id="category-list">
<h1>Categories</h1>
<input class="categories" type="checkbox" name="filter" value="Math" checked>Math<br/>
<input class="categories" type="checkbox" name="filter" value="Science" checked>Science<br/>
<input class="categories" type="checkbox" name="filter" value="Reading" checked>Reading
</div>
jQuery:
var checkedAttr = []; // array for checked attributes
// change event listener for whenever one or more of the following checkboxes have been checked/unchecked
$('#category-list :checkbox').change(function()
{
var value = $(this).val();
if($(this).is(':checked')) // checked
{
console.log(value + ' is now checked!!!!!!!!!!!!!!!!!!!!!!!!');
$('#category-list :checkbox').each(function(i, item){ // loop thru the input checkboxes
if(!(value === $(item).val())) // check if the current value does NOT match that already stored in array
{
checkedAttr.push(value); // add value to array
console.log("checkedAttr:", checkedAttr);
}
else // if it does match...
{
checkedAttr.splice(i, 1);// remove it from array
console.log("checkedAttr:", checkedAttr);
}
});
// check which attributes are checked and store in 'checkedAttr' array
//$('input[name=filter]').each(function(i, item){
//});
}
else // unchecked
{
console.log(value + ' is now unchecked!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
}
});
Check it Brother its working as you want
var checkedAttr = [];
$('#category-list :checkbox').change(function()
{
checkedAttr = [];
$('#category-list :checkbox').each(function(i, item){
if($(item).is(':checked'))
{
checkedAttr.push($(item).val());
}
});
console.log("checkedAttr:", checkedAttr);
});
You can also check it in JSFiddle
https://jsfiddle.net/xdrLra77/
You can do it simply with a mapcall
var checkedAttr = [];
$('#category-list :checkbox').change(function() {
checkedAttr = $('#category-list :checked').map(function(){
return $(this).val();
}).get();
console.log(checkedAttr);
});
(Updated jFiddle)
(Edit: better yet, put the condition in the jQuery selector)
Edited
var checkedAttr = []; // array for checked attributes
//first load, see what is checked
$('#category-list :checkbox').each(function(){
if($(this).is(':checked')) // checked
checkedAttr.push($(this).val())
})
// change event listener for whenever one or more of the following checkboxes have been checked/unchecked
$('#category-list :checkbox').change(function()
{
var value = $(this).val();
var position = checkedAttr.indexOf($(this).val());
if($(this).is(':checked')) // checked
{
if(position == -1){ // dnot exist in array, add
checkedAttr.push($(this).val());
console.log("checkedAttr:", checkedAttr);
}else{ // exist in array, do nothing
//do nothing
}
console.log(value + ' is now checked!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
}
else // unchecked
{
if(position == -1){ // dont exist in array, do nothing
//do nothing
}else{ // exist in array, remove
checkedAttr.splice(position,1);
console.log("checkedAttr:", checkedAttr);
}
console.log(value + ' is now unchecked!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
}
});
You can get the checked elements by using $('.categories:checked'). Then you may iterate through those values to get the actual values
var checkedValues= $('.categories:checked');
var valuesArray=[];
$.each(checkedValues, function(checkedValue){
valuesArray.push(checkedValue.value)
}
Use $.inArray:
if (index === -1 && $(this).is(':checked')) {
checkedAttr.push(value); // add value to array
console.log("added:", checkedAttr);
} else if (index !== -1 && ! $(this).is(':checked')) {
checkedAttr.splice(index, 1);// remove it from array
console.log("removed:", checkedAttr);
}
Amended fiddle: https://jsfiddle.net/o1rmz1o1/4/
I'm trying to increment the value of an input type="number" element using jQuery. However I currently have it so that every time I press the add button it appends 1 to the value so I get a value like 1111 etc etc...
I was able to do it fine when it was set to type=text but it was not ideal as I was trying to increment the values so all that was happening was the counter was being appended to the value of the input box. Output was like this 01 02 03 04.
Currently, I'm doing this:
HTML
<input type="number" class="qty" id="book-qty" disabled/>
<span class="add">ADD</span>
jQuery
var count = 0;
$('.minus').click(function () {
if (count - 1 >= 0) {
count = parseInt($(this).parent().find('#book-qty').val());
count = count - 1;
$(this).parent().find('#book-qty').val(count);
} else {
alert('Nothing to take away!');
}
});
$('.add').click(function () {
count = $(this).parent().find('#book-qty').val();
count = count + 1;
$(this).parent().find('#book-qty').val(count);
});
I have a JSFiddle I'm working on here:
https://jsfiddle.net/javacadabra/L1sLr921/
Does anyone know?
jsfiddle demo
you need to parse the value to an integer otherwise it get treated as a string so it will concatenate instead of add together.
count = parseInt($('#book-qty').val());
Also you need to specify a default value for your inputs like stated by Mex.
Set the default value to 0 with "value=0" on the input type=number.
Then use:
count = parseInt(count) + 1;
instead of:
count = count + 1;
I am managing to check the value inside a postcode input field using the following:
html:
<input type="text" class="cart-postcode2" size="10" tabindex="22">
JQuery:
$('.cart-postcode2').keyup(function(){
var value = $(this).val();
if (value.indexOf('BT') >= 0) {
alert("is ireland");
}
})
This is working great however I want it to only alert if it starts with BT and does not contain BT in any part of the value, does anyone know if this is possible?
So typing BT2 9NH will alert "Ireland" but typing OX2 8BT will not
You can check if string starts with BT, as indexOf() will give index zero if value stats with BT
$('.cart-postcode2').keyup(function(){
var value = $(this).val();
if (value.indexOf('BT') == 0) {
alert("is ireland");
}
})
a regex solution:
$('.cart-postcode2').keyup(function(){
var value = $(this).val();
if (value.match(/^BT/)) {
alert("is ireland");
}
})
I have several textfields which will populate a text area.
I managed to populate it with a javascript function. On the onblur event of a textfield, the value of the textfield is passed and the textarea is field with this value.
However, my problem is the following:
If I modify a previously filled textfield, the textarea will simply append it again.
What I need is some functionality that if:
1: If I give focus to the textfield which is already been filled and I don't modify it, it will not be appended (I implemented this with an if statement and substring.
2: If I modify a previously filled textfield, the text area DOES NOT append it again at the end of the string BUT it replaces the part of the textarea with just that text field new value.
Take for instance the following 2 textfields:
<input type="text" id="txtName" name="txtName" />
<input type="text" id="txtSurname" name="txtSurname" />
If I fill up these textfields with John and Doe respectively, the textarea value will become:
txtName=John,txtSurname="Doe"
I managed to implement this.
What I need is that if I edit txtName from John to Alex, the textarea value will be as follows:
txtName=Alex,txtSurname=Doe
and not like is currently being displayed, i.e.
txtName=John,txtSurname=Doe,txtName=Alex
Should I achieve this by using an array which will store all the textfields values?
Any help would be greatly appreciated.
Many thanks in advance.
the following code should work for you. I have wrapped the textboxes inside a div. and also registered a onkeyup event on both the textboxes.
The javascript code iterates through each textboxe inside the div, and prints its name and value in the textarea.
HTML
<div id="textBoxContainer">
<input type="text" id="txtName" onkeyup="UpdateTextArea();" name="txtName" />
<input type="text" id="txtSurname" onkeyup="UpdateTextArea();" name="txtSurname" />
</div>
<textarea id="textAreaResult"></textarea>
Javascript
<script type="text/javascript">
function UpdateTextArea() {
var textBoxContainerDiv = document.getElementById("textBoxContainer");
var textboxes = textBoxContainerDiv.getElementsByTagName("input");
var finalResult = "";
var textAreaFinalResult = document.getElementById("textAreaResult");
for (var i = 0; i < textboxes.length; i++) {
finalResult = finalResult + textboxes[i].id + "=" + textboxes[i].value + ",";
}
textAreaFinalResult.value = finalResult;
}
</script>
Hope this Helps! :)
For the record, I feel like this code is an ugly hack, but it should do the trick...
var fieldName = "txtName"; //your field name
var newValue = "Alex"; //your new value
var value = document.getElementById("my-textarea").value;
value = "," + value; //add a comma so we can ensure we don't replace the wrong value where the fieldname is a substring of another fieldname
if(value.indexOf("," + fieldName + "=") > 0) //see if a value is already defined
{
var index = value.indexOf("," + fieldName + "=") + fieldName.length + 2;
var start = value.substring(0, index); //get the portion before the value
var end = value.substring(index); //get everything else
if(end.indexOf(",") > 0)
{
end = end.substring(end.indexOf(",")); //remove the value by reducing the end to the location of the next comma
}else{
end = ""; //if there isn't another comma it was the last value in the list, so set the new end to nothing
}
value = start + newValue + end;
value = value.substring(1); //remove the starting comma we gave it
document.getElementById("my-textarea").value = value;
}else{
//append it to the end as you are already doing
}