i used this code but some thing wrong.
i show only last three number show using php in javascript.
var number = "678342345"
function substr() {
var numbersub = <?php
$rest = substr(number, -3);
echo $rest;
?>
document.getElementById("nember").innerHTML = numbersub;
};
<button class="buttonsa" onclick="substr()">Show Number</button>
<br>
<div id="nember"></div>
var number = "678342345";
Thats a variable in javascript (on the client). You can't access it in PHP (on the backend). But you could just do the same you did in php in js:
var numbersub = number.substr(-3);
Or you have to move number to the backend.
If you want to show the the last three number only:
let number = "678342345"
document.getElementById("mybutton").addEventListener('click', function() {
let str = number.toString();
document.getElementById("number").innerHTML = str.substr(str.length-3);;
})
<button class="buttonsa" id="mybutton">Show Number</button><br>
<div id="number"></div>
If you want to show the number without the last three digits:
let number = "678342345"
document.getElementById("mybutton").addEventListener('click', function() {
let str = number.toString();
document.getElementById("number").innerHTML = str.substr(0, str.length-3);;
})
<button class="buttonsa" id="mybutton">Show Number</button><br>
<div id="number"></div>
Good luck.
Related
I have a project where we have a compare the original code and code written by the user. The user can code and then on button click we have to compare the written code with original code.
I have both original and new code in string
originalHtml : <html><body style='color:white;background:purple;'></body></html>
newHtml : <html> <body style="background:purple;color:white;"> </body> . </html>
Here there are 3 things to keep in mind
1) White space (should not show the difference for white space)
2) ' and " (should not compare quotes, both are valid in HTML)
3) Attribute order (should show difference only for missing attribute, ignore attributes order)
Any suggestions or alternative solution will be appreciated.
I have created a code pen for you, this will solve your problem.
https://codepen.io/bearnithi/pen/KEPXrX
const textArea = document.getElementById('code');
const btn = document.getElementById('checkcode');
const result = document.getElementById('result');
let originalHTML = `<html><head>
<title>Hello </title>
</head><body>
<p class="hello"></p>
</body>
</html>`
btn.addEventListener('click', checkCode);
function checkCode() {
let newHTMLCode = textArea.value.replace(/\s/g,"");
let oldHTMLCode = originalHTML.replace(/\s/g,"");
if(newHTMLCode === oldHTMLCode) {
console.log(true);
result.innerHTML = 'TRUE';
} else {
console.log(false);
result.innerHTML = 'FALSE';
}
}
<textarea id="code">
</textarea>
</br>
<button id="checkcode">Check Code</button>
<p id="result"></p>
You can convert all of them to one uniform and compare them.
Example:
remove all space, tab (with one space)
replace all ' to "
sort attribute.
and some rule you defined
Example cheerio to get attribute:
var cheerio = require('cheerio');
var yourString = `<html><body attr2='hi' attr1='hello' style='color:white;background:purple;'></body></html>`;
var $ = cheerio.load(yourString);
var yourAttrs = $('body')[0].attribs;
var sorted = {};
Object.keys(yourAttrs).sort().forEach(function(key) {
sorted[key] = yourAttrs[key];
});
console.log(sorted);
I have a page of items with various prices in GBP, each price is within a span with a class of price, what I would like to do is change the value of ALL the prices to that value divided by 1.2. so along the lines of
$('.price').html() / "1.2";
now i'm aware that this won't work as the format is £10,500 for example, I havent been able to find similar here but i'd like to take that £10,500 value divide it by 1.2 and have the value update to the result (£8,750). Anything I have tried thus far leaves me with NaN and i'm struggling to make progress.
Add a button for testing:
<button id="test-button">Test Currencies</button>
Add the following jQuery:
$('#test-button').on('click', function () {
// Get currency elements
var currencies = $('.price');
var newSymbol = '£';
var eRate = 0.8333;
$.each(currencies, function (index, value) {
// Change value to a number using regex
var number = Number($(this).html().replace(/[^0-9\.]+/g, ""));
// Assign new value and add number formatting
$(this).html(newSymbol + (number * eRate).toFixed(2).toLocaleString('en'));
});
});
Hope it helps.
Here you go :-)
Tested and working.
$("span").each(function()
{
var strNewString = $(this).html().replace(',','');
$(this).html(strNewString / 1.2);
});
function format_price(_input_str){
var input_str=_input_str+''; //if input integer convert to string
input_str=input_str.replace(new RegExp(' ',"g"), ''); //if exist spaces
input_str=input_str.replace(new RegExp('£',"g"), ''); //if exist simbil £
input_str=input_str.replace(new RegExp(' ',"g"), ''); //if wxist
var input_int = parseInt(input_str)||0;
if(input_int==0){ return _input_str;} //return original string
input_str=input_int+'';
var out_str='';
while(input_str.length > 3){
out_str=input_str.substr(-3)+' '+out_str;
input_str=input_str.substr(0,input_str.length-3);
}
if(input_str.length>0){out_str=input_str+' '+out_str;}
out_str='£ '+out_str;
return out_str;
}
$('.price').each(function(){
var this_price=$(this).html();
$(this).html(format_price(this_price));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="price">12345</div>
<div class="price">76 09</div>
<div class="price">4576 09</div>
<div class="price">45</div>
<div class="price">£ 12 345 678 </div>
I'm developing a program which basically just receives input from the user twice (risk carrier and sum, but that's just a placeholder to make my program less abstract), groups those two values together and then repeats the contents in a loop. See the code below.
<head>
<script type="text/javascript">
function fillArray(){
document.getElementById("danke").innerHTML = "Thanks for specifying the amount of entries.";
var numberOfEntries = parseInt(document.getElementById('input0').value);
var i = 0;
var myArrA = [];
var myArrB = [];
var x = " ";
while(i<numberOfEntries){
var neuRT = prompt("Enter a risk carrier");
myArrA.push(neuRT);
var neuRH = prompt("Enter a risk sum");
myArrB.push(neuRH);
i++;
}
for(i = 0; i<anzahlEintraege; i++){
x = myArrA[i] + " carries a risk of " + myArrB[i];
document.getElementById("test").innerHTML = x;
}
}
</script>
</head>
<body>
<h1>risk assessment</h1>
<input type="text" id="input0" />
<button type="button" onclick="fillArray()">Number of entries</button> <p id="danke"></p>
<button type="button" onclick="untilNow()">Show all entries so far</button>
<br />
<br />
<div id="test"></div>
</body>
</html>
My issues are:
1.) I want to display the array by writing into an HTML element, which I attempted in the for-loop. Pop-ups are to be avoided. How can I loop through HTML elements, such as demo1, demo2, demo3 etc.? I can't just write <p id="demo" + i></p>. What other options are there?
2.) Say I want to make use of the untilNow() function. The scope of my arrays is limited to fillArray(). Do I need to "return" the arrays to the untilNow() function as parameters?
Thanks everyone!!!
The problem with your current code is that you're replacing the html by the last value in every loop. You're using = rather than +=. So, a quick fix would be to replace:
document.getElementById("test").innerHTML = x;
by:
document.getElementById("test").innerHTML += x;
An example of how you could wrap an array of strings in HTMLElements and add them to your document (note that there are many other ways/libraries to achieve the same result):
var myStrings = ["Hello", "stack", "overflow"];
// Two performance rules:
// 1. Use a fragment to prevent multiple updates to the DOM
// 2. No DOM queries in the loop
var newContent = myStrings.reduce(function(result, str) {
var li = document.createElement("li");
var txt = document.createTextNode(str);
li.appendChild(txt);
result.appendChild(li);
return result;
}, document.createDocumentFragment());
// Actually add the new content
document.querySelector("ul").appendChild(newContent);
<ul class="js-list"></ul>
I have a javascript code which is supposed to get the content of a div. and then compare to a string and if they are equal change the content on that div.
var strs = document.getElementById('prodAvailable').innerHTML.toLowerCase();
var stra = "GS2023".toLowerCase();
if(stra == strs) {
document.getElementById('prodAvailable').innerHTML = "milk";
}
<div id="prodAvailable" class="Value"> GS2023 </div>
it doesnt work because the string in your div has spaces in the beginning and end of the string. you might want to trim the string prior to comparison.
var strs = document.getElementById('prodAvailable').innerHTML.toLowerCase().trim();
var stra = "GS2023".toLowerCase();
if (stra == strs) {
document.getElementById('prodAvailable').innerHTML = "milk";
}
<div id="prodAvailable" class="Value"> GS2023 </div>
I am utterly new to JavaScript and am trying to self-learn a few things - so be gentle.
I am trying to set a variable using document.getElementById(' ').innerHTML but I can't get it to work - I just get "undefined" returned when I try to use this variable.
All of the examples I have seen says that this should work, but it isn't and I'm at my wits' end. Any help will be greatly appreciated.
This is the code...
<script>
var str = document.getElementById('str').innerHTML;
function calc()
{
if(document.getElementById('checkbox').checked)
document.getElementById('str').innerHTML = str ;
else
document.getElementById('str').innerHTML='unchecked';
}
</script>
Checkbox: <input type="checkbox" id="checkbox" name="checkbox" onclick="calc();"/>
<div>Str: <span id="str">6</span></div>
My ultimate aim is to add a number to the variable "str" using another variable; so something like...
var str = document.getElementById('str').innerHTML;
var add = 2
function calc()
{
if(document.getElementById('checkbox').checked)
document.getElementById('str').innerHTML = str + add;
else
document.getElementById('str').innerHTML='unchecked';
}
I'm aware that I probably need to parse the str variable as an integer for this, but I've stumbled before I've even got that far.
Please help.
The value of str is determined when the page is loading (and before the element exists). I believe you want it inside calc:
function calc()
{
var span = document.getElementById('str');
var str = span.innerHTML;
var add = 2;
if(document.getElementById('checkbox').checked)
span.innerHTML = str + add;
else
span.innerHTML = 'unchecked';
}
The problem is that your span is below the script and actually str is not still there. Here is an example which works http://jsfiddle.net/krasimir/2C25E/
<script>
function calc() {
var str = document.getElementById('str').innerHTML;
var add = 2;
if(document.getElementById('checkbox').checked)
document.getElementById('str').innerHTML = parseInt(str) + add;
else
document.getElementById('str').innerHTML='unchecked';
}
</script>
Checkbox: <input type="checkbox" id="checkbox" name="checkbox" onclick="calc();"/>
<div>Str: <span id="str">6</span></div>
Also you should use parseInt to be sure that you get a Number and not a String.
if you had included the script in side the <head>tag This will work for you.
function calc() {
var str = document.getElementById('str').innerHTML;
//more code
Try this, a working version and a bit optimised:
var str = document.getElementById('str');
var chk = document.getElementById('checkbox');
var add = 2
function calc() {
chk.checked ? str.innerHTML = parseInt(str.innerHTML) + add : str.innerHTML = 6;
}
chk.onchange = function () {
calc();
};
Demo here