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
Related
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>
I have one textbox called main_textbox when user enter any number i call javascript
function on the onblur event of textbox and by this code
function generate_bale(){
var bale=document.getElementById("number_of_bale").value;
var boxes = "<p>";
for (var i=0;i<`bale`;i++){
boxes+="<input type='text' name='bale_numbers[]'><br><br>";
}
document.getElementById("bale_box").innerHTML = boxes;
}
I genereate number of textbox which enter in main_textbox
now suppose if i want to generate number like
1.textbox
2.textbox
3.textbox
so how to print this number in front textbox so i can identify from all generated textbox which number of textbox is
THANX in advance
for (var i=0;i<bale;i++){
boxes+= i + ". <input type='text' name='bale_numbers[]'><br><br>";
}
document.getElementById("bale_box").innerHTML = boxes;
}
Did you ment to something like that?
function generate_bale(){
var bale=document.getElementById("number_of_bale").value;
var boxes = "<p>";
for (var i=0;i<bale;i++){
boxes+="<label for='bale_"+i+"'>"+i+"</label><input id='bale_"+i+"' type='text' name='bale_numbers[]'/><br/><br/>";
}
boxes+="</p>";
document.getElementById("bale_box").innerHTML = boxes;
}
You may change the code that used to generate textbox as following:
boxes+="<label>"+ i + "<label><input type='text' name='bale_numbers[]'><br><br>";
Assuming that the following is the answer you expected,
Try this
function generate_bale(bale){
var bale=document.getElementById("number_of_bale").value;
var boxes = "<p>";
for (var i=0;i<bale;i++){
textboxNo = i+1;
boxes+=textboxNo+".textbox<input type='text' name='balue_"+textboxNo+"'><br><br>";
}
document.getElementById("bale_box").innerHTML = boxes;
}
Check the fiddle here
function generate_bale(){
var bale=document.getElementById("number_of_bale").value;
var boxes = "<p>";
for (var i=0;i<`bale`;i++){
boxes+=+i+1+".textbox <input type='text' name='bale_numbers[]'><br><br>";
}
document.getElementById("bale_box").innerHTML = boxes;
}
I have the following hunk of JS where I define var i with some PHP.
<script type="text/javascript">
var i = <?php echo $photo_count; ?>;
function updatePreview(){
var x = document.getElementById('preimage').value;
var y = document.getElementById('precapt').value;
var preview = "";
var special = document.getElementById('special').value;
i++;
preview += "<div id='smallbox"+i+"' class='smallbox'><table><tr><td rowspan='2'><img id='picture"+i+"' src='"+x+"' /><br /><input type='button' onclick='removeimg("+i+");' value='delete' /></td><td>URL: <input onchange='updateimg("+i+");' type='text' id='image"+i+"' value='"+x+"'/></td></tr><tr><td>Caption: <input type='text' id='capt"+i+"' value='"+y+"'/></td></tr></table></div><hr />";
//window.alert(preview);
//document.getElementById('special').value += "#"+x+"|"+y;
document.getElementById('preview').innerHTML += preview;
document.getElementById('preimage').value = "";
document.getElementById('precapt').value = "";
//window.alert(document.getElementById('special').value);
}
function showSubmit(){
window.alert("i = "+i);
document.getElementById('hideImg').style.display = "none";
document.getElementById('hideTags').style.display = "block";
while(i>1){
var img = document.getElementById("image"+i).value;
var capt = document.getElementById("capt"+i).value;
if(img.length>3){
document.getElementById('special').value += "#"+img+"|"+capt;
window.alert(document.getElementById('special').value);
window.alert("i = "+i);
document.getElementById('preview2').innerHTML += "<img class='postpreviewimg' src='"+img+"' />";
}
i--;
}
document.getElementById('preview').style.display = "none";
}
</script>
In the page's source I can see that PHP is defining i correctly but in the first line of showSubmit() where I alert(i) it shows i's value to be 1, unless updatePreview() is called first.
In other words.. if the pages source looks like this: var i = 36; and then I call the function showSubmit() it alerts i = 1 when it should alert i = 36
Each time updatePreview() is called i will increment from 1, instead of from 36.
Am I defining i incorrectly? Isn't that the proper way to set a global variable?
You are defining i as a global variable. So every script on the page that uses something like i=10 will change this value.
And since i is a common used variable counter name its very likely there is a script that changes it. If you use var MyPhotoCount = <?php echo $photo_count; ?>; as name its more likely to work.
Even if this other script is included before or after this script it could cause problems. The other script could be using an on ready function or any other delay that is triggered before you call ShowSubmit();
Global variables should always be unique. And you also just found the reason why its never a good idea to use them. You cannot trust their value.
UPDATE:
You are including nicEdit.js on your page and that script contains the following code (line 185 in full source):
domLoaded : function() {
if (arguments.callee.done) return;
arguments.callee.done = true;
for (i = 0;i < bkLib.domLoad.length;i++) bkLib.domLoad[i]();
},
Your i variable is changed there.
i am currently on a Google Map Version 2 (sorry using the old version and please do not suggest me to use V3 instead because this is our requirement). Basically, this page should allow the user to add a place and select the type of that place (e.g. restaurant, bar, school, etc.). These information will be added in the database and will be used for toggling. Adding the place is working now and requires to be redirected to another php page (testmap.php) so that it will display the markers in the map. But toggling needs the information from the type selected in a dropdown list. My problem is that I do not know how to "associate" the type with each marker. I do not know how to transfer the data from the "type" dropdown list.
P.S.
The fourth to the last line is the code where the address data is transferred in my addNewMarker function onSubmit.
The PHP code above it is the dropdown list which contains the possible values of the "types" as explained above.
To conclude, I need actual codes on how to get the marker type from the dropdownlist and be transferred together with the addNewMarker function so that testmap.php can use the values in the database and can be easily toggled.
Thank you so much for those who will help me!
<script type="text/javascript">
if(GBrowserIsCompatible()) {
map_compatible = true;
}
/* Initialize the map this will be called when the document is loaded from: <body onLoad="initialize_map();"> */
function initialize_map() {
if( map_compatible ) {
}
function addNewMarker(newAddress){
var set;
var lat;
var longi;
if(set==null){
set=1;
geocoder = new GClientGeocoder();
geocoder.getLatLng(newAddress, function(point){
if(!point){
alert(address + " not found");
}else{
lat = point.y;
longi = point.x;
alert("The latitude of " + newAddress + " is " + lat + " and longitude is " + longi);
default_address.push([latitude,longitude]);
location.href="testmap.php?lat="+lat+"&longi="+longi+"&set="+set+"&newAdd="+newAddress;
}
});
}
}
function getType(type){
//markertype = type;
document.write("Hello");
}
</script>
</head>
<body onLoad="initialize_map();">
<div id="main-wrapper">
<div id="main-padding">
<div id="map_canvas"></div>
<form name="markertype_form" method = "POST" action = "addMarker.php" class="form">
<?php
#$submit = $_POST['view'];
$selectedtype = '';
if(isset($_GET)){
$connect = mysql_connect("localhost","root","abc123");
mysql_select_db("mapping");
$query="SELECT id,typename FROM markertypes ORDER BY typename";
$result = mysql_query ($query);
echo "<select name='types'>";
$types = strip_tags(#$_POST['types']);
echo "<option disabled>---------------------Select---------------------</option>";
while($nt=mysql_fetch_array($result)){
$selected = false;
// check if the current value equals the value submited
if($_POST['types'] == $nt['id']){
$selected = true;
$selectedtype = $nt['typename'];
}
// show selected attribute only if $selected is true
echo "<option value='{$nt['id']}' ". ($selected ? "selected" : "") .">{$nt['typename']}</option>";
}
echo '</select>';
echo "</select>";
echo "<input type='submit' name ='view' value='View Details'>";// Closing of list box
echo '<br>';
}
?>
</form>
<form name="direction_form" onSubmit="addNewMarker(this.new_address.value); return false;" class="form">
Add markers? Enter the address and we will mark it for you: <input type="text" name="new_address" class="form-field" /><br /><br />
<input type="submit" value=" Mark this place! " class="form-submit" />
</form>
If you put an id on the types select box in your php, then you could add some lines of code to your javascript above.
Below is assuming the "types" select element has an id of "marker-type":
function addNewMarker(newAddress){
var set;
var lat;
var longi;
var e = document.getElementById("marker-type");
var mtype = e.options[e.selectedIndex].value;
if(set==null){
set=1;
geocoder = new GClientGeocoder();
geocoder.getLatLng(newAddress, function(point){
if(!point){
alert(address + " not found");
}else{
lat = point.y;
longi = point.x;
alert("The latitude of " + newAddress + " is " + lat + " and longitude is " + longi);
default_address.push([latitude,longitude]);
location.href="testmap.php?lat="+lat+"&longi="+longi+"&set="+set+"&newAdd="+newAddress+"&type="+mtype;
}
});
}
}
Please note above, that in the AddMarker function I added a new variable for "mtype" which selects the select box and gets the current option value.
Then below, where the API calls testmap.php I added the type selector and gave it the value for the "mtype" var.
Later in your testmap.php code, you just follow on by getting using:
$_GET['type']
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/