Passing multiple variables to Javascript Function - javascript

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>

Related

How to check and uncheck all checkboxes

I have a problem with my code. I am trying to click on the button to check all of the checkboxes but nothing is working.
Here's my code.
<body>
<html>
<input type="checkbox" id="chk_boxes1" name="chk_boxes1" class="delete_customer" value="<?php echo $rowTrackers['id']; ?>" />
<br>
<input type="checkbox" id="chk_boxes1" name="chk_boxes1" class="delete_customer" value="<?php echo $rowTrackers['id']; ?>" />
<br>
<input type="checkbox" id="chk_boxes1" name="chk_boxes1" class="delete_customer" value="<?php echo $rowTrackers['id']; ?>" />
<br>
<button type="button" name="btn_checkall" id="btn_checkall">Check all</button>
</html>
</body>
<script>
$(document).ready(function(){
$('#btn_checkall').click(function(){
if($(this).prop('checked')){
$('.chk_boxes1').prop('checked', true);
}else{
$('.chk_boxes1').prop('checked', false);
}
});
});
</script>
I don't know where the trouble is coming from, but I guess that something have to do with the id, name or whatever it is that make it stop working.
Can you please show me the correct code that I could use to check and uncheck all of the checkboxes when I click on a button using with my code?
One thing to correct is that you have your html tag after your body tag. The html tag should for sure be the parent.
Other than this it looks like you have assigned "chk_boxes1" to id's instead of classes. If you change them to classes then things should work:
<input type="checkbox" name="chk_boxes1" class="delete_customer chk_boxes1" value="<?php echo $rowTrackers['id']; ?>" />
<br>
<input type="checkbox" name="chk_boxes1" class="delete_customer chk_boxes1" value="<?php echo $rowTrackers['id']; ?>" />
<br>
<input type="checkbox" name="chk_boxes1" class="delete_customer chk_boxes1" value="<?php echo $rowTrackers['id']; ?>" />
<br>
Also you are checking at button to determine checked status. This also will make the code not work. You can add and remove a class to the button if you want to change status or you can do something like this to check the group of checkboxes:
$(document).ready(function(){
$('#btn_checkall').click(function(){
if ($('.chk_boxes1:checked').length == $('.chk_boxes1').length) {
$('.chk_boxes1').prop('checked', false);
}
else {
$('.chk_boxes1').prop('checked', true);
}
});
You have a lot going wrong there.
Firstly, your HTML tags are in the wrong order. Your document should start with <html> and end with </html>:
So, change your document to be like this:
<html>
<body>
// your content
</body>
</html>
And you also want to include your script at the bottom of your <body> or, as you're listening for DOM ready event, include the script in the <head>. So, adjust your <script> position to here:
<html>
<body>
// your content
<script>
// script here
</script>
</body>
</html>
As for the main question, I suggest these changes:
HTML:
Remove the duplicate IDs. ID are meant to be totally unique for each element.
<input type="checkbox" name="chk_boxes1" class="delete_customer" value="<?php echo $rowTrackers['id']; ?>" />
<br>
<input type="checkbox" name="chk_boxes1" class="delete_customer" value="<?php echo $rowTrackers['id']; ?>" />
<br>
<input type="checkbox" name="chk_boxes1" class="delete_customer" value="<?php echo $rowTrackers['id']; ?>" />
<br>
jQuery:
Select the checkboxes by name instead of ID:
$(document).ready(function() {
$('#btn_checkall').click(function(){
var $chk_boxes = $('input[name="chk_boxes1"]');
if($chk_boxes.prop('checked')) {
$chk_boxes.prop('checked', true);
} else {
$chk_boxes.prop('checked', false);
}
});
});
As people have said, ids should be unique:
$(document).ready(function(){
//Use JQuery .on to attach event handler
$('#btn_checkall').on('click', function(){
//Get all checkboxes by class
const $checkboxes = $('.delete_customer');
//Use .each to iterate the checkboxes
$checkboxes.each(function(){
$(this).prop('checked', true);
});
});
});

HTML element passing first value in PHP array

I've got a php page that gets data from mysql database as $certs[] and populates that as a table:
($db is read from file, it is constant)
<?php echo $cert["id"] ?>
<button type="button" class="awe" title="Edit" id="editbtn" onclick="openNewModalWithValue('Modal2')" value =<?php echo $cert["id"] ?> >&#xf019</button>
<form action="sample.php" method="POST">
<input type="hidden" name="id" value=<?php echo $cert["id"] ?>>
<input type="hidden" name="db" value=<?php echo $db ?>>
<button type="submit" name="mission" title="Delete">&#xf00d</button>
</form>
And I try to get id value in Modal window. (Like press 'EDIT' button and you get modal window with values set.) So my Modal window is:
<form id="modal-form" method="POST" action="sample2.php">
<input type="number" id="idb" name="idbase" />
<input type="text" id="nme" name="name"/>
<input type="hidden" name="db" value=<?php echo $db; ?>>
<input type="hidden" id= "idbs" name="idbs" />
<button id="form-submit" type="submit" >Edit</button>
</form>
and the Javascript for opening modal window is:
function openNewModalWithValue(modal){
document.getElementById(modal).style.display = "block";
document.getElementById("idb").value = document.getElementById("editbtn").value;
}
The problem is that even though PHP sends $certs[] values correctly, and table populates correctly, when I hit 'edit' button, I get preserved values of item#1 in PHP array, no matter which row/data I click.
Is there an easier way rather than applying counter to every row and operating with it?
Problem may be idb is multiple id in DOM. document.getElementById find Dom in whole page. so you must provide unique id

How to keep php $_GET value from a submit button after form submit from javascript?

I have a php page with 2 submit buttons and 2 radio buttons:
<?php
$choiceIdx = 1;
$language = 'English';
if($_GET)
{
if(isset( $_GET['choice'] ))
{
$choiceIdx = $_GET['choice'];
}
if(isset( $_GET['language'] ))
{
$language = $_GET['language'];
}
}
?>
<form method="get">
<button type='submit' name='choice' value='1'>Choice1</button>
<button type='submit' name='choice' value='2'>Choice2</button>
<input id="English" type="radio" name="language" value="English" <?php echo ($language=='English')?'checked':'' ?> onchange="this.form.submit();" />
<label for="English">English</label>
<input id="Slovenian" type="radio" name="language" value="Slovenian" <?php echo ($language=='Slovenian')?'checked':'' ?> onchange="this.form.submit();" />
<label for="Slovenian">Slovenian</label>
</form>
If I click on Slovenian radio button, I get:
http://localhost/index.php?language=Slovenian
If I then click on Choice2 submit button, "language" is saved and I get:
http://localhost/index.php?choice=2&language=Slovenian
If I then click on English radio button, "choice" is not saved and I get:
http://localhost/index.php?language=English
This is my first php page and after hours of googling i added this line:
<input type="hidden" name="choice" value="<?php echo $choiceIdx; ?>">
The "choice" is now saved, but i get:
http://localhost/index.php?choice=1&language=Slovenian&choice=2
I don't want it twice in url. Please explain what i am doing wrong. Thank you!
EDIT: I want to use GET (and not POST) because the URL has to be saved as a bookmark.
Here is an alternate version (as a followup to my first answer) that updates the hidden value when clicking the choice-button:
<script>
function setChoice(val) {
document.getElementById('hiddenChoice').value=val;
}
</script>
<form method="get">
<button type='submit' onClick="setChoice(1);">Choice1</button>
<button type='submit' onClick="setChoice(2);">Choice2</button>
<input type='hidden' id='hiddenChoice' name='choice' value='<?php echo $choiceIdx; ?>'>
<input id="English" type="radio" name="language" value="English" <?php echo ($language=='English')?'checked':'' ?> onchange="this.form.submit();" />
<label for="English">English</label>
<input id="Slovenian" type="radio" name="language" value="Slovenian" <?php echo ($language=='Slovenian')?'checked':'' ?> onchange="this.form.submit();" />
<label for="Slovenian">Slovenian</label>
</form>
If you have more values to retrieve you might want to create a more sofisticated and less specific js-function. You could easily pass in the id of the target input f.e.
Also you should rethink if it's realy neccessary to always submit the form, or if it might be better to first collect all the data and only send one form back to the server.
Add that to your form:
<input type='hidden' name='choiceStored' value='<?php echo $choiceIdx; ?>'>
This will store the last received val for choice and re-send it at the next form submit.
and change your php to:
$choiceIdx = 1;
$language = 'English';
if($_GET)
{
// eighter get new value
if(isset( $_GET['choice'] ))
{
$choiceIdx = $_GET['choice'];
// or if we don't have a new value, take the 'stored' one:
} elseif (isset($_GET['choiceStored']))
{
$choiceIdx = $_GET['choiceStored'];
}
if(isset( $_GET['language'] ))
{
$language = $_GET['language'];
}
}
You are passing the same name twice. 'choice' has been defined as both the hidden value name and the button value name. To be able to differentiate, you should change the hidden value name to something like 'savedchoice'. And reference it by that name

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

PHP variable to HTML textbox using 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.

Categories