Create a simple button using Javascript

Hi All,

I would like to know whether it is possible to create a simple button using javascript. i know that text fields can be created using Javascript. any help would be great.

Humaira

you need to be more specific…

Yes, you create a button just like you would a textfield. What’s the difference?

<input type=“text” />

vs.

<input type=“button” />

Hi

Sorry for not being specific before i have finally managed to create a button but I am unable to attach a onclick event to the button. I have tried several possibilities: The code is as follows:

function Hi()
{
alert(“psst”);
}

function addRowToTable()
{
var tbl = document.getElementById(‘secondtable’);
var lastRow = tbl.rows.length;
// if there’s no header row in the table, then iteration = lastRow + 1
var iteration = lastRow;
var row = tbl.insertRow(lastRow);
var cell1 = row.insertCell(0);

var buttonnode= document.createElement('input');
buttonnode.setAttribute('type','button');
buttonnode.setAttribute('name','sal');
buttonnode.setAttribute('value','sal');
cell1.appendChild(buttonnode);
buttonnode.attachEvent('OnClick',Hi());

}

The problematic line is as follows:

buttonnode.attachEvent(‘OnClick’,Hi());
When using the above line I get an error type mismatch

i have also tried using

buttonnode.setAttribute(‘OnClick’,Hi());

In the above case even before the button is created function Hi gets executed so it does not wait for the created button to be clicked.

Any help would be great. Thanks for the previous feedback

Humaira

how about


function Hi()
{
alert("psst");
}

var buttonnode= document.createElement('input');
buttonnode.setAttribute('type','button');
buttonnode.setAttribute('name','sal');
buttonnode.setAttribute('value','sal');
cell1.appendChild(buttonnode);

//New Part here
buttonnode.onClick = Hi;

Hi

I have tried your suggestion without the brackets it does not enter the function hi when the button is created or when I click on the button. However when I have inserted the brackets it does the same as before(enters the hi function when it creates the button).

Tried the following
buttonnode.onClick = Hi;
buttonnode.onClick = Hi();

thats weird, cuz I double checked my answer in the o’reilly DHTML reference, and it seems it should work…

There are two things wrong with this line:

buttonnode.attachEvent(‘OnClick’,Hi());

1)js is case sensitive, so ‘OnClick’ is incorrect–it should be ‘onclick’. In an onclick event that is inline in the html:

<input type"button" value=“click me” OnClick=“my_func()” />

you can use OnClick, ONCLICK, or even OnClIcK because HTML is case insensitive.

  1. There is a difference between a reference to a function and a function. This is a function:

my_func()

This a reference to the same function:

my_func

Note the absence of the function execution operator ‘()’. If you look at the format for attachEvent(), it requires a function reference, i.e. no function execution operator should follow the function name.

The function execution operator tells js to immediately execute a function and store the return value. That is not what you want. You want to store the function, and have it execute some time later, so you need to use a function reference. Once again, html plays by different rules, so when your function is inline in the html, the format is:

OnClick=“my_func()”

and the function execution operator does not cause the function to execute immediately.

This is a mistake that probably everyone makes at some point:

buttonnode.setAttribute(‘OnClick’,Hi());

events are not considered attributes, so that just plain won’t work

well i am not a js expert, but event handlers can be assigned as object properties…

Who said they couldn’t be? Your code creates an ‘onClick’ property and assigns an even handler to it–which is not executed ‘onclick’ becasue onClick and onclick are different properties. js executes the ‘onclick’ property when a user clicks on the button.

yeah sorry, i posted that because i misread your previous post :slight_smile:
then i removed the post…

Just want to say thank you I have finally found a soloution which i will post at bottom for anyone who is intrested. I have one more question though lol I have a table within html, and I have a delete button associated with each row would javascript be able to identify the row when delete button clicked upon?

solution for the onclick problem:

var buttonnode= document.createElement(‘input’);
buttonnode.setAttribute(‘type’,‘button’);
buttonnode.setAttribute(‘name’,‘sal’);
buttonnode.setAttribute(‘value’,‘sal’);
buttonnode.attachEvent(‘onclick’,Hi);
cell1.appendChild(buttonnode);

Thanks for you help guys…

Also sorry still on to that button problem if the Hi function took in a parameter how would I specify the parameter

function Hi(display)
{
alert(display);
}

var buttonnode= document.createElement(‘input’);
buttonnode.setAttribute(‘type’,‘button’);
buttonnode.setAttribute(‘name’,‘button’+3);
buttonnode.setAttribute(‘value’,‘sal’);
buttonnode.attachEvent(‘onclick’,Hi);
cell1.appendChild(buttonnode);

