making a calculation using JavaScript - 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();

Related

How can I make this javascript to capitilize all first letter of a field?

How can I edit this code to make "This name input field" to be "This Name Input Field"?
Can anyone give me a light? :)
EDIT: I'm really noob, I don't know nothing about javascript, just trying to edit this code to get first letters capitilized.
function wpf_dev_capitalize() {
?>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery( '.wpforms-field.capitalize input' ).keyup(function() {
jQuery(this).val(jQuery(this).val().substr(0,1).toUpperCase() + jQuery(this).val().substr(1).toLowerCase());
});
jQuery( '.wpforms-field.capitalize textarea' ).keyup(function() {
jQuery(this).val(jQuery(this).val().substr(0,1).toUpperCase() + jQuery(this).val().substr(1).toLowerCase());
});
});
</script>
<?php
}
add_action( 'wpforms_wp_footer_end', 'wpf_dev_capitalize', 30 );
const capitalize_first_letter = string =>{
let stringArr = string.split(' ');
return stringArr.map(word=>{
let splitWord = word.split('')
let capitalized = splitWord[0].toUpperCase();
splitWord.shift();
splitWord.unshift(capitalized)
return splitWord.join('')
}).join(' ');
}
To avoid reinventing the wheel, one possible solution is just use something like lodash (as a "standard library") in the project for every trivial cases in your project like this:
import { startCase } from "lodash";
console.log(startCase("This name input field")); // This Name Input Field

DatePicker: Select single date when using range selection

I have a range DatePicker from Primefaces.
But I also want to be able to just select one date.
But if i do so, i won't get any values, just a empty array.
This is because the internal function (which i can't modify) only returns something when two values are given. Or at least I think that.
The workaround which i thought of was just taking the first value of the array by calling it with a javascript function, but i can't access it, because the PF function has neither a function name nor a class.
Here the code of the PrimeFaces function:
if (this.isRangeSelection()) {
if (this.value && this.value.length) {
var b = this.value[0],
g = this.value[1];
d = this.formatDateTime(b);
if (g) {
d += " " + this.options.rangeSeparator + " " + this.formatDateTime(g)
}
}
}
Here is my poor javascript attempt:
<script type="text/javascript">
function getArrayValue(){
console.log("inFunction");
console.log(window.d.value[0]);
}
</script>
This is called with this:
<div class="p-field p-col-12 p-md-4">
<p:datePicker id="range" selectionMode="range"
value="#{SearchBean.range}" onblur="getArrayValue()">
</p:datePicker>
</div>
Thanks for your help in advance! :)
I just helped a friend do the same thing that sets the range to both dates being the same you can do it with this JS...
<script type="text/javascript">
function adjustDateRange(widgetVar) {
var widget = PF(widgetVar);
var dates = widget.getDate();
if (dates[0] && !dates[1]) {
dates[1] = dates[0];
widget.jq.data().primeDatePicker.updateModel(null, dates);
}
}
</script>
Then in your DatePicker...
<p:datePicker id="range"
widgetVar="wgtRange"
selectionMode="range"
value="#{SearchBean.range}"
onblur="adjustDateRange('wgtRange')">
</p:datePicker>

Special Characters Validation Not Working as expected

I'm trying to apply Regular Expression Validation to a textbox User Control and it's only working when I enter something at the end of the text in the textbox. And when I type something somewhere in the middle of the text, it's not working.
For Example: Hey Man! (When I type '!' at the end of the text, my Code's working fine)
Hey! Man! (But when I insert '!' somewhere in the middle of the text after the entire text is typed, not working)
Below is my Code:
$("textarea[id$=<%= TxtValue.ClientID %>]").keyup(function () {
var txt = $(this).val();
var regex = new RegExp('[^0-9a-zA-Z-,_.\:\s]+$');
var vldttxt = regex.test(txt);
if (txt.length > 0 && vldttxt === true) {
alert("Error");
}
var noSpclChar = txt.replace(regex, "");
this.value = noSpclChar;
});
Any help would be greatly appreciated! Thanks!
This should work. Your ending $ is what is keeping it from matching anything within the string:
$("textarea[id$=<%= TxtValue.ClientID %>]").keyup(function () {
var txt = $(this).val();
var regex = new RegExp('[^0-9a-zA-Z-,_.\:\s]+');
var vldttxt = regex.test(txt);
if (txt.length > 0 && vldttxt === true) {
alert("Error");
}
var noSpclChar = txt.replace(regex, "");
this.value = noSpclChar;
});
> Most simple code ....Special Characters Validation
function checkForm(theForm) {
var result = /^[a-z0-9\\.;,:'\\s]{1,100}$/i(theForm.data.value);
if (!result) {
alert("No legal characters entered");
}
return !!result;
}

Changing values with jQuery

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>

Find ID in String using match

I'm building a widget that will generate a graph for an element when it is double clicked on the page. Without remaking all widgets this is the only way for me to tackle the problem.
I want find the ID of a widget from the html of an element.
All widgets I want to work are inside a div element panel_content_id_#
I want to find the number found on the line of code
var io_id=32715;
How can I search the string for this pattern and get the number (32715).
$('div[id^="panel_content_id_"]').dblclick(function(e){
console.log($(this).attr('id'));
var code = $(this).html();
// Find ID
var id = -1;
var search = code.match("var io_id=");
if(search > -1){
}
console.log($(this).html());
});
The line of code im looking for will look like so
var io_id=xxxxx;
Where xxxxx = some random number I dont know
I want to find xxxxx
Split it in two parts - All the code before the var io_id= and the other part is after that.
And then you know that the line ends with ;, so from that second part you cut of the stuff that is before the semicolon.
CODE
$('div[id^="panel_content_id_"]').dblclick(function(e){
console.log($(this).attr('id'));
var code = $(this).html();
// Find ID
var id = -1;
if (code.indexOf("var io_id")>-1) {
id = parseInt(code.split("var io_id=")[1].split(";")[0]);
}
if(search > -1){
console.log("The code betrayed me");
}
console.log("The id is: " +id);
});
Maybe you could try this regex pattern:
\d+(?! var io_id=)
Used like this:
$('div[id^="panel_content_id_"]').dblclick(function(e) {
console.log($(this).attr('id'));
var code = $(this).html();
// Find ID
var id = -1;
var search = code.match("var io_id=");
if (search) { // Edited
// New code
alert(code.match(/\d+(?! var io_id=)/gim));
}
console.log($(this).html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="panel_content_id_32715">
Div content
<br><br>
var io_id=32715;
</div>

Categories

Resources