Using the GetElementByClassName and GetElementById - javascript

I want to print variables in the same paragraph but on different lines. I was using this:
<p id="demo1"></p><p id="demo2"></p><p id="demo3"></p>
<button type="button" onclick="myFunction()">Try It!</button>
<script>
function myFunction()
{
var lastname="Doe";
var age=30;
var job="carpenter";
document.getElementById("demo1").innerHTML=lastname;
document.getElementById("demo2").innerHTML=age;
document.getElementById("demo3").innerHTML=job;
}
</script>
but it prints each value in a new paragraph. I tried changing to classname instead but I'm doing something wrong. Help me please. TY.
<p class="demo1, demo2, demo3"></p>
<button type="button" onclick="myFunction()">Try It!</button>
<script>
function myFunction()
{
var lastname="Doe";
var age=30;
var job="carpenter";
document.getElementByClassName("demo1").innerHTML=lastname;
document.getElementByClassName("demo2").innerHTML=age;
document.getElementByClassName("demo3").innerHTML=job;
}
</script>
Also can you use
document.getElementById("demo1").innerHTML=lastname;
and more then one id and value at then end? Something like this?
document.getElementById("demo1,demo2,demo3").innerHTML=lastname,age,job;
How can you read that correctly, I know the above not valid, but what is the correct method to do it?
Ty
Jared Moore

<p id="demo1"></p>
<button type="button" onclick="myFunction()">Try It!</button>
<script>
function myFunction()
{
var lastname="Doe";
var age=30;
var job="carpenter";
var concat = lastname + '<br />' + age + '<br />' + job
document.getElementById("demo1").innerHTML=concat;
}
</script>

The reason that the three parts are in three different paragraphs is that you have three p elements. If you want all the values to be in the same paragraph, you should use an inline element, such as span. This is what it would look like:
<p><span id="demo1"></span><span id="demo2"></span><span id="demo3"></span></p>
By the way, using innerHTML is asking for someone to hack your site; if your real code looks anything like this:
element.innerHTML = userSuppliedData
then anyone can run whatever JavaScript they want on your page by passing this:
<script type="text/javascript">
alert('All your site are belong to us.');
</script>
This is known as cross-site scripting, XSS. Instead, do this:
element.appendChild(document.createTextNode(userSuppliedData))

Related

How do I give parameters to a function in a javascript file that accesses HTML and CSS attributes?

I am trying to pass html parameters to a function in a javascript file, I tried it like this:
function func(element, value) {
element.getElementById('myelement').InnerHTML = value;
}
and then something like this:
<button type="button"
onclick="script.js.func(document, 'example')">Click Me!</button>
<p id="myelement"></p>
But it doesn't work. I'm fairly new to JavaScript so sorry if I'm not as good.
I know that script.js.anything probably wouldn't work, but I don't know how to do it.
Rather than using the HTML onclick attribute, you can use JavaScript Event Listeners:
var button = document.getElementById("mybutton");
var paragraph = document.getElementById("myelement");
function func(value) {
paragraph.innerHTML = value;
}
button.addEventListener("click", function() {
func("incredible value here");
});
<button id="mybutton">Click me!</button>
<p id="myelement"></p>
If you need to specify the parameters in the HTML itself, you can specify them with a data- attribute:
var button = document.getElementById("mybutton");
var paragraph = document.getElementById("myelement");
function func(value) {
paragraph.innerHTML = value;
}
button.addEventListener("click", function() {
var value = button.getAttribute("data-value");
func(value);
});
<button id="mybutton" data-value="some value">Click me!</button>
<p id="myelement"></p>
If the JavaScript file is included in the head of your HTML, you should be able to just call it like this:
<button type="button"
onclick="func('Testing')">Click Me!</button>
<p id="myelement"></p>
Now, as far as passing parameters into the call, you can pass things like strings, numbers, etc no problem. If you want to pass in the "document", as in your example, I would actually recommend to do that inside the JavaScript function, instead of passing it in.
function func(value) {
document.getElementById('myelement').InnerHTML = value;
}
And your HTML:
<button type="button"
onclick="func('Testing')">Click Me!</button>
<p id="myelement"></p>
In your case, using vanilla JS, I think this can resolve your issue.
I think I understand what you are trying to do with this code
<button type="button" onclick="script.js.func(document, 'example')">Click Me!</button>
You are trying to load the script.js file and then the function inside it which is func.
For that in JavaScript you have to load the file first and then you can use the JavaScript functions. Something like this:
<script type="text/javascript" src="script.js"></script> <!-- Assuming the js file is on same level as the index.html file -->
<button type="button" onclick="func(document, 'example')">Click Me!</button>
On a fundamental level, this should work. If you want to refactor or clean your code have a look at other answers.