how would I replace this line:

buttonnode.attachEvent(‘onclick’,Hi);

would javascript be able to identify the row when delete button clicked upon?

Not if you are using attachEvent() for the delete button. Normally, inside your event handling function, the ‘this’ keyword would be the element that was clicked. So, for instance, you could do this:

function Hi()
{
alert(this.name); //sal
alert(“psst”);
}

but with attachEvent(), that’s not the case, and it is a drawback of that IE only function. If you want your script to be cross browser, you also need to use addEventListener() for Mozilla browsers.

However, it’s easier and crossbrowser to do like JRMillion suggested:


window.onload=function()
{
	//document.getElementById("b0").onclick = hi;
	var buttonnode= document.createElement('input');
	buttonnode.setAttribute('type','button');
	buttonnode.setAttribute('name','sal');
	buttonnode.setAttribute('value','sal');
	cell1.appendChild(buttonnode);

	[color="red"]buttonnode.onclick = hi;[/color]
	
};

function hi()
{
	alert(this.name);
	alert('hi');
}

Also sorry still on to that button problem if the Hi function took in a parameter how would I specify the parameter

function Hi(display)
{
alert(display);
}

You can’t specify a parameter. There are a couple of ways around that. You can do something like this:

var display;
function Hi()
{
alert(display);
}

or this:

buttonnode.onclick = relay;

function relay()
{
Hi(display);
}

…which can also be written like this:

buttonnode.onclick = function(){Hi(this, display)};

Edit:

Note that in this case, the event handler function is the anonymous function, so ‘this’ is automatically passed to that function–but not Hi(). Hi() is not the event handler function. So, you have to manually pass ‘this’ to Hi(). Inside the anonymous function, ‘this’ represents the html element that was clicked, so you need to pass ‘this’ as an argument to Hi()

could you do something like this?
(this is based on what i do in actionscript, which is similar to js)


button.stuff = 'hey';
button.onclick = Hi;

function Hi(){
    alert(this.stuff);
}


ok well here is what I am trying to do I have created a table within HTML when the delete button is clicked for a particular row I would like the specified row to be deleted and also when the user clicks on add it should add another row to the table which would also contain a delete button therefore if the button is clicked that particular row should be deleted. I therefore think that this solution wont work:

var display;
function Hi(display)
{
alert(display);
}

here is the full code it has some php too:

For the time being I am adding an extra row once one has been deleted:

<?php
session_start();
?>
<html>
<head>
<title>Select medicines</title>
<script>
function MoveOption(selectbox,number)
{
loopnumber=((number+3)*3);
//check to see which option was chosen
for (var i = 0; i < selectbox.length; i++)
{
if (selectbox.options[i].selected)
{
var selectedtext= selectbox.options[i].text;
alert(“this is selected text” +selectedtext);
var selectedvalue=selectbox.options[i].value;
}
}

var k=0;

//checks for the next empty field to insert within it
for(k=0; k<loopnumber; k++)
{
if (document.forms[1].elements[k].value ==“”)
{
alert(“hello”);
document.forms[1].elements[k].value=selectedtext;
k=loopnumber;
}
else
{
k= k+2;
}
}
}

function removerow(a){
document.getElementById(‘secondtable’).deleteRow(a);
addRowToTable();
}

function addRowToTable()
{
var tbl = document.getElementById(‘secondtable’);
var lastRow = tbl.rows.length;
// if there’s no header row in the table, then iteration = lastRow + 1
var iteration = lastRow;
var row = tbl.insertRow(lastRow);
// left cell
var cell1 = row.insertCell(0);
alert(lastRow+“hello”);
var cell2=row.insertCell(1);

var buttonnode= document.createElement('input');
buttonnode.setAttribute('type','button');
buttonnode.setAttribute('name','button'+3);
buttonnode.setAttribute('value','sal');
buttonnode.attachEvent('onclick',removerow);//require this particular row to be deleted
    cell1.appendChild(buttonnode);


    var e1= document.createElement('input');
e1.setAttribute('type','text');
e1.setAttribute('name','field'+4);
cell2.appendChild(e1);

}
</script>

</head>
<body>
<?php
print_r($_POST);
//database details
$Host = “localhost”;
$User = “root”;
$Password = “”;
$db = “MedicalCenter”;

//link to the database
$Link = mysql_connect($Host,$User,$Password) or die(“<H1>Error</H1><P>Could Not Connect To Database </FORM></BODY></HTML>”); ;
mysql_select_db($db)or die(“<H1>Error</H1><P>Could not select database </FORM></BODY></HTML>”);

//integer intialisation
$count=0;
$i=0;
$j=0;
$k=0;

//query to find the medicine names associated with a particular model and detail category
$Med_Query="select medicine.Medicine_name from medicine,medlink where medlink.MedicineID = medicine.MedicineID and medlink.CategoryID=‘26’ and

Detail_CatID =‘73’“;
echo $Med_Query;
$Med_Res = mysql_query($Med_Query)or die(”<H1>Error hhhhhh</FORM></BODY></HTML>“);
$num_medicines = mysql_num_rows($Med_Res);
while ($row = mysql_fetch_array($Med_Res))
{
//create an array of medicine names
$medicines[$i]=$row[0];
$i++;
}
echo”<form action=\“selectboxes.php\” name=\“MoveList\”>
<table =\“firsttable\”>
<tr>
<td colspan=\“2\”><b>Recommended Medicines</b></td>
</tr>
<tr>
<td width=\“12\”></td>
<td><br>
<select name=\“Enabled\” size=\“5\” multiple style=\“width: 400px;\” onDblClick=\“MoveOption(this.form.Enabled,$num_medicines)\” > “;
//put the medicines found into the select box
for ($j=0;$j< $num_medicines;$j++)
{
echo “<option value=\”$medicines[$j]\”>$medicines[$j]</option>“;
}
echo”</select>“;
$rowcount = $num_medicines +3;
echo “</table>”;
echo”</form>";

echo"<form action=\“modified_table.php\” name=\“medicine_form\” method=\“post\”>";
$textname=“field”;
$power=“mg”;
$des=“desc”;
$field=$textname.$count;

echo “<table id=\“secondtable\”>”;
echo"<tr>
<td colspan=\“2\”><b>Chosen Medicines</b></td>
</tr>“;
echo “<tr>”;
echo”<td> </td>“;
echo “<td width=\“20\”><br>”;
echo"Medicine”;
echo"</td>“;
echo “<td width=\“20\”>”;
echo"Mg”;
echo"</td>“;
echo “<td width=\“20\”>”;
echo"Amount”;
echo"</td>“;
echo “<td width=\“20\”>”;
echo"Description”;
echo"</td>“;
echo”</tr>“;
$_SESSION[‘count’]=$rowcount;
$button=“button”;
for ($k=0;$k <$rowcount;$k++)
{
$field=$textname.$count;
$mg=$power.$count;
$desc=$des.$count;
$amount=“amount”.$count;
echo “<tr>”;
echo”<td><input type=\“button\” name=\“button.count\” value=\“del\” onClick=\“removerow($count)\”></td>“;
echo “<td width=\“20\”>”;
echo”<input type=\“text\” name=\“$field\” value=\“$count\”>“;
echo”</td>“;
echo”<td width=\“20\”>“;
echo”<input type=\“text\” name=\“$mg\”>“;
echo”</td>“;
echo”<td width=\“20\”>“;
echo”<input type=\“text\” name=\“$amount\”>“;
echo”</td>“;
echo”<td width=\“20\”>“;
echo”<input type=\“text\” name=\“$desc\”>“;
echo”</td>“;
$count++;
echo”</tr>“;
}
echo”</table>“;
echo”<table>“;
echo”<tr>“;
echo”<td><br><b>Repeat Prescription<b>“;
echo”</td>“;
echo”</tr>“;
echo”<tr>“;
echo”<td><b>Repeat Number<b>“;
echo”</td>“;
echo”<td><input type=\“text\” name=\“$repeats\” value=\“0\”>“;
echo”</td>“;
echo”</tr>“;
echo”</table>";
?>

</form>
</body>
</html>

Yes…and you can always try it. :slight_smile: In js, you can add properties to any object at will. For instance, you can do this:

function Hi()
{
	alert('hi');
}

Hi.color="red";
alert(Hi.color); //red

function Bye()
{
	alert("see ya");
}

Hi.greeting = Bye;
Hi.greeting();  // see ya

This is generally what I used to attach onclick to elements …
May be of some help ?

  buttonnode.setAttribute("onclick",function(){alert('Clicked')})

This is generally what I used to attach onclick to elements …

I guess you don’t care about FF1.0. Does it work in any non IE browser?

I’m just waiting for all browser to comply with w3c :stuck_out_tongue:

And by the way I just tested it under FF1 it works !