Generate input button with onClick function using JavaScript DOM - javascript

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();
};

Related

Is there an error in my code or have I simply written it wrong?

I'm making a code where if you press the button after the name it will move to the other list. Pressing a button give me the error: "missing ) after argument list". I can't seem to find anything wrong in the code.
<!DOCTYPE html>
<html>
<title>Favoritter</title>
<body>
<p>Hotell</p>
<p id="hotellDiv"></p>
<p>Favoritter</p>
<p id="favDiv"></p>
</body>
<script>
let hotelliste = ["Norwegian Wild", "Stofjord Hotel", "Norefjell Ski og Spa", "Brikdalsbre Fjellstove", "Gudvangen Fjordtell"];
let favoritter = [];
skrivhliste();
skrivfliste();
function skrivhliste(){
document.getElementById("hotellDiv").innerHTML = "";
for (var j = 0; j < hotelliste.length; j++){
document.getElementById("hotellDiv").innerHTML += hotelliste[j] + "<input type=\"button\" onclick=\"leggTil("+hotelliste[j]+")\"><br>";
}
}
function skrivfliste(){
document.getElementById("favDiv").innerHTML = "";
for (var j = 0; j < favoritter.length; j++){
document.getElementById("favDiv").innerHTML += favoritter[j] + "<input type=\"button\" onclick=\"fjern("+favoritter[j]+")\"><br>";
}
}
function leggTil(hotell){
if (hotelliste.indexOf(hotell) > -1) {
hotelliste.splice(hotelliste.indexOf(hotell), 1);
}
favoritter.push(hotell);
skrivhliste();
}
function fjern(hotell){
if (favoritter.indexOf(hotell) > -1) {
favoritter.splice(favoritter.indexOf(hotell), 1);
}
hotelliste.push(hotell);
skrivfliste();
}
</script>
</html>
Look at this:
"<input type=\"button\" onclick=\"fjern("+favoritter[j]+")\">
What string are you going to end up with when you insert the value of favoritter[j]?
<input type="button" onclick="fjern(Norwegian Wild)">
There you don't have the string "Norwegian Wild", you have the variable Norwegian followed by a space followed by the variable Wild (and neither of those variables exist).
If you are programatically generating JavaScript then you need to generate the quotes that go around strings you generate.
This is hard to do well. Especially when that JS gets embedded in HTML that you are also generating on the fly. You have multiple levels of escape sequences to deal with.
Avoid generating strings like this. Use direct DOM methods instead.
For example:
Once, so it can be reused:
function clickHandler(event) {
const button = event.currentTarget;
const hotel = button.dataset.hotel;
leggTil(hotel);
}
Then inside your loop:
const button = document.createElement('input');
button.type = 'button';
button.value = 'display label';
button.dataset.hotel = hotelliste[j];
button.addEventListener('click', clickHandler);
document.getElementById("hotellDiv").appendChild(button);
Your code is ok, please make a string into onclick function like below.
Pass the value in single quotes into both onclick function.
document.getElementById("favDiv").innerHTML += favoritter[j] + "<input type=\"button\" onclick=\"fjern('"+favoritter[j]+"')\"><br>";

JavaScript/HTML - Passing onclick button parameter to JavaScript function

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.

How to add a JavaScript function to an HmlGenericControl from codebehind

From server side, I'm injecting an input and button element dynamically to client side. I also would like to inject a JavaScript function into each. The input's function should be triggered onchange and for the button's, should be onclick
This is what I've done so far:
//js definition
string script = #"<script>";
script += #" function OnCroquis0BtnClick()
{
var fileUp = $('#File');
fileUp.trigger('click');
}";
script += #"function OnCroquis0FileSelected()
{
txtBx = document.getElementById('MainContent_txtBx');
var fileUpload = document.getElementById('File');
txtBx.value = fileUpload.files[0].name;
}";
script += #"</script>";
ClientScript.RegisterClientScriptBlock(GetType(), "testScript0" ,
script);
//html elemets definition
HtmlGenericControl input = new HtmlGenericControl(),
btn = new HtmlGenericControl();
input.TagName = "input";
input.ID = lbl.Text + "File";
input.Attributes["onchange"] = "OnCroquis0Fileselected()";
input.Attributes["style"] = "display: none;";
docRequeridosMainDiv.Controls.Add(input);
btn.TagName = "button";
btn.ID = "btn";
btn.InnerText = "Anejar";
btn.Attributes["onclick"] = "OnCroquis0BtnClick(); return false";
btn.Attributes["style"] = "margin-right:2%;";
docRequeridosMainDiv.Controls.Add(btn);
They are visible and style's are being applied, but js isn't. I figured since any html attribute is added through Attributes["attri"] maybe a js function could be too.
Thanks, in advance.
Try using RegisterStartupScript instead of RegisterClientScriptBlock
Page.ClientScript.RegisterStartupScript(this.GetType(), "testscript0", script, false);
this enforces that script is executed after all the elements in the page gets loaded.
Managed to get it working. On my version, I had function names misplaced :P

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.

using the method onclick () to trigger a function that opens a window it grabs from the clicked button

<script language="JavaScript">
function goThere()
{
var the_url = window.document.form.button.value;
var good_url = fixURL(the_url);
var new_window = window.open(good_url,"new_window","menubar,resizeable");
}
function fixURL(the_url)
{
var the_first_seven = the_url.substring(0,7);
the_first_seven = the_first_seven.toLowerCase();
if (the_first_seven != 'http://')
{
the_url = "http://" + the_url;
}
return the_url;
}
</script>
</head>
<body>
<form name="the_form" onclick="goThere()"; return false;">
<input type="button" name="the_url" class="broadGroups" onClick="goThere()" value="http://en.wikipedia.org/wiki/Category:Sports"></input>
<input type="button" name="the_url" class="broadGroups" onclick="goThere()" value="http://en.wikipedia.org/wiki/Category:Film"></input>
</form>
</body>
</html>
So this code may be totally messed up, but here is what I am trying to do.
There are two buttons inside the tag. I want each to use the method onsubmit to trigger the function goThere(). How do I set it up so that the_url is set to a value that I pull from the button tag. I also want to be able to put non-url text on the button itself while allowing it to call goThere () through the method call onsubmit.
In the end it should just take the url, make sure it starts with http:// (in this case it doesnt matter because the user isn't inputting the url, but I'd like to keep it in for other purposes later on) and open it in a new window with a menubar and the resizable property.
Sorry for the long post. Any help would be greatly appreciated.
Pass in this in your goThere call. This will bring in the clicked element to your goThere function. Then you access the attributes for the clicked button.
http://jsfiddle.net/wJMgb/
onClick="goThere(this)"
function goThere(elem) {
var the_url = elem.value;
var good_url = fixURL(the_url);
var new_window = window.open(good_url, "new_window", "menubar,resizeable");
}
function fixURL(the_url) {
var the_first_seven = the_url.substring(0, 7);
the_first_seven = the_first_seven.toLowerCase();
if (the_first_seven != 'http://') {
the_url = "http://" + the_url;
}
return the_url;
}

Categories