Changing URL output of User Input with JavaScript

I'm trying to build something simple here:
a user types into an input field a url eg. http://sharepoint.com/human-resources/usa/Lists/testList/EditForm.aspx?ID=666&Source=http%3A%2F%sharepoint.com
.. hits "submit", when the URL gets spit out as a link, changing into: https://sharepointusa.com/en-us/human-resources/usa/Lists/testList/EditForm.aspx?ID=666&Source=http%3A%2F%sharepoint.com
I've been trying unsuccessfully to just spit out the whole URL, losing parameters, so I need a new approach, what is an easy vanilla javascript to just replace http://sharepoint.com/ with https://sharepointusa.com/en-us/ and leave the rest of the URL?
thanks
EDIT: 2 great answers, thank you, I adapted the first answer to my original code, while I play around with the second answer to see how it compares!:
<br>
<input type="text" id="userInput" value="Enter your text here"><br>
<input type="button" onclick="changeText2()" value="change text">
<script>
function changeText2()
{
var input=document.getElementById('userInput').value;//gets the value entered by user
const updatedUrl = input.replace('http://sharepoint.com/', 'https://sharepointusa.com/en-us/');
document.getElementById("link").href = updatedUrl;
document.getElementById("link").innerHTML = updatedUrl;
}
</script>
if you have a variable containing the full original url
const url = 'http://sharepoint.com/human-resources/usa/Lists/testList/EditForm.aspx?ID=666&Source=http%3A%2F%sharepoint.com';
then you can just do
const updatedUrl = url.replace('http://sharepoint.com/', 'https://sharepointusa.com/en-us/');
and updatedUrl will have what you're asking for.
It1 got it right before me! anyways, this is a more advanced representation of how to change it directly from the input fields.
<!DOCTYPE html>
<html>
<body>
<input id="demo" value="http://sharepoint.com/human-resources/usa/Lists/testList/EditForm.aspx?ID=666&Source=http%3A%2F%sharepoint.com">
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var str = document.getElementById("demo").value;
var changed = str.replace("sharepoint", "sharepointusa");
document.getElementById("demo").value = changed;
}
</script>
</body>
</html>

Button don't executes JS

I'm interested on learn about the programming world and I'm trying some basics about making simple web plugins. The thing is I'm not able to make my button run a little JS, any tip? Thanks a lot!!
<button id="button1" onclick="myFunction()">Start the script</button>
<script type="application/javascript">
document.addEventListener("button1", myFunction);
function myFunction() {
var para = document.createElement("p");
var ht1 = '<p class="pop">Working</p>';
var ht2 = '<p class="image"><img src="image.png"></p>';
};
</script>
First of all if you want that something would happen you need to write that in the function. You already wrote variables, but you did nothing with them, so nothing could happen.
Try this :
<p id="demo" onclick="myFunction()">Click me to change my HTML content (innerHTML).</p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed!";
}
</script>

How to display image using javascript

