JavaScript/HTML - Passing onclick button parameter to JavaScript function - javascript

I'm very new to JavaScript so I apologize if this question has an extremely obvious answer. What I'm trying to do is pass the name of a text box in HTML to a function in Javascript via an onclick button. The goal of the function is to test a given string and highlight it based on certain parameters (for my testing, it is simply length).
There are multiple weird odds and ends within the functions that I'm aware of and working on, I know the functions work as when I remove the parameters and call the code text box directly, it prints exactly what I expect it to. But I want to be able to pass multiple text boxes without needing a specific function per box.
The code I have is as follows. I've included all of it in case the mistake was made somewhere I didn't expect it to be.
<!DOCTYPE html>
<html>
<head>
<style>
.highlight {
background-color: yellow;
}
</style>
</head>
<body>
<label for="wordOne">Word One</label><br>
<input type="text" id="wordOne" name="wordOne"><br>
// Pass the value for the wordOne textbox to verify function
<button type="button" onclick="verify(wordOne,this)">Check</button><br><br>
<label for="wordTwo">Word Two</label><br>
<input type="text" id="wordTwo" name="wordTwo"><br>
// Pass the value for the wordTwo textbox to verify function
<button type="button" onclick="verify(wordTwo,this)">Check</button><br><br>
<p id="test"></p><br>
<p id="error"></p>
<script>
// Highlights any code in a given line.
function highlight(text,id,begin,end) {
// document.getElementById("error").innerHTML = "TEST";
var inputText = document.getElementById(id);
var innerHTML = inputText.innerHTML;
var index = innerHTML.indexOf(text)+begin;
if (index >= 0) {
innerHTML = innerHTML.substring(0,index) + "<span class='highlight'>" + innerHTML.substring(index,index+text.length) + "</span>" + innerHTML.substring(index + text.length-end);
inputText.innerHTML = innerHTML;
return string;
}
}
function verify(button,el){
var begin=1;
var end=1
var id="test";
var string = document.getElementById(button).value;
var len=string.length;
if(len>5)
{
document.getElementById(id).innerHTML = string +" "+len;
highlight(string,id,begin,end);
}
else
{
document.getElementById(id).innerHTML = string;
}
}
</script>
</body>
</html>
I apologize again if this is extremely obvious but I'm honestly not sure what I'm doing wrong. Thanks in advance for any help!

You can get the name of the textbox by the attribute
var x = document.getElementsByTagName("INPUT")[0].getAttribute("name");
And then use it in your function as
var x = document.getElementsByTagName("INPUT")[0].getAttribute("name");
function highlight(x,id,begin,end) {
// document.getElementById("error").innerHTML = "TEST";
var inputText = document.getElementById(id);
var innerHTML = inputText.innerHTML;
var index = innerHTML.indexOf(text)+begin;
if (index >= 0) {
innerHTML = innerHTML.substring(0,index) + "<span class='highlight'>" + innerHTML.substring(index,index+text.length) + "</span>" + innerHTML.substring(index + text.length-end);
inputText.innerHTML = innerHTML;
return string;
}
}
NOTE : By [0] it means the first one that is the first textbox.

Related

Appending HTML inputs using JavaScript gives "undefined" value

I have a small code trying to append values using HTML inputs to the same document.
<h2 id="myh"> Header</h2>
<input type="text" id="text">
<button onclick="func()">Append</button>
<script type="text/javascript">
var child = document.getElementById("text").value;
function func() {
var h = document.getElementById('myh');
h.insertAdjacentHTML('afterend', '<p> New Para' + toString(child) + '</p>');
}
</script>
the variable child dose not take the text value from the input, which outputted as `undefined'
image 1: typed Test
Image 2: Clicked the Button
how to get the value form the input as New ParaTest?
Code Edited using the answer.
You don't need toString() method, remove it.
Get the reference of element in the child variable and get the value the func()
var child = document.getElementById("text");
function func() {
var h = document.getElementById('myh');
h.insertAdjacentHTML('afterend', '<p> New Para: ' + child.value + '</p>');
}
<h2 id="myh"> Header</h2>
<input type="text" id="text">
<button onclick="func()">Append</button>
child variable needs to assign inside func function and don't need toString()
try this
function func(){
var h = document.getElementById('myh');
let child = document.getElementById("text").value;
h.insertAdjacentHTML('afterend','<p> New Para' + child + '</p>');
}
<html>
<body>
<h2 id="myh"> Header</h2>
<input type="text" id="text">
<button onclick="func()">Append</button>
</body>
</html>
Your variable should be global. Try taking it inside the function and then check it.
function func(){
var child = document.getElementById("text").value;
var h = document.getElementById('myh');
h.insertAdjacentHTML('afterend','<p> New Para' + toString(child) + '</p>');
}

Why does this code repeat?

This is code I've written for a class assignment. The assignment reads as follows:
"Build a function that will start the program. Please call it main().
From the main() function, call a function called getValue().
The getValue() function will get a number from the user that will be used for the next step.
Also from the main() function, call a function called getSquareRoot().
The getSquareRoot() function will get the square root of the number that was received by the user in the getValue() function.
Make sure that you display the results, including the original number and the square root of the number, to the user in an easily readable statement.
Bolding is included in the original, by the way.
Here's my code and it works, except that somehow functions are being called twice, and results are being displayed twice, with the second iteration assigning userInput a value of 0. I can't seem to identify where the 'loop' is getting fired off (beginner here). Any help would be very much appreciated; I know I'n staring at it but it's totally eluding me.
<html lang="en">
<head>
<title>Project 3 Part A</title>
<meta charset="utf-8">
<script>
function main()
{
var msg1="";
var msg2="";
var userInput = "";
getValue(userInput);
getSquareRoot(userInput);
}
function getValue(userInput)
{
var userInput = document.getElementById("userNumber").value;
return getSquareRoot(userInput);
}
function getSquareRoot(userInput)
{
squareRoot = Math.sqrt(userInput);
var msg1 = "Your original number was " + userInput + ".";
var msg2 = "The square root of " + userInput + " is " + squareRoot + ".";
document.getElementById("original").innerHTML += msg1;
document.getElementById("results").innerHTML += msg2;
}
</script>
</head>
<body>
<br>
<input type="button" id="userInputButton" onclick="javascript:main();" value="Square root input value: "/>
<input type="text" id="userNumber">
</div>
<div id="original">
</div>
<div id="results">
</div>
</body>
enter code here
You need to remember that each function should optimally have 1 purpose only. The function 'getSquaredRoot' here is in charge of both calculating the root as well as outputting the result for the user to see.
Plus as Lucky Chingi said, you're calling getSquaredRoot twice.
function main()
{
var userInput = getValue();
var squaredRoot = getSquareRoot(userInput);
var msg1 = "Your original number was " + userInput + ".";
var msg2 = "The square root of " + userInput + " is " + squareRoot + ".";
document.getElementById("original").innerHTML += msg1;
document.getElementById("results").innerHTML += msg2;
}
function getValue()
{
return document.getElementById("userNumber").value;
}
function getSquareRoot(userInput)
{
return Math.sqrt(userInput);
}
Notice how it's logically seperated now.

Generate input button with onClick function using JavaScript DOM

I use JavaScript to generate form input fields on my page. Everything works fine, except the button. I came across some problems generation the button's onClick function using DOM. You can see the code below, but on my page, there is no the onClick function as the attribute of the input button tag:
n = 1;
function generate() {
var radiomore = document.createElement("input");
radiomore.type = "button";
radiomore.name = "opt[" + n + "]";
radiomore.value = "Add more options";
radiomore.setAttribute = ('onClick',addradiomore);
var div = document.createElement("div");
div.innerHTML = "Op: " + radiomore.outerHTML + "<br/>";
document.getElementById("mydiv").appendChild(div);
n++;
}
function addradiomore() {
//here goes the function code
}
And this is what it generates on my page:
<input type="button" name="opt[1]" value="Add more options">
There is no function?!?!
P.S.
Even if I use like this it doesn't work:
radiomore.onclick = addradiomore();
You should use this:
radiomore.onclick = addradiomore;
DEMO
What about:
radiomore.onclick = function () {
addradiomore();
};

Create a inputbox which writes to textarea(php)

Just for fun am I creating a chatroom for one of my school classes.
What I'm after is a JavaScript, with a inputbox which pops up, once a button (add url) is pushed, where the user can paste a url which then gets written in the textarea.
I want this feature just so "http://" gets placed in front of the added url.
Been trying with this script (which looks correct to me... but it doesn't work)
<input type="button" id="s_5" onclick="addUrl()">
<script>
function addUrl()
{
var x;
var nettside=prompt("Type in URL:","www.example.com");
if (nettside!=null)
{
x="http://" + nettside + ";
document.getElementById("area").innerHTML=x;
}
}
</script>
yeah, the textarea it's supposed to write to:
<textarea name="txt" id="area" class="typo_vind" placeholder="......" autofocus title="Type your message here, have a great day!"></textarea>
EDIT
HTML:
<input type="button" id="s_5" onclick="javascript:formatText(addUrl())">
JS:
<script>
function addUrl()
{
var x;
var nettside=prompt("Skriv inn lenkeadressen her:","www.testtest.com");
if (nettside!="")
{
x="" + "BESKRIVELSE AV LENKEN" + "";
document.getElementById("area").value=x;
}
}
</script>
Two problems remains.
I don't want that script to clean out the textarea
I don't want the <undefined></undefined> to get added to the end
This is the result with the script as it is now:
<a href=http://www.eksempel.com>__BESKRIVELSE_AV_LENKEN__</a><undefined></undefined>
EDIT 2
Solved the problem where the script cleaned out the texarea with this:
<script>
function addUrl()
{
var x;
var nettside=prompt("Skriv inn lenkeadressen her (uten http://):","www.eksempel.com");
{
x="<a target =_blank href=http://" + nettside + ">" + "__BESKRIVELSE_AV_LENKEN__" + "</a>";
var Field = document.getElementById('area');
var val = Field.value;
var selected_txt = val.substring(Field.selectionStart, Field.selectionEnd);
var before_txt = val.substring(0, Field.selectionStart);
var after_txt = val.substring(Field.selectionEnd, val.length);
Field.value = before_txt + x + after_txt;
}
}
</script>
So now all that's missing is removal of the <undefined></undefined>-tags.
HTML: <input type="button" id="s_5" onclick="javascript:addUrl()">
SOLVED!
You should check the console of your browser - it always notifies about what error has occurred.
You have a typo in this line:
x="http://" + nettside + ";
The ending + " should be deleted.
Also, here:
document.getElementById("area").innerHTML=x;
you should use value instead (normally you do this with for elements):
document.getElementById("area").value=x;
This might not cause problems in the browser you are using, but might lead to strange behaviour under certain circumstances :).

Dynamically generating a button using DOM and editing onclick event

I trying to generate an input (type="button") and setting the onclick-Event to a function, which should hand over a parameter. The whole object should be appended to a div and thats it. Basically this is my try, but I can't see why it does not work.
I pasted the code to jsfiddle, hence its easier for you to reproduce. Click here.
What am I'm doing wrong? I'm learning it by trial and error, so please explain whats wrong. Thanks a lot!
[edit] for the case jsfiddle will be down one day, here is the code I tried to run... :)
<!doctype html>
<html>
<head>
<title>onclick event example</title>
<script type="text/javascript" language="javascript">
var i = 0;
var h = new Array();
function addButton() {
i++;
var container = document.getElementById("check0");
var h[i] = document.createElement("input");
h[i].type = 'button';
h[i].name = 'number' + i;
h[i].value = "number" + i;
h[i].id = 'number' + i;
h[i].onclick = function() {
showAlert(i)
};
container.appendChild(h[i]);
}
function showAlert(number) {
alert("You clicked Button " + number);
}​
</script>
</head>
<body>
<div id="check0">
<input type="button" value="klick mich" id="number0" onclick="addButton()"/>
</div>​
</body>
</html>
Here is the fixed fiddle for you.
var h[i] = ... is invalid JavaScript.
What you write in the "JavaScript" frame on jsfiddle is executed onload, so this code is not yet present when the HTML you provide is executed (and neither is the addButton() function).
<script>
var i = 0;
var h = new Array();
function addButton() {
i++;
var container = document.getElementById("check0");
h[i] = document.createElement("input");
h[i].type = 'button';
h[i].name = 'number' + i;
h[i].value = "number" + i;
h[i].id = 'number' + i;
h[i].onclick = function() {
showAlert(i)
};
container.appendChild(h[i]);
}
function showAlert(number) {
alert("You clicked Button " + number);
}
</script>
<div id="check0">
<input type="button" value="klick mich" id="number0" onclick="addButton()"/>
</div>​
Try using h.push(...) instead of trying to send to a non created element in the array
var x = document.getElementById('pagination');//pagination is an empty div in html
var y ='';
for(var i = 0; i <= (pageMax); i++){
y = y+"<a id ='pageNumber"+i+"' onclick='changePage("+(i+1)+");'>"+(i+1)+"</a>\n ";
} x.innerHTML=y }
i used this to make a pagination for a table. The function will create a row of numbers until button max. 'changePage("+(i+1)+"); ... will call a function and send the i index(number that the page is) of the pagenumber. also i dynamically create a id unique for each number.

Categories