Javascript replace function in same field - javascript

My code
<!DOCTYPE html>
<html>
<body>
<input type="text" id="text" value=""><br>
<button onclick="myFunction()">Submit</button>
<script>
function myFunction() {
var str = document.getElementById("text");
var res = str.replace("1", "2");
document.getElementById("text") = res;
}
</script>
in input field i am taking some input from user on (click) submit i want to replace all 1 with 2 and i want to display result in same field but its not working..

You need to get the value
function myFunction() {
//getElementById returns dom object
var el = document.getElementById("text");
//you want to replace its value
var str = el.value;
//use a simple regex to replace all instances
var res = str.replace(/1/g, "2");
//set the value property of the target element
el.value = res;
}
Demo: Fiddle, short version

This is what you want:
function myFunction() {
var inputElt = document.getElementById("text");
var res = inputElt.value.replace("1", "2");
inputElt.value = res;
}

Your line:
document.getElementById("text") = res;
instead, should look like this:
document.getElementById("text").value = res;

Related

My JS to retrieve querystring params isn't working, any ideas why?

I'm trying to get a simple example of using js to retrieve querystring params working and it's not (even though I said simple).
Here's my code:
I've tried putting alert statements in and debugging the old fashioned way but to be honest I'm used to using VS2017 for c# not js
Here's the code I'm using.
I have 2 html pages, the first just has a link:
try me
The second has the code:
this is some text <br />
<script> getparams2();</script>
this is some more text <br />
<script>
function getUrlParam(parameter, defaultvalue) {
var urlparameter = defaultvalue;
if (window.location.href.indexOf(parameter) > -1) {
urlparameter = getUrlVars()[parameter];
}
return urlparameter;
}
</script>
<script>
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {
alert(value);
vars[key] = value;
});
return vars;
}
</script>
<script>
function getparams2()
{
var mytext = getUrlVars()["type"];
}
</script>
The result I'm trying to acheive is that the h1.html page can display the type parameter from the url.
Thanks in advance,
Paul.
Your code works. You just need to execute it when the document is ready also you need to return something or update your page to see the results.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
</head>
<body>
<div id="params"> Printing The URL Params here</div>
<script type="text/javascript">
$( document ).ready(function() {
getparams2();
function getUrlParam(parameter, defaultvalue) {
var urlparameter = defaultvalue;
if (window.location.href.indexOf(parameter) > -1) {
urlparameter = getUrlVars()[parameter];
}
return urlparameter;
}
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function
(m, key, value) {
alert(value);
vars[key] = value;
});
return vars;
}
function getparams2()
{
var mytext = getUrlVars()["type"];
//console.log(mytext);
$('#params').text(mytext);
}
});
</script>
</body>
</html>
I would do it the following way:
URL-Param function
function getUrlParam(name){
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if (results == null) { return ""; }
else { return results[1]; }
};
Call from your getParams2
function getParams2(){
return getUrlParam('type');
};
getParams2 will return the value of the param if it is in the URL.

Use slice(); method to achieve an arithmetic operation

My aim is to use a single input to collect numbers and strings then use it to determine a math operation.
For example, I parse in values such as √64 intending to find the square root of 64. Knowing that this is no valid javascript, so I decided to get the first character with result[0]; which is "√" and then slice out the remaining values with result.slice(1); which is "64", then when the condition that result[0] == "√" is true then Math.sqrt(sliceVal) . This seems perfect and runs well in a mobile editor, but doesn't run in any web browser.
function actn() {
var input = document.getElementById("input").value;
var display = document.getElementById("display");
var result = input.toString();
var firstVal = result[0];
if (firstVal == "√") {
var sliceVal = result.slice(1);
display.innerHTML = Math.sqrt(sliceVal);
}
}
I do not know why It is not running at your end but It is working perfectly according to your requirement I tested above code :)
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function actn() {
var input = document.getElementById("test").value;
var result = input.toString();
var firstVal = result[0];
if (firstVal == "√") {
var sliceVal = result.slice(1);
alert(Math.sqrt(sliceVal));
}
alert("No match found");
}
</script>
</head>
<body>
<input type="text" id="test" />
<button type="button" onclick="actn()">Test</button>
</body>
</html>
Checking ASCII value instead of character comparison should work.
<html>
<body>
<input type="text" id="input" />
<button type="button" id="sqrRoot">Square Root</button>
<h1 id="display"></h1>
<script>
function actn() {
var input = document.getElementById("input").value;
var display = document.getElementById("display");
var result = input.toString();
var firstVal = result[0];
/* Ascii value for √ is 8730 */
if (firstVal.charCodeAt(0) === 8730) {
var sliceVal = result.slice(1);
display.innerHTML = Math.sqrt(sliceVal);
}
}
document.getElementById("sqrRoot").addEventListener("click", function () {
actn();
});
</script>
</body>
</html>

Split string and in some cases remove