How to display an image as many times as input(number) given by the user in html using javascript? There seem to be an error in my code,dont know how to rectify.
<!DOCTYPE html>
<html>
<body>
<p>Click the button to add a new element to the array.</p>
<input type="number" id="myNumber" value="">
<button onclick="imag(c,x)">Try it</button>
<p id="demo"></p>
<script>
function imag(c,x) {
var x = document.getElementById("myNumber").value;
var c="<img src='C:/Users/Akhil/Desktop/New folder/G.jpg'/>";
var arr = [];
for (var i = 0; i < x; i++) {
arr.push(c);
document.getElementById("demo").innerHTML = arr;
}
}
</script>
</body>
</html>
Try this:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to add a new element to the array.</p>
<input type="number" id="myNumber" value="">
<button onclick="imag()">Try it</button>
<p id="demo"></p>
<script>
function imag() {
var x = document.getElementById("myNumber").value;
var c = '\<img src="http://static.guim.co.uk/sys-images/Guardian/Pix/pictures/2014/4/11/1397210130748/Spring-Lamb.-Image-shot-2-011.jpg"\/\>';
var arr = [];
for (var i = 0; i < x; i++) {
arr.push(c);
document.getElementById("demo").innerHTML = arr;
}
}
</script>
</body>
</html>
Notice that I just changed <button onclick="imag(c,x)">Try it</button> to <button onclick="imag()">Try it</button>; and I switched your apostrophes here: var c="<img src='C:/Users/Akhil/Desktop/New folder/G.jpg'/>";
You told javascript that imag() should get two variables. but you never gave the function actual variables (and you filled them inside the function). so I removed the variables from the function's deceleration.
second thing I did was change the Quotation marks and Apostrophes since HTML standards require Quotation marks for the tags' content. switching between them allows you to keep the HTML standard.
The .innerHTML property takes a string. So, you need to convert your array to a single string like this:
document.getElementById("demo").innerHTML = arr.join("");
Note that 'C:/Users/Akhil/Desktop/New folder/G.jpg' is generally not a valid URL to refer to your image so you may need to fix that too. You can read here to see how file URLs work: http://en.wikipedia.org/wiki/File_URI_scheme
And, there's no reason to pass two empty variables to your imag() function. You can change this:
<button onclick="imag(c,x)">Try it</button>
to this:
<button onclick="imag()">Try it</button>
Firstly, you call imag function with the c and x, but the code doesn't know anything about them. That's why you get a TypeError.
You should create an event handler for the click event of the button, not this inline handler, where you can pass whatever you like at values of x and c.
Check this plunk here
And lastly, the innerHTML property takes a string (HTML or plain text). But in this case it will join all your values, comma separated, because the toString method of the array is invoked. Reference here
Your variables x and c are undefined, there is nothing in it so your code breaks. This is how parameters work, you give them a value and pass them to the function, so c becomes 'hello' and x becomes 5, fiddle:
<p>Click the button to add a new element to the array.</p>
<input type="number" id="myNumber" value="">
<button onclick="imag('hello',5)">Try it</button>
<p id="demo"></p>
Javascript
function imag(c,x) {
var arr = [];
for (var i = 0; i < x; i++) {
arr.push(c);
document.getElementById("demo").innerHTML = arr;
}
}
But this is not very flexible right? So your solution is already stated in other answers. You don't pass in parameters and make the variables in the function everytime you click on the button and please stop using inline calls. It is really outdated, messy and unnecessary! Learn how to use eventhandlers.

Pass script tag value to input tag in html

I am trying to pass a particular variable value from the script tag to an input tag. But somehow it is not working.
I am trying to pass variable1 value from the below code from script tag to input tag.
So suppose variable1 value is John then this line in my code will look like this-
<input ONCLICK="window.location.href='some_url&textId=John'">
Below is the code
<html>
<head>
<title>Applying</title>
</head>
<body>
<script>
function getUrlVars() {
// some code
}
var variable1 = getUrlVars()["parameter1"];
var variable1 = unescape(variable1);
// some more code
</script>
<input ONCLICK="window.location.href='some_url&textId=variable1'">
</body>
</html>
Can anyone explain me what wrong I am doing?
Try it that way:
var variable1 = getUrlVars()["parameter1"];
variable1 = unescape(variable1);
document.getElementById('Apply').onclick = function() {
window.location.href = 'some_url&textID=' + variable1;
};
That attaches a function to the onclick event that exactly does what you want. For the initial input element simply remove the onclick attribute:
<input name="Apply" type="button" id="Apply" value="Apply" />
If you wish to perform inline functions, you need to wrap the code in an executable closure:
<input name="Apply" type="button" id="Apply" value="Apply" ONCLICK="(function() {window.location.href='your_data'})();">
As this can be largely unmaintainable, I recommend you abstract this functionality into a more organized place in your application.
(function(window, $, undefined) {
// assuming you use jQuery
$('#Apply').click(function() {
window.location.href = '';// your code
})
})(window, $);
I may be totally misunderstanding what you want to do, but I hope this helps.
The whole url parameters bit is surely unnecessary.
You can just set the value attribute in the field:
var field = document.getElementById('textfield');
var value = 'Some text';
field.addEventListener("click", function () {
this.setAttribute('value', value);
});
Here's a jsfiddle example: http://jsfiddle.net/LMpb2/
You have it inside the ' ' you need to add it into the string. So try
"window.location.href='some_url&textId='+variable1+';'"
I would change it to the following if your trying to bind the click handler to this input element:
<html>
<head>
<title>Applying</title>
</head>
<body>
<script>
function getUrlVars() {
// some code
}
var variable1 = getUrlVars()["parameter1"];
var variable1 = unescape(variable1);
document.getElementById("Apply").onclick = function() {
window.location.href='some_url&textId=' + variable1;
}
// some more code
</script>
<input name="Apply" type="button" id="Apply" value="Apply" >
</body>
</html>
I haven't tested it yet but it should work.
at onclick call a function, inside that function set window.locatio.href !
a sample
<script>
var url="www.google.com";
function myfunc(){
alert(url);
}
</script>
<input type="button" onclick="myfunc()" value="btn" >
http://jsfiddle.net/CgKHN/

Categories

Resources