I have a form that asks a user to give a device type a name and say how many attributes they would like to assign to that device type. That form calls the below php files which uses a loop to create the desired number of attributes.
I have used the name="attribute".$i in order to be able to identify each attribute on the next php page to send the information to a database.
<?php echo $_POST['device-name']; ?>
<?php
$num=$_POST['number-of-attributes'];
$num=intval($num);
for($i=0; $i<$num; $i++) {
newAttribute($i);
}
function newAttribute($i) {
echo ("<div id=\"new-attribute\">");
echo ("<h3>New Attribute</h3>");
echo ("<label for=\"attribute".$i."\">Name</label>");
echo ("<input id=\"attribute\" type=\"text\" name=\"attribute".$i."\">");
echo ("</div>");
}
?>
However I also want the user to be able to click for example:
<div id="small-button">New Attribute</div>
and create another set of fields to define an attribute.
How would I do this?
Thanks in advance
Using javascript/jquery on the client-side:
var template = "<div class=\"new-attribute\">"
+ "<h3>New Attribute</h3>"
+ "<label for=\"attribute\">Name</label>"
+ "<input id=\"attribute\" type=\"text\" name=\"attribute\">"
+ "</div>";
$(document).ready(function() {
// The DOM has loaded
$("#small-button").on('click', function() {
// The user clicked your 'New Attribute' button
// Append a new attribute to the <body> with `template` we defined above:
$(body).append(template);
});
});
Note: I changed id="new-attribute" to class="new-attribute" since there will be more than 1.
You would need JavaScript for said job. In your HTML document, at the end of the body element add the following script element:
<script type="text/javascript">
var numberOfAttributes = 1;
function newAttributeFields(e) {
// Creates the div
var div = document.createElement('div');
div.id = 'new-attribute';
// Appends the fields
div.innerHtml = '<h3>New attribute</h3><label for="attribute' + numberOfAttributes + '">Name</label><input id="attribute" type="text" name="attribute' + numberOfAttributes + '">';
// Appends it to the body element
document.getElementsByTagName('body')[0].appendChild(div);
// Increments the number of attributes by one
numberOfAttributes = numberOfAttributes + 1;
}
var smallButton = document.getElementById('small-button');
// When the 'small button' is clicked, calls the newAttributeFields function
smallButton.addEventListener('click', newAttributeFields, false);
</script>
Related
The following function appends on-click a div containing an image, to each main div from the "edit" class.
I need to insert on-click a div into each subdiv from c.$k class. All the sub-divs from c1/c2 class have unique ids.
Basically I need to display a rrdtool created graph inside each sub-div which represents a device with unique IP. (the id of the sub-div)
In other words I need to get the id from each class c.$k div and use it as 'ipx' on var y,
then insert a new div class='graph' into each class c.$k div. So we can ignore the second parameter from my function (ipx) as it's not relevant. I need to use the "children" ids from div class='edit'.
This is the first time when I'm using jquery and any help is more than welcome.
function edit_mode(idname,ipx) {
var x = document.getElementById(idname);
$(x).toggle( "fade" );
// var subdivid = $("#idname").children("div");
var y = 'http://domain.com/index.php?ip='+ipx;
$("#"+idname+" img:last-child").remove();
$("<div class='graph'><img src='"+y+"'></div>").appendTo(x);
};
The PHP code:
$k=1;
$t="";
while($row = mysql_fetch_array($result)){
if ($row['id'] != $t) {
if ($t != "") {echo "</div>";}
echo "<div onclick=\"edit_mode('".$row['idDevice']."','".$row['IP']."')\">".$row['name']." ".$row['IP'] ."</div><br><div class=\"edit\" id=\"".$row['idDevice']."\">";
$t = $row['id'];
$k = 1;
}
echo "<div id=\"".$row['IP']."\" class=\"c".$k."\"><form method=\"post\" action=\"edit.php?idDevice=".$idDevice."\">";
.................................................................
echo "</form></div>";
$k = 1+($k % 2);
}
I've done this:
function edit_mode(idname) {
var x = document.getElementById(idname);
$(x).toggle( "fade" );
var subdivid = $.map($('#idname > div'), function(child) { return child.id; });
var y = 'http://domain.com/index.php?ip='+subdivid;
$("#"+idname+" img:last-child").remove();
var el = document.createElement('div');
el.className="graph";
el.innerHTML = '<img src='+y+'>' ;
document.getElementById(subdivid).appendChild(el);
This is doing exactly what I want, except that is working for one parent div with one child. The question would be now: how can I modify this function to work when I have dynamically created arrays of divs (idname) with children (subdivid).
Thank you
From what I can see the second parameter to edit_mode is the id of the sub div with class c.$k, so you can use it for appending the div with image
function edit_mode(idname,ipx) {
var x = document.getElementById(idname);
$(x).toggle( "fade" );
// var subdivid = $("#idname").children("div");
var y = 'http://domain.com/index.php?ip='+ipx;
$("#"+idname+" img:last-child").remove();
$("<div class='graph'><img src='"+y+"'></div>").appendTo('#' + ipx);
};
I Have to delay my redirection by few seconds. When I try to do this It is not working. I have attached my Javascript and php below. can anyone please help me to solve the problem.window location not working.
<script type="text/javascript">
// constants to define the title of the alert and button text.
var ALERT_TITLE = "Answer";
var ALERT_BUTTON_TEXT = "Ok";
// over-ride the alert method only if this a newer browser.
// Older browser will see standard alerts
if(document.getElementById) {
window.alert = function(txt) {
createCustomAlert(txt);
}
}
function createCustomAlert(txt) {
// shortcut reference to the document object
d = document;
// if the modalContainer object already exists in the DOM, bail out.
if(d.getElementById("modalContainer")) return;
// create the modalContainer div as a child of the BODY element
mObj = d.getElementsByTagName("body")[0].appendChild(d.createElement("div"));
mObj.id = "modalContainer";
// make sure its as tall as it needs to be to overlay all the content on the page
mObj.style.height = document.documentElement.scrollHeight + "px";
// create the DIV that will be the alert
alertObj = mObj.appendChild(d.createElement("div"));
alertObj.id = "alertBox";
// MSIE doesnt treat position:fixed correctly, so this compensates for positioning the alert
if(d.all && !window.opera) alertObj.style.top = document.documentElement.scrollTop + "px";
// center the alert box
alertObj.style.left = (d.documentElement.scrollWidth - alertObj.offsetWidth)/2 + "px";
// create an H1 element as the title bar
h1 = alertObj.appendChild(d.createElement("h1"));
h1.appendChild(d.createTextNode(ALERT_TITLE));
// create a paragraph element to contain the txt argument
msg = alertObj.appendChild(d.createElement("p"));
msg.innerHTML = txt;
// create an anchor element to use as the confirmation button.
btn = alertObj.appendChild(d.createElement("a"));
btn.id = "closeBtn";
btn.appendChild(d.createTextNode(ALERT_BUTTON_TEXT));
btn.href = "#";
// set up the onclick event to remove the alert when the anchor is clicked
btn.onclick = function() { removeCustomAlert();return false; }
}
// removes the custom alert from the DOM
function removeCustomAlert() {
document.getElementsByTagName("body")[0].removeChild(document.getElementById("modalContainer"));
}
function handler(var1,quizId,isCorrect,score) {
alert(var1);
//var id = parseInt(quizId);
quizId++;
var points=10;
if(isCorrect=='true'){
score=score+points;
var string_url="quiz.php?qusId="+quizId+"&score="+score;
setTimeout('window.location =string_url',5000) ;
}
else{
var string_url="quiz.php?qusId="+quizId+"&score="+score;
setTimeout('window.location =string_url',5000) ;
}
}
</script>
while($row1=mysql_fetch_array($result1)){
?><input type="radio" name="answers" value="<?php echo $row1['answers'];?>" onclick="handler('<?php echo $row1["feedback"]; ?>',<?php echo $qusId;?>,'<?php echo $row1["isCorrect"]; ?>',<?php echo $score;?>)
"/ ><?php echo $row1['answers']; ?><br/>
<?php
} ?>
The first parameter of setTimeout should be a function. Try wrapping it with an anonymous function like so:
setTimeout(function() {
window.location = string_url
}, 5000);
try this:
`setTimeout("createCustomAlert(txt);", 3000);`
I actually converted the html checkboxes into images(below is the code), now the checkboxes have 3 states one for checked, one for unchecked and one for null,
now i want to add a DRAG feature to it like if we select unchecked and drag on other checkboxes, the other checkboxes should get this value, i meam the image must be changed.
Here is an example on this link http://cross-browser.com/x/examples/clickndrag_checkboxes.php , this example is without images but i want the same thing to happen with images.
Any help will really make my day, Thanks!
here is the code:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
var inputs;
var checked = 'checked.jpg';
var unchecked = 'unchecked.jpg';
var na = 'na.jpg';
function replaceChecks()
{
//get all the input fields on the funky_set inside of the funky_form
inputs = document.funky_form.getElementsByTagName('input');
//cycle trough the input fields
for(var i=0; i < inputs.length; i++)
{
//check if the input is a funky_box
if(inputs[i].className == 'funky_box')
{
//create a new image
var img = document.createElement('img');
//check if the checkbox is checked
if(inputs[i].value == 0 )
{
img.src = unchecked;
inputs[i].checked = false;
}
else if(inputs[i].value = 1 )
{
img.src = checked;
inputs[i].checked = true;
}
else if(inputs[i].value = 2 )
{
img.src = na;
inputs[i].checked = true;
}
//set image ID and onclick action
img.id = 'checkImage'+i;
//set name
img.name = 'checkImage'+i;
//set image
img.onclick = new Function('checkChange('+i+')');
//place image in front of the checkbox
inputs[i].parentNode.insertBefore(img, inputs[i]);
//hide the checkbox
inputs[i].style.display='none';
}
}
}
//change the checkbox status and the replacement image
function checkChange(i)
{
if(inputs[i].value==0)
{
inputs[i].checked = true;
inputs[i].value = 2;
document.getElementById('checkImage'+i).src=na;
}
else if(inputs[i].value==1)
{
inputs[i].checked = false;
inputs[i].value = 0;
document.getElementById('checkImage'+i).src=unchecked;
}
else if(inputs[i].value==2)
{
inputs[i].checked = true;
inputs[i].value = 1;
document.getElementById('checkImage'+i).src=checked;
}
}
setTimeout(function(){replaceChecks();}, 0);
</script>
</head>
<form name="funky_form" action='checkkkkkkkkkkkkkkkkkkkkkkkkk.php' method='POST'>
<table id="table1" border=1px cellpadding=1px cellspacing=1px>
<tr>
<th>D/T</th>
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
<th>5</th>
<th>6</th>
<th>7</th>
<th>8</th>
<th>9</th>
<th>10</th>
<th>11</th>
<th>12</th>
<th>13</th>
<th>14</th>
<th>15</th>
<th>16</th>
<th>17</th>
<th>18</th>
<th>19</th>
<th>20</th>
<th>21</th>
<th>22</th>
<th>23</th>
<th>24</th>
</tr>
<?php
$days = array('SUN');
foreach($days as $key=>$val)
{
print "<tr>";
print"<th>$val</th>";
for($i=0; $i<24; $i++){
print "<td>";
print " <input type=\"checkbox\" id=\"${val}${i}\" name=\"sun${i}\"
class=\"funky_box\" />";
print "</td>";
}
print "</tr>";
}
$days = array('MON');
foreach($days as $key=>$val)
{
print "<tr>";
print"<th>$val</th>";
for($i=0; $i<24; $i++){
print "<td>";
print " <input type=\"checkbox\" id=\"${val}${i}\" name=\"mon${i}\"
class=\"funky_box\" />";
print "</td>";
}
print "</tr>";
}
?>
</table>
</form>
It really is quite simple, bind an event to mousedown and not click, set a variable to indicate that the button is held down and at the same time check/uncheck the current checkbox etc.
Set another event to the mouseenter event of any checkbox, then check it the mousebutton is held down, and set the state to the same as the first checkbox where the mousebutton was first pressed down.
var state = false, mouse=false;
$('checkbox').on({
click: function(e) {
e.preventDefault();
},
mousedown: function(e) {
this.checked = !this.checked;
state = this.checked;
if(e.which === 1) mouse = true;
},
mouseup: function(e) {
if(e.which === 1) mouse = false;
},
mouseenter: function(e) {
if (mouse) this.checked = state;
}
});
Here's a fiddle to show how : FIDDLE
This will still have some bugs in it, and will need some additional checks etc. but it's basically how it's done.
I'm not going to go through all your code with bits of PHP and javascript sprinkled in it, you should probably have set up a fiddle with the HTML and some images if that is what you wanted, so you'll have to figure out how and where to switch the images yourself, but that should be pretty straight forward
There are several ways to add event listeners. The following concept can also be used using jQuery (and personally what I prefer).
object = document.getElementById("objectName");
$(object).bind('dragstart', eventStartDrag);
$(object).bind('dragover', eventStartDrag);
$(object).bind('drag', eventDragging);
$(object).bind('dragend', eventStopDrag);
And there are jQuery shortcuts such as:
$(object).mousedown(eventMouseDown);
$(object) is the object you want to listen for the event. Not all browsers support event capturing (Internet Explorer doesn't) but all do support event bubbling, so I believe the most compatible code is adding the event listener without jQuery.
object.addEventListener('mousedown', eventStartDrag, false);
According to this post, the preferred way of binding an event listener to a document in jQuery is using .on() rather than .bind(), but I have not tested this yet.
Hope this helps.
I guess that jQuery Draggable and Droppable could help you.
SAMPLE CODE
One more SAMPLE without drag and drop that is more similar to your example with regular checkboxes.
I have some code that involves clicking on a button and either you are logged in and you go to the next page or you are logged out and you get an alert. I have never liked onClick inside HTML and so I would like to turn this around into clicking on the id and having the jQuery do its magic.
I understand the click function of jQuery, but I don't know how to put do_bid(".$val["id"]."); down with the rest of the Javascript. If I haven't given enough information or if there is an official resource for this then let me know.
<li class='btn bid' onclick='do_bid(".$val["id"].");'> Bid </li>
<script>
//Some other Javascript above this
function do_bid(aid)
{
var loged_in = "<?= $_SESSION["BPLowbidAuction_LOGGED_IN"] ?>";
if(loged_in=="")
{
alert('You must log in to bid!');
}
else
{
document.location.href="item.php?id="+aid;
}
}
</script>
UPDATE: This is the entirety of the Javascript code. I think none of the answers have worked so far because the answers don't fit the rest of my Javascript. I hope this helps
<script language="JavaScript">
$(document).ready(function(){
function calcage(secs, num1, num2) {
s = ((Math.floor(secs/num1))%num2).toString();
if (LeadingZero && s.length < 2)
s = "0" + s;
return "" + s + "";
}
function CountBack() {
<?
for($i=0; $i<$total_elements; $i++){
echo "myTimeArray[".$i."] = myTimeArray[".$i."] + CountStepper;";
}
for($i=0; $i<$total_elements; $i++){
echo "secs = myTimeArray[".$i."];";
echo "DisplayStr = DisplayFormat.replace(/%%D%%/g, calcage(secs,86400,1000000));";
echo "DisplayStr = DisplayStr.replace(/%%H%%/g, calcage(secs,3600,24));";
echo "DisplayStr = DisplayStr.replace(/%%M%%/g, calcage(secs,60,60));";
echo "DisplayStr = DisplayStr.replace(/%%S%%/g, calcage(secs,1,60));";
echo "if(secs < 0){
if(document.getElementById('el_type_".$i."').value == '1'){
document.getElementById('el_".$i."').innerHTML = FinishMessage1;
}else{
document.getElementById('el_".$i."').innerHTML = FinishMessage2;";
echo " }";
echo "}else{";
echo " document.getElementById('el_".$i."').innerHTML = DisplayStr;";
echo "}";
}
?>
if (CountActive) setTimeout("CountBack()", SetTimeOutPeriod);
}
function putspan(backcolor, forecolor, id) {
document.write("<span id='"+ id +"' style='background-color:" + backcolor + "; color:" + forecolor + "'></span>");
}
if (typeof(BackColor)=="undefined") BackColor = "white";
if (typeof(ForeColor)=="undefined") ForeColor= "black";
if (typeof(TargetDate)=="undefined") TargetDate = "12/31/2020 5:00 AM";
if (typeof(DisplayFormat)=="undefined") DisplayFormat = "%%D%%d, %%H%%h, %%M%%m, %%S%%s.";
if (typeof(CountActive)=="undefined") CountActive = true;
if (typeof(FinishMessage)=="undefined") FinishMessage = "";
if (typeof(CountStepper)!="number") CountStepper = -1;
if (typeof(LeadingZero)=="undefined") LeadingZero = true;
CountStepper = Math.ceil(CountStepper);
if (CountStepper == 0) CountActive = false;
var SetTimeOutPeriod = (Math.abs(CountStepper)-1)*1000 + 990;
var myTimeArray = new Array();
<? for($i=0; $i<$total_elements; $i++){?>
ddiff=document.getElementById('el_sec_'+<?=$i;?>).value;
myTimeArray[<?=$i;?>]=Number(ddiff);
<? } ?>
CountBack();
function do_bid(aid)
{
var loged_in = "<?= $_SESSION["BPLowbidAuction_LOGGED_IN"] ?>";
if(loged_in=="")
{
alert('You must log in to bid!');
}
else
{
document.location.href="item.php?id="+aid;
}
}
}</script>
If you want to attach click event handler using jQuery. You need to first include jQuery library into your page and then try the below code.
You should not have 2 class attributes in an element. Move both btn and bid class into one class attribute.
Markup change. Here I am rendering the session variable into a data attribute to be used later inside the click event handler using jQuery data method.
PHP/HTML:
echo "<li class='btn bid' data-bid='".$val["id"]."'>Bid</li>";
JS:
$('.btn.bid').click(function(){
do_bid($(this).data('bid'));
});
If you don't want to use data attribute and render the id into a JS variable then you can use the below code.
var loged_in = "<?= $_SESSION["BPLowbidAuction_LOGGED_IN"] ?>";
$('.btn.bid').click(function(){
if(!loged_in){
alert('You must log in to bid!');
}
else{
do_bid(loged_in);
}
});
First, you need to make the <li> have the data you need to send, which I would recommend using the data attributes. For example:
echo "<li class=\"btn bid\" data-bid=\"{$val['id']}\">Bid</li>";
Next, you need to bind the click and have it call the javascript method do_bid which can be done using:
function do_bid(bid){
//bid code
}
$(function(){
// when you click on the LI
$('li.btn.bid').click(function(){
// grab the ID we're bidding on
var bid = $(this).data('bid');
// then call the function with the parameter
window.do_bid(bid);
});
});
Assuming that you have multiple of these buttons, you could use the data attribute to store the ID:
<li class='btn' class='bid' data-id='<?php echo $val["id"]; ?>'>
jQuery:
var clicked_id = $(this).data('id'); // assuming this is the element that is clicked on
I would add the id value your trying to append as a data attribute:
Something like:
<li class='btn' class='bid' data-id='.$val["id"].'>
Then bind the event like this:
$('.bid').click(function(){
var dataId = $(this).attr('data-id');
doBid(dataId);
});
You can store the Id in a data- attribute, then use jQuery's .click method.
<li class='btn' class='bid' data-id='".$val["id"]."'>
Bid
</li>
<script>
$(document).ready(function(){
$("li.bid").click(function(){
if ("" === "<?= $_SESSION["BPLowbidAuction_LOGGED_IN"] ?>") {
alert('You must log in to bid!');
}
else {
document.location.href="item.php?id=" + $(this).data("id");
}
});
});
</script>
If you are still searching for an answer to this, I put a workaround.
If data is not working for you, try the html id.
A working example is here: http://jsfiddle.net/aVLk9/
i have a javascript function like this:
function addfamily(divName){
var newdiv = document.createElement('div');
newdiv.innerHTML = '<input type="text" name="family[]" size="16">';
document.getElementById(divName).appendChild(newdiv);
}
which dynamically adds textbox to the form and a php script like this:
<?php
$result_family = mysql_query("SELECT * FROM family_member where login_id='$_SESSION[id]'");
$num_rows_family = mysql_num_rows($result_family);
if ($num_rows_family>0) {
while($row_family = mysql_fetch_assoc($result_family)){
echo "<script language=javascript>addfamily('family');</script>";
}
}
having this code the textboxes are added fine.
i just need to know how can i set a dynamic value as the textbox value by passing the php variable $row_family[name] to the function and the value of the textbox???
please help
Since you want to pass the name of the Div along with $row_family['name'] your javascript function should look like
function addfamily(divName,familyName){
var newdiv = document.createElement('div');
newdiv.innerHTML = "<input type='text' name='family[]' size='16' value=" + familyName + ">";
document.getElementById(divName).appendChild(newdiv);
}
and then the call from PHP should be like
echo "addfamily('family',$row_family['name']);";
HTH