Changing values with jQuery - javascript

I have the following:
<span class="label-info">3</span>
I have the following jquery
var replaceit = $(this).closest(':has(.label-info)').find('.label-info').text();
The value of the variable is always a single whole number but will not always be 3:
ie: 1, 2, 3, 4, 5.
I have tried this numerous ways and cannot get the value to change. My latest attempt was:
return $(this).closest(':has(.label-info)').html().replace(replaceit, (replaceit - 1));
My end result, is to subtract 1 from whatever the current value of "lable-info" is, and switch it with this new result. So a new span based on the value of 3 would become.
<span class="label-info">2</span>
How do I achieve this?
Updated Code for more clarity
html:
<div>
<span class="lable-info">3</span>
</div>
<div>
<a class="accept_friend">accept</a>
</div>
javascript:
$(document).on("click", "a.accept_friend", function() {
var checkValue = $(this).closest(':has(.name)').find('.name').text();
var removeit = $(this).closest(':has(.item)').find('.item').fadeOut();
var replaceit = $(this).closest(':has(.label-info)').find('.label-info').text();
$.ajax({
url: '/includes/accept_friend.php',
type: 'post',
data: {checkValue},
success:function(data){
return removeit;
$("a.remove_pending").text(function () {
return ('.label-info').html().replace(replacei, replaceit);
});
}
Notes:
I am not using id. I am using class. There are multiple classes with the same name. So I have to call by closest.

Getting a value from a span, subtracting it by 1 and updating the span(using jQuery):
HTML
<span class="label-info">3</span>
jQuery
var n = $(".label-info").text(),
n2 = n - 1;
$(".label-info").text(n2);
Hope it helps a bit

Please try below code
var currentVal = $(this).closest(':has(.label-info)').html();
var newValue = parseInt(currentVal - 1);
return newValue;

Hope this helps you
var replaceit = $(this).closest(':has(.label-info)').text();
$(this).closest(':has(.label-info)').text(replaceit-1);
Example fiddle https://jsfiddle.net/nzdtnoas/

You can use .text( function ) to changing text of element to another string.
$(".label-info").text(function(i, text){
return text - 1;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="label-info">3</span>

Related

making a calculation using JavaScript

Why this isn't working?
I also did this by assigning the result back to the input field but that didn't work and still this is not showing an alert which should show the result..
<script type="text/javascript">
function calculate() {
var calculateit=document.getElementById('disp');
var pluscharacter=/+/;
var matchplus=calculateit.search(pluscharacter);
var inputlength=calculateit.length;
if(matchplus!=-1 && matchplus!=0 matchplus!=inputlength) {
answer=calculateit[0]+calculateit[1];
alert("Your answer is: "+answer+" Is it?");
}
}
</script>
Your if statement isn't a valid condition. Try:
if(matchplus!=-1 && matchplus!=0 && matchplus!=inputlength)
var calculateit = document.getElementById('disp');
var matchplus = calculateit.search(pluscharacter);
calculateit is a Node doesn't have any search() method.
You're doing stuff you don't need to do - just split the string. You also need to get the innerHTML - THAT's the string. Or you can get the "value" from an input field instead. I'd trim it to get rid of the white space around the equation, though the parseInt would take care of that as well. I'd also push the answer into another div. Here's a jsfiddle:
https://jsfiddle.net/mckinleymedia/9ezky35v/2/
With this HTML:
<h3>Equation</h3>
<div id="disp">12+12</div>
<h3>Answer</h3>
<div id="answer"></div>
You can use this script:
function calculate() {
var calculateit = document.getElementById('disp').innerHTML.trim(),
numbers = calculateit.split('+'),
answerDiv = document.getElementById('answer');
if ( numbers.length > 1 ) {
answer = parseInt(numbers[0]) + parseInt(numbers[1]);
answerDiv.innerHTML = "Your answer is: <b>" + answer + "</b>, Right?";
} else {
answerDiv.innerHTML = "I can't calculate that equation.";
}
}
calculate();

Jquery adding two values together, returning sum of both values [duplicate]

This question already has an answer here:
Getting an empty value with val()
(1 answer)
Closed 7 years ago.
I am trying to add two values together, and append that value to a div. The value is saying "0" when value1 = 30 and value2 = 3.
<script>
jQuery(document).ready(function( $ ) {
var value1 = $(".value1").val();
var value2 = $(".value2").val();
var sum = addnumbers(value1,value2);
$(".sum").append(sum);
function addnumbers(value1,value2){
var sum=Number(value1)+Number(value2);
return sum;
};
});
</script>
Html is pretty evident:
<div class="value1">30</div>
<div class="value2">3</div>
<div class="sum"></div>
You should do
var value1 = $(".value1").text(); // or html (in your html both are same)
var value2 = $(".value2").text();
div doesn't have value attribute.
so either use .html() or .text()
with divs (in your case) you need to use .text() .. .val() with inputs , select
var value1 = $(".value1").text();
var value2 = $(".value2").text();
.val() only works for inputs. For any other HTML element to get the html within you can use .html() or .text()
HTML
<div class="value1">30</div>
<div class="value2">3</div>
<div class="sum"></div>
JS
$(document).ready(function() {
$(".sum").append(addnumbers($(".value1").html(),$(".value2").html()));
});
function addnumbers(value1,value2){
return (Number(value1)+Number(value2));
};
JSFiddle
I've made you a fiddle
Code:
jQuery(document).ready(function( $ ) {
var value1 = $(".value1").html();
var value2 = $(".value2").html();
function addnumbers(value1,value2){
var sum = parseInt(value1) + parseInt(value2);
return sum;
};
var sum = addnumbers(value1,value2);
$(".sum").append(sum);
});
<div class='value1'>2</div>
<div class='value2'>4</div>
<div class='sum'></div>

Get value of span element and output it

Ok, I am more than impressed that you guys took your time to answer this, thank you so much, I did not expect it. Hope well follows you.
To explain my problem, I used that fiddle tool you all had. This is the code I have:
enter code here
http://jsfiddle.net/5xzSy/1/
-What I need, is to sum up the values that get calculated in the spans : budgetI + actualI
Modified your code to : Use .text() to populate the Span and assign some value to your inputs..(Since you have used jQuery)
http://jsfiddle.net/xubam99v/
HTML Code
<pre>
<input id=primaryB type="text" value="100"></input><input id=primaryA type="text" value="100"></input><span id=primary></span><br />
<input id=spouseB type="text" value="100"></input><input id=spouseA type="text" value="100"></input><span id=spouse></span><br />
Budget: <span id=budget></span> <br />
Actual: <span id=actual></span><br />
</pre>
Javascript/jQuery Code
var primaryBValue = parseFloat($('#primaryB').val());
var primaryAValue = parseFloat($('#primaryA').val());
$('#primary').html(primaryBValue + primaryAValue);
var spouseBValue = parseFloat($('#spouseB').val());
var spouseAValue = parseFloat($('#spouseA').val());
$('#spouse').html(spouseBValue + spouseAValue);
$('#budget').text(primaryBValue + spouseBValue);
$('#actual').text(primaryAValue + spouseAValue);
listen on the change-event to sum numbers after you insert then
http://jsfiddle.net/55c5uqhc/2/
$('#primaryB,#primaryA,#spouseB,#spouseA').change(calc);
function calc() {
var primaryBValue = parseFloat($('#primaryB').val());
var primaryAValue = parseFloat($('#primaryA').val());
$('#primary').html(primaryBValue + primaryAValue);
var spouseBValue = parseFloat($('#spouseB').val());
var spouseAValue = parseFloat($('#spouseA').val());
$('#spouse').html(spouseBValue + spouseAValue);
$('#budget').html(primaryBValue + spouseBValue);
$('#actual').html(primaryAValue + spouseAValue) ;
}
You need to create a trigger upon which you populate the <span>s, also use text() instead oh html()
Here's example(probably a bad one but it's good place to start):
function:
$('input').keyup(function(e){
var spouseBValue = parseFloat($('#spouseB').val());
var spouseAValue = parseFloat($('#spouseA').val());
var primaryBValue = parseFloat($('#primaryB').val());
var primaryAValue = parseFloat($('#primaryA').val());
$('#spouse').text(spouseBValue - (-spouseAValue));
$('#primary').text(primaryBValue - (-primaryAValue));
$('#budget').text(primaryBValue - (-spouseBValue));
$('#actual').text(primaryAValue - (-spouseAValue));
});
fiddle

exclude the first string from being appended to a character

FIDDLE Example
I'm learning how to append all the data attributes from div.query elements to a url string: http://web.com?get=
With the script I can get this result:
"http://web.com?get=|Africa|Asia|Europe"
But is there any way not to have the first one coupled with "|" so that the url should be
"http://web.com?get=Africa|Asia|Europe"
I want to get that result because either http://web.com?get=|Africa|Asia|Europe
or http://web.com?get=Africa|Asia|Europe| would be invalid. Any suggestions?
JS:
$( document ).ready(function() {
$(".query").each(function() {
var div_terms = $(this).data('term'),
source = $('#main').data('source');
var x = source+'|'+div_terms;
$('#main').data('source',x);
$('.result').html(x);
});
});
HTML:
<div id="main" data-source="http://web.com?get="></div>
<div class="query" data-term="Africa"></div>
<div class="query" data-term="Asia"></div>
<div class="query" data-term="Europe"></div>
<div class="result"></div>
The easiest way is to pull all the countries to an array and join them using the pipe character.
var terms = $('.query').map( function() {
return $(this).data('term');
}).get().join('|');
var source = $('#main').data('source');
$('.result').html( source + terms );
Demo
http://jsfiddle.net/cHtT6/3/
You just need to replace the first '|' in the resulting url with an empty character ''.
Make it simple use javascript join function
$( document ).ready(function() {
var terms=[];
$(".query").each(function() {
var div_terms = $(this).data('term');
terms.push(div_terms);
});
var x = $('#main').data('source')+terms.join("|");
$('.result').html(x);
});
Fiddle here
Use an if statement to check if it's the first 'data-term'. If it is then don't use the | character. Then in the else statement you just do as you've already done
DEMO
Just Check whether end is reached like this:
$( document ).ready(function() {
var i=0;
$(".query").each(function() {
i++;
var div_terms = i==$(".query").length? $(this).data('term')+"":$(this).data('term')+"|",
source = $('#main').data('source');
var x = source+''+div_terms;
$('#main').data('source',x);
$('.result').html(x);
});
});
Here when last term is reached. Automatically only "" is appended in all other cases "|" is appended.

.clone doesn't not appear to be incrementing

this script is suppose to clone a new row of a HTML table. It does not seem to be incrementing the name, id, attributes. What am I doing wrong? The only other thing that is not working is get the value from the previous input id of #endtime_* and putting it in the cloned input id of #starttime_* although I think that is because it does seem to be incrementing as it clones a row.
<script type="text/javascript">
function MaskTime(){
var index = $("#TimeCard tbody>tr").length-1;
$('#endtime_'+index).mask("99:99 aa");
$('#starttime_'+index).mask("99:99 aa");
}
function update_rows(){
$("#TimeCard tbody>tr:odd").css("background-color", "#FFF");
$("#TimeCard tbody>tr:even").css("background-color", "#999");
}
$(document).ready(function() {
$("#addrow").click(function() {
var row = $('#TimeCard tbody>tr:last').clone(true).insertAfter('#TimeCard tbody>tr:last');
var index = $("#TimeCard tbody>tr").length-1;
var endvalue = $('#endtime_'+index-1).val();
$("td:eq(0) select").attr("name", 'type_'+index).attr("id", 'type_'+index).addClass("validate[required]").val('')
$("td:eq(1)").html(" ")
$("td:eq(2) select").attr("name", 'propid_'+index).attr("id", 'propid_'+index).addClass("validate[required]").val('')
$("td:eq(3)").html(" ")
$("td:eq(4) input").attr("name", 'starttime_'+index).attr("id", 'starttime_'+index).addClass("validate[required,custom[timeclock]]").val(endvalue)
$("td:eq(5) input").attr("name", 'endtime_'+index).attr("id", 'endtime_'+index).addClass("validate[required,custom[timeclock]]").val('')
$("td:eq(6)").html(" ")
update_rows();
MaskTime();
return false;
});
});
</script>
For the first part of your question:
It does not seem to be incrementing the name, id, attributes.
Your script isn't giving the proper context for where the tds are for which you want to modify the attribues, etc.
Here's a modification that corrects that, adding a new variable "newrow" (to reduce DOM calls) and modifying the lines of code related to td:eq(#)...
$(document).ready(function() {
$("#addrow").click(function() {
var row = $('#TimeCard tbody>tr:last').clone(true).insertAfter('#TimeCard tbody>tr:last');
var index = $("#TimeCard tbody>tr").length-1;
var endvalue = $('#endtime_'+index-1).val();
var newrow = $("#TimeCard tbody>tr:last");
newrow.children("td:eq(0)").children("select").attr("name", 'type_'+index).attr("id", 'type_'+index).addClass("validate[required]").val('')
newrow.children("td:eq(1)").html(" ")
newrow.children("td:eq(2)").children("select").attr("name", 'propid_'+index).attr("id", 'propid_'+index).addClass("validate[required]").val('')
newrow.children("td:eq(3)").html(" ")
newrow.children("td:eq(4)").children("input").attr("name", 'starttime_'+index).attr("id", 'starttime_'+index).addClass("validate[required,custom[timeclock]]").val(endvalue)
newrow.children("td:eq(5)").children("input").attr("name", 'endtime_'+index).attr("id", 'endtime_'+index).addClass("validate[required,custom[timeclock]]").val('')
newrow.children("td:eq(6)").html(" ")
update_rows();
MaskTime();
return false;
});
});
Also, I'd made a jsfiddle with the above: http://jsfiddle.net/m78UN/2/
I'm not following what you're wanting when you describe your second problem:
The only other thing that is not working is get the value from the previous input id of #endtime_* and putting it in the cloned input id of #starttime_*
...so I've not attempted to address that.
I think you can do everything you're doing in a way simpler way. I don't have your original HTML, but check this out as a possible alternative. It mainly does 3 things:
Removed IDs used for finding things
Caches selectors
Adds classes to time inputs to make them easier to reference
Removed MaskTime() function
Here's the code:
$(document).ready(function() {
var $timecard = $("#TimeCard");
var $tbody = $timecard.find("tbody");
var $rows = $tbody.children("tr");
$("#addrow").click(function(e) {
e.preventDefault(); // clearer than return false
var $lastRow = $tbody.find("tr:last-of-type");
var lastEnd = $lastRow.find(".endTime").val();
var $newRow = $lastRow.clone(true).appendTo($tbody);
var $cols = $newRow.find("td");
var index = $rows.length - 1;
$cols.eq(0).find("select").attr("name", 'type_' + index).addClass("validate[required]").val('');
$cols.eq(1).empty();
$cols.eq(2).find("select").attr("name", 'propid_' + index).addClass("validate[required]").val('');
$cols.eq(3).empty();
$cols.eq(4).find("input").attr("name", 'starttime_' + index).addClass("time startTime validate[required,custom[timeclock]]").val(lastEnd);
$cols.eq(5).find("input").attr("name", 'endtime_' + index).addClass("time endTime validate[required,custom[timeclock]]").val('');
$cols.eq(6).empty();
update_rows(); // no idea what this is
$newRow.find(".time").mask("99:99 aa"); // MaskTime() just did this
});
});

Categories

Resources