I've got a product title which I'm splitting and inserting a linebreak using javascript like this:
<script>
function myFunction() {
var str = "How are you - doing today?";
var res = str.split("-").join('<br>');
document.getElementById("demo").innerHTML = res;
}
</script>
This works for most case scenarios, however in some cases I will need to remove the second line completely. So everything after the - will need to be removed. Only within that element though, so if I've got this for example
<h3>This is a product - title</h3>
the result should be
<h3>This is a product</h3>
Again this only needs to apply to elements with a certain class. Anybody got any idea ow to do this?
Why not us a simple replace,
string = string.replace(/-/g, '<br>');
or for complete deletion, take
string = string.replace(/-.*$/g, '');
Check className of the element:
function myFunction() {
const str = `How are you - doing today?`
const first = str.split(`-`)[0]
const all = str.split(`-`).join(`<br/>`)
const el = document.getElementById(`demo`)
const el.innerHTML = el.className === `any-name` ? first : all
}
Try this:
(function() {
// For splitted titles
var split = document.querySelectorAll(".dash-split");
var splits = [];
split.forEach(function(spl) {
splits.push(spl.innerHTML.split("-").join("<br>"));
});
console.log(splits); // Outputs ["This is <br> split!"]
// For removed titles
var removedEls = document.querySelectorAll(".dash-split");
var removed = [];
removedEls.forEach(function(rem) {
removed.push(rem.innerText.split("-")[0].trim());
});
console.log(removed); // Outputs ["This is"]
})();
<!DOCTYPE html>
<html>
<head>
<title>Welcome!</title>
</head>
<body>
<div>
<h1 class="dash-split">This is - split!</h1>
<h1 class="dash-remove">This is - removed!</h1>
</div>
</body>
</html>
This should get you what you want, provided the script runs at the end of the document. For wrapping, it keys off of the class title-wrap.
<html>
<head></head>
<body>
<h3>This is a product - title</h3>
<h3 class="title title-wrap">This is a product - with a wrapped title</h3>
<h3>This is a product - with another title</h3>
<script>
(function() {
var titles = document.querySelectorAll('h3');
titles.forEach(function(o, i) {
var title = o.innerHTML;
if (/title-wrap/ig.test(o.className)) {
o.innerHTML = title.replace(/-/g, '<br />');
} else {
o.innerHTML = title.replace(/-.*$/g, '');
}
});
})();
</script>
</body>
</html>

How do I return this as string not html element?

How do I return this as string not html element?
<script>
function myFunction() {
var str = "<input type='text'/>";
var res = str.toString();
document.getElementById("demo").innerHTML = res;
}
</script>
Try textContent instead of innerHTML.
I had use attribute .textContent in javascript to resolve problem. Maybe it will be help a lot.
HTML
<body>
Click button to return a string of input.
<br/>
<button onclick="generate();">Try it</button>
<br/><br/>
<span id="demo"></span>
</body>
Javascript
<script>
function generate() {
var str = "<input type='text'/>";
var res = str.toString();
document.getElementById("demo").textContent = res;
}
</script>
Link for demo:
https://jsfiddle.net/hofvb4ky/1/
Refer from:
https://www.w3schools.com/jsref/prop_node_textcontent.asp

How to use Skulpt to eval Python line by line

The example given by Skulpt runs the interpreter on the whole string containing the python program:
https://github.com/skulpt/skulpt/blob/master/example/calling_from_js.html
Is there a possibility to run the interpreter line by line, for example in order to highlight the Python line which is currently executed?
Thank you in advance.
var program = "print('something')\nprint('something else')";
var programs = program.split("\n");
for(var i = 0; i<programs.length; i++){
//skulpt on `programs[i]` and highlight that line
}
Essentially you just want to do something like this:
Split the full program into a series of lines
Run each line through Skulpt individually (highlight this line as needed)
Slightly modified code from your second link:
<script src="../dist/skulpt.min.js" type="text/javascript"></script>
<script type="text/javascript">
function outf(text)
{
var output = document.getElementById("output");
text = text.replace(/</g, '<');
output.innerHTML = output.innerHTML + text;
}
function runit(prog)
{
//changed this so the function accepts an argument
var output = document.getElementById("output");
output.innerHTML = '';
Sk.configure({output:outf});
try {
var module = Sk.importMainWithBody("<stdin>", false, prog);
var obj = module.tp$getattr('a');
var runMethod = obj.tp$getattr('run');
var ret = Sk.misceval.callsim(runMethod, 10);
alert(ret.v);
} catch (e) {
alert(e);
}
}
</script>
<form>
<textarea id="code" rows="24" cols="80">
class Test:
def run(self, b):
self.a = 10 + b
return self.a
print "Hello World"
a = Test()
</textarea><br>
<button onclick="runit()" type="button">Run</button>
</form>
<pre id="output"></pre>
Then just insert this code wherever you want
var programs = document.getElementById("code").value;
for(var i = 0; i<programs.length; i++){
// Whatever code you want to use to highlight the line goes here
runit(programs[i]);
}

Categories

Resources