PHP variable to HTML textbox using Javascript - javascript

I am trying to place the PHP variable $e into HTML textbox id="textid" upon a button onclick. I have played around with various syntax, but I cannot seem to get it to work. What am I doing wrong?
<script type="text/javascript">
function ElementContent(id,content)
{
document.getElementById(id).value = content;
}
</script>
<input type="text" name="" value ="" id="textid" ;"/>
<?php
$e = "test";
echo '<button value="" class="button" onclick="ElementContent(\'textid\',\'$e\')" />';
?>

echo '<button value="" class="button" onclick="ElementContent(\'textid\',\''.$e.'\')" />Button Name</button>';
You have to concat the string, as php doesn't automatically recognise dollars+some name as a variable in single quote strings.

PHP variables will only be interpreted in strings constructed with double-quotes ("). Update your code as follows:
<button value="" class="button" onclick="ElementContent('textid', '<?php echo $e ?>')" />
As you can see, there's no need to output the whole button markup in PHP. Thus, your final code should be:
<script type="text/javascript">
function ElementContent(id,content) { document.getElementById(id).value = content; }
</script>
<input type="text" name="" value ="" id="textid" />
<?php $e = "test"; ?>
<button value="" class="button" onclick="ElementContent('textid', '<?php echo $e ?>')">Button</button>
I also took the time to fix a few issues with your markup, too.

Related

How to add value="" to input

Is there a possibility to add the value tag to an input with javascript?
e.g. to change a input fild in a form from:
<input type="text" name="mail" id="mail">
to:
<input type="text" name="mail" id="mail" value="<?php echo $_SESSION['email'] ?>
EDIT:
<?php
echo '
<script type="text/javascript">
document.getElementById("mail").setAttribute("value", "<?php echo $_SESSION["email"];?>");
</script>';
?>
Use setAttribute() to fill in the attribute of an element.
document.getElementById("mail").setAttribute("value", "<?php echo $_SESSION['email'];?>");
<input type="text" name="mail" id="mail">
You can't use <?php inside a PHP string. Use concatenation instead.
<?php
echo '
<script type="text/javascript">
document.getElementById("mail").setAttribute("value", "' . $_SESSION["email"] . '");
</script>';
?>
Yes, you can access the value field of an input with javascript
document.getElementById('mail').value = "someemail#email.com";
Not sure what you are trying to achieve but you could save PHP value as a JS variable and go from there. Something like this?
var email = '<?php echo $_SESSION['email'];?>';
document.getElementById('mail').value = email;
Using the method echo, returning the element input.
$youvalue = "This is the value of the input"
echo '<input type="text" name="mail" id="mail" value="'.$yourvalue.'">';
Using the method echo again, returning a script.
$youvalue = "This is the value of the input"
echo '<script>var x = document.createElement("input");x.type = "text";x.name = "mail";x.id = "mail";x.value = "'.$youvalue.'"; document.body.appendChild(x);</script>'

Passing multiple variables to Javascript Function

I am able to pass one variable (ID) to the javascript function, however when I go to add the businessname variable, the popupdiv does not display.
Button to displaydiv and pass ID (this works)
<input type='button' id='report-submit' value='Go' onclick='displayDiv(".$id.")'>
Javascript (works)
function displayDiv(divid) {
e=document.getElementById("zbadmin-"+divid);
strUser=e.options[e.selectedIndex].value;
if (strUser=='2') {
document.getElementById('def').style.display = "block";
document.getElementById('link-id').href="delete?id="+divid;
}
}
But when I add businessname, doesnt work
<input type='button' id='report-submit' value='Go' onclick='displayDiv(".$id.",'".$businessname."')'>
Javascript (doesnt work)
function displayDiv(divid,divbizname) {
e=document.getElementById("zbadmin-"+divid);
strUser=e.options[e.selectedIndex].value;
if (strUser=='2') {
document.getElementById('def').style.display = "block";
document.getElementById('link-id').href="delete?id="+divid+"&businessname="+divbizname;
}
}
Am I missing something very simple? I replaced it with plain text and it didnt work either.
EDIT:
Heres the code prior to the button. It grabs data from SQL table and produces a dropdown. As a test, ive put $id as both variables in the below code, it works fine and displays the popup.
while($row = mysql_fetch_array($proposal_result)) {
$date=substr($row["date"], 0, 50);
$formatted_date=date('d/m/Y', strtotime($date));
$id=substr($row["idproposal"], 0, 50);
$businessname=substr($row["businessname"], 0, 50);
$status=substr($row["status"], 0, 50);
$staff=substr($row["staff"], 0, 50);
$file_access='<storage-bucket>';
$file_name='proposal_'.$id.'_'.$businessname.'.pdf';
$file=$file_access.$file_name;
print "<tr><td>".$formatted_date."</<td><td>".$id."</td><td width='25px'><a href='".$file."'target='_blank'><img src='".$images."/attachment.png' alt='file'></a></td><td>".$businessname."</td><td>".$staff."</td><td>".$status."</td><td>
<div>
<select id='zbadmin-".$id."' name='zbadmin-".$id."' class='dropdowns' required>
<option value='0'>Select and action...*</option>
<option value='1'>Change Status for ID#".$id."</option>
<option value='2'>Delete Proposal</option>
</select>
<input type='button' id='report-submit' value='Go' onclick='displayDiv(".$id.",".$id.")'></div>
If I use the $id, $date it works fine as its grabbing numbers, but as soon as I replace the second variable with one thats a string, it doesnt display the popupdiv below:
<div id='def'>
<div id='popup'>
<form name='deletefeedback' action='' method='post'>
<!--<img id='close' src='images/3.png'> CLOSE ICON-->
<h2>Reason for deleting proposal <script>function getID() { alert($divid);window.location='?divid='+$divid';}</script></h2>
<hr>
<input id='deletereason' type='radio' name='deletereason' class='radio' value='Added by mistake'>Added by mistake<br />
<input id='deletereason' type='radio' name='deletereason' class='radio' value='Added by mistake'>No longer required<br />
<input id='deletereason' type='radio' name='deletereason' class='radio' value='Added by mistake'>Incorrect Information Provided<br />
<input id='deletereason' type='radio' name='deletereason' class='radio' value='Added by mistake'>Reason 4<br />
<textarea name='deletecomments' placeholder='Comments...'></textarea><br />
<a href='' id='link-id'><input type='button' id='report-submit' value='Delete Proposal'></a><a href='/zerobooks-admin-dashboard'><input type='button' id='report-submit' value='Cancel'></a>
</form>
</div>
</div>
You're adding a weird mix of single quotes before the second argument, get rid of those:
onclick='displayDiv(".$id.", ".$businessname.")'
Got it working. Found the answer at passing a parameter with onclick function is read as a variable when it should be read as a string
Essentially, I just added backslashes to pass parameter as string
<input type='button' id='report-submit' value='Go' onclick='displayDiv(".$id.",\"".$businessname."\")'>
Use
<input type='button' id='report-submit' value='Go' onClick="displayDiv('<?php echo $id ?>', '<?php echo $businessname ?>');">
Example
<?php
$id = '1';
$businessname = 'Business Name';
?>
<html>
<head>
<script type="text/javascript">
function displayDiv(id, businessname) {
alert(id);
alert(businessname);
}
</script>
</head>
<body>
<input type='button' id='report-submit' value='Go' onClick="displayDiv('<?php echo $id ?>', '<?php echo $businessname ?>');">
</body>
</html>

How to Enable dynamic textbox onclick using javascript?

I have textboxes created with DB fields and a "E" for Edit link next to it. Initially the text fields are disabled. If the user wants to modify the value from DB they would click the link and the textbox next to it will be enable. The problem is that it is modifying the first text box of the same code number. This is probably because the id attribute on text field is the same and I would like to properly identified text but have failed.
Here is my code
<input type="text" name="form_line[code]" size="10"
value='<?php echo bucks($tmp['adj_amount']); ?>' disabled="true" id="editable"/>
<a id="myedit" title="Click to Edit Adjustment Value" href="#" onclick="edit_adj();return false;">E</a>
<script type="text/javascript">
function edit_adj() {
document.getElementById("editable").disabled = false;
}
</script>
An example of output is shown below and if I click on "E" the first textbox gets enabled :(
I think this will work for you:
<?php
for ($x=0; $x<=10; $x++) {
?>
<input type="text" name="somename" size="10"
value='<?php echo "hello" ?>' disabled="true" id="editable<?php echo $x ?>"/>
<a id="myedit" title="Click to Edit Adjustment Value" href="#" onclick="edit_adj(<?php echo $x ?>);return false;">Edit</a>
<br/>
<?php
}
?>
<script type="text/javascript">
function edit_adj(id) {
document.getElementById("editable"+id).disabled = false;
}
</script>
Hope this helps!
Essentially, this is giving a unique id to each text field and passing the id into the javascript that enables the text field in question. I created a test page locally and it worked.

Printing a PHP variable in HTML textarea

I have a PHP snippet which generates the required output in a variable $ans1. What I want to do is print this variable $ans1 in a <textarea>. I tried to write the following code but it generates the output as usual and not in the textbox. The following is my PHP code:
while($row = mysqli_fetch_array($result)) {
if($submit3 == "Positive") {
$ans1 = $row['reply_yes'];
echo $ans1;
} else if($submit3 == "Negative") {
$ans1 = $row['reply_no'];
echo $ans1;
}
echo "<br/>";
break;
}
And following is my HTML code:
<form method="post" action="fetch_page.php">
<input type="submit" name="submit1" value="Positive" onclick="enter()"/>
<input type="submit" name="submit2" value="Negative" onclick="enter()"/>
<textarea name="txt1" cols="66" rows="10" id="txt1"> </textarea>
<script>
function enter()
{
document.getElementById('txt1').value= <?php echo htmlspecialchars($ans1);?>;
}
</script>
</form>
Please tell me where am I going wrong.
Adding quotes like this isnt working either
document.getElementById('txt1').value= "<?php echo htmlspecialchars($ans1);?>";
As you can see in the following image, the answer(the not bold part) should get printed in the textbox also according to my html code
You can add the text you want to be displayed in the textarea between the <textarea> tag.
<textarea name="txt1" cols="66" rows="10" id="txt1">
<?php echo $ans1; ?>
</textarea>
If the text still doesn't appear or you get an error then make sure you access variables from the global scope. Like below.
<textarea name="txt1" cols="66" rows="10" id="txt1">
<?php echo $GLOBALS['ans1']; ?>
</textarea>
You need to add quotes around the echoed value:
document.getElementById('txt1').value = "<?php echo htmlspecialchars($ans1);?>";
And your script should be situated in <head>
Edit
What about using this:
document.getElementById('txt1').value = "<?php Print($ans1); ?>";
You didn't surround the php with quotes. The following works:
<form method="post" action="fetch_page.php">
<input type="submit" name="submit1" value="Positive" onclick="enter()"/>
<input type="submit" name="submit2" value="Negative" onclick="enter()"/>
<textarea name="txt1" cols="66" rows="10" id="txt1"> </textarea>
<script>
function enter()
{
document.getElementById('txt1').value = "<?php echo htmlspecialchars($ans1); ?>";
}
</script>
</form>
Your question is not a PHP problem. You can't see any output from the function because your script is halted upon submission! So change the submit buttons to type="button" and add a ID, then use the script below. Using jQuery (to minimize t he code you need to write) and use a timeout to actually have time for the function be able to display the results.
$(".button").click(function() {
var buttonName = $(this).attr('name'),
elm = $(this);
$('#txt1').val( buttonName + ' was clicked.' ); // Add response
setTimeout(function(){
elm.get(0).form.submit(); // Submit form
}, 5000); // After 5 seconds
});
JSFIDDLE

Multiple forms onclick event only working for first form

I'm sure this has been asked befor but I can't seem to find it in a search
I have multiple forms on a page generated by php all with onCick event
The problem is it only picks up the first event after that any other clicks produce same result from first click
Here is javascript
function CompareScores(form)
{
var scoreA = document.getElementById("score_A").value;
var scoreB = document.getElementById("score_B").value;
if(scoreA > scoreB){
alert('Score A is Larger ' + scoreA)
}else{
alert('Score B is Larger ' + scoreB)
}
}
And the php generating forms
<?php
while($i<=$numPrelimTeams) {
if($i!=$e) {
?>
<form action="processScores.php" method="post"><p><u><?php echo $prelimTeam[$i]; ?> --> SCORE : <input type="text" class="small" id="score_A" name="score_A" size="1"></u></p>
<input type="hidden" name="team_A" value="<?php echo $prelimTeam[$i]; ?>">
<input type="hidden" name="game" value="<?php echo $game_num; ?>">
<p class="right">Game # <?php echo $game_num; ?> ) <input type="button" value="Enter Scores" onClick="CompareScores(this.form)"></p>
<?php
}else{
?>
<p><u><?php echo $prelimTeam[$i]; ?> --> SCORE : <input type="text" class="small" id="score_B" name="score_B" size="1"></u></p>
<input type="hidden" name="team_B" value="<?php echo $prelimTeam[$i]; ?>">
</form><br><br><br>
<?php
$game_num++;
$e=$e+2;
}
$i++;
}
?>
Without knowing the inputs or seeing the result, it's hard to tell for sure, but it looks like you might be generating multiple instances of this form on the same page, giving you multiple page elements named "score_A" and "score_B". document.getElementById will then become a bit ambiguous.
Since you're already sending the form object, use that instead:
var scoreA = form.score_A.value;
...
There is essentially a single problem with your code. You have multiple instances of the same ID.
To fix it, try something like this.
<input type="text" class="small score_A" name="score_A" size="1" />
Similarly
<input type="text" class="small score_B" name="score_B" size="1" />
Now, you can write a querySelector in your JS
function CompareScores(form) {
var a = form.querySelector('.score_A').value;
var b = form.querySelector('.score_B').value;
//do something
}

Categories