Clear or Delete file from textField - javascript

I am working with PHP's Yii framework and having issues clearing or deleting the uploaded file from the textfield. Currently, it will delete the content from the fileField, but can't get it to delete the textfield. Any ideas?
UPDATE
I can now clear my textField because I've hard coded my clearFileInputField function by adding $('.getFile').val(""); I reference this in my HTML by adding the 'class' => 'getName' in the input section. While this clears the data, it doesn't remove the file after saving. Any suggestions?
HTML
<div id = "clearContent">
<?php echo $form->labelex($model,'info'); ?>
<?php echo $form->textfield($model,'info', array(placeholder => "No file chosen", readonly => true, 'class' => 'getName')); ?><br>
<?php echo $form->fileField($model,'info'); ?>
<?php echo $form->error($model,'info'); ?>
<input type="checkbox" onclick = "clearFileInputField('clearContent')" href="javascript:noAction();"> Remove File
</div>
JavaScript:
<script>
function clearFileInputField(tagId) {
document.getElementById(tagId).innerHTML = document.getElementById(tagId).innerHTML;
$('.getFile').val("");
}
</script>

I am not sure if I understood the problem you are having correctly. If I understood the question completely wrong, please elaborate and I will try to improve my answer.
If you want to remove the the content (the value attribute) of a text and file input you can use code like the following:
// listen to the click on the #clearnbtn element
document.getElementById('clearbtn').addEventListener('click', function() {
// Remove the value of the #foo and #bar elements
document.getElementById('foo').value = "";
document.getElementById('bar').value = "";
});
If you would like to remove an entire field you can do that like so:
// Retrieves the input element, gets its parents and removes itself from it
var fooElement = document.getElementById('foo');
fooElement.parentElement.removeChild(fooElement)
Or you can set the innerHTML attribute of the parent element to an empty string ('').
document.getElementById('clearContent').innerHTML = "";
https://jsfiddle.net/osjk7umh/1/

Related

Get value from jQuery editor to PHP

I'm using this jquery plugin to create a wysiwyg text editor,
I created a textarea in PHP where:
<textarea name="body" id="body"><?php echo $body?></textarea>
and
<script type="text/javascript">
$(document).ready( function() {
$("#body").Editor();
});
</script>
Now i need to get value of this area for send it to SQL
if (isset($_POST['add-article'])) {
unset($_POST['add-article']);
$_POST['user_id'] = $_SESSION['id'];
$_POST['username'] = htmlentities($_SESSION['username']);
$_POST['published'] = isset($_POST['published']) ? 1 : 0;
// I need this line
$_POST['body'] = htmlentities($_POST['body']);
When I put text into this editor, it doesn't enter (value) into the textarea.
I have to have value before I press the add-article button, beacuse now it gives me an empty text.
I found something like this
function displayText(){
alert($("#body").Editor("getText"));
}
This causes it to return text ( i think only display by JS ) but i completely dont know how to use in my PHP scripts.
Second thing is when i write article and make a mistake something like ( Article title already exist ) ( in one session ) text in textarea stayed, but now doesn`t work it.
I think about if there is an error for example "Title already exist" follows:
} else {
$title = $_POST['title'];
$body = $_POST['body'];
$category_id = $_POST['category_id'];
$published = isset($_POST['published']) ? 1 : 0;
}
In my honest opinion i need something like:
add-article.addEventListener('click', function {
$body (from PHP) = alert($("#body").Editor("getText"))(from JS);
}
Thank you in advance for help.
On the plugin page you referenced, I see this is one of the recommendations. Capture the value you want when the click button is pressed, before the form submits.
Add a script to your form submit to put the texteditor content into this element
<form onsubmit='return getItReady()'>
Add an element to the form you'll use as a proxy element and keep it hidden, something like
<textarea id='txtEditorContent' name='txtEditorContent' style='visibility:hidden;height:0px' tabindex="-1"></textarea>
Then add the script to prepare it
<script>
function getItReady() {
console.log('The content:', $('#body').Editor("getText"));
$('#txtEditorContent').val($('#body').Editor("getText"));
return true;
}
</script>
Then in your PHP, it will come through as $_POST['txtEditorContent'].

Strings with double quotes in html input field displaying as &quot

Im getting data from sql and using php to generate javascript for an edit button for each entry. The edit interface uses a text input in a form. When the generated edit button is clicked, the text within this field is set to equal the name of the entry from sql.
This works fine in all cases expect when the name contains double quotes ("), in which case the quotes are replaced with &quot in the text field.
The php genertaed javascript is below:
function editButton($suffix,$name)
{
echo "<button class=\"edit\" onclick=\"editMode$suffix()\">Edit</button>";
echo "<script>
<!--
function editMode$suffix(){
document.getElementById(\"title\").innerHTML = \"Edit Artist\"
var main = document.getElementById(\"main\");
main.style.display = 'none';
var edit = document.getElementById(\"edit\");
edit.style.display = 'block';
//Set the input of the edit interface to be equal to the current name
document.getElementById(\"editInput\").value = \"$name\";
document.getElementById(\"artEdit\").value = \"$name\";
}
-->
</script>";
}
The $name variable is sanitized via htmlentities() before being passed to the function. Without doing so, the edit interface for entries with quotes will not even display.
I found this which sounds like the same issue but no solutions (https://code.google.com/archive/p/embeddedjavascript/issues/19) :/
IF anyone has a solution or can point out some stupid thing im doing thats causing this it would be very appreciated. At this point im going to have to just disable database entry for double quotes and limit to singles.
Just change all the double-quotes in the JavaScript portion to single-quotes, then use addslashes() on the $name variable:
function editButton($suffix, $name)
{
$name = addslashes( html_entity_decode($name) );
echo "<button class='edit' onclick='editMode$suffix()'>Edit</button>";
echo "<script>
<!--
function editMode$suffix() {
document.getElementById('title').innerHTML = 'Edit Artist'
var main = document.getElementById('main');
main.style.display = 'none';
var edit = document.getElementById('edit');
edit.style.display = 'block';
//Set the input of the edit interface to be equal to the current name
document.getElementById('editInput').value = '$name';
document.getElementById('artEdit').value = '$name';
}
-->
</script>";
}
*Also added html_entity_decode() to converts the entities back to their initial state. Consider removing the htmlentities() altogether, in which case, you can remove the html_entity_decode() from the above script.

Javascript fill html input form

I have a generated list of Buttons:
<?php
echo "<td> <button id=\"{$cell}\" onclick=\"ausfüllen($cell)\">{$cell}</button></td>"
?>
and I want to call a JavaScript function:
<script>
function ausfüllen(text) {
document.getElementById("nv_durchwahl").value = "dw";
}
</script>
to fill out some other <td>:
<td>
<input type="text" id="nv_durchwahl" name="nv_durchwahl" value="">
</td>
This is how i tried it.
The buttons are generated without any problem but it doesn't fill out the form.
Any ideas where I went off in this one?
You forgot to close the function bracket
<script>
function ausfüllen(text) {
document.getElementById("nv_durchwahl").value = "dw";
}
</script>
And there is no element with ID "nv_durchwahl".
try to concatenate this way... the function ausfüllen receives a string, check how is being translated into html code...
<?php
echo "<td> <button id='".{$cell}."' onclick='ausfüllen(".'"'.{$cell}.'"'.")'>".{$cell}."</button></td>";
?>
when you say
fill out the form.
means putting on the element with id "nv_durchwahl" (which should be unique) the value "dw" or the content of "text" variable?
<script>
function ausfüllen(text) {
//set the value of the element with the specific id to "dw"
//text is never used!
document.getElementById("nv_durchwahl").value = "dw";
}
</script>

Filemaker, PHP and jquery > show hide elements

I am echoing out a form (foreach) from my filemaker records which will result in the items ID, Name, a Checkbox and then an image.
In my understanding i will have to use classes or the elements will all have the same id.
My Code;
foreach($result->getRecords() as $record){
$id = $record->getField('Record_ID_PHP');
$name = $record->getField('DB_Name');
$pic = $record->getField('Photo_Path');
echo '"'.$id.'"<br>';
echo $name.'<br>';
echo '<input type="checkbox" class="check" value="Invoices/Photos/RC_Data_FMS/Invoices_db/Photos/'.$pic.'">';
echo '<div class="pics">';
echo '<img style="width:200px;" src="Invoices/Photos/RC_Data_FMS/Invoices_db/Photos/'.$pic.'"><br>';
echo '<hr>';
echo '</div>';
}
Which results in a page full of the records, a checkbox and the relating image.
I wish to only show these images when the checkbox is checked but cannot find a solution, i have tried many jquery scripts, to no avail.
The images will then populate the next page as a pdf to be printed.
I am hoping not to have to grab the checkbox's values as an array to then use the get method with 100's of if statements but cant see another way ?
The jquery ive used.
$(document).ready(function () {
$('.pics').hide();
$('.check').click(function () {
$('pics').show;
});
$('.pics').hide;
});
and
$(function() {
$(".check").click(function(e) {
e.preventDefault();
$('.pics').hide();
$('.pics').show();
});
});
Plus many similar alternatives.
Is there something obvious i am missing ?
Query to filemaker method;
I have changed the path field to a calculated value which works great, thank you, although with 1000's of records, i would need lots of php code to echo the checkbox's to the website and lots more to be able to edit them from the website.
I have done this previously with the value held within the checkbox in filemaker.
$sesame = $print->getField('Allergens::Allergens[11]'); if ($sesame == "Sesame") { $sesame = "checked" ;} else if ($sesame !== "Sesame") {$sesame = "" ;}
This displays the checkbox synced with filemaker.
if ($_POST['Sesame'] == 'Sesame'){ $a_sesame = 'Sesame';} else { $a_sesame = 'No Sesame'; }
This is sent as a variable to my script.
if($a_sesame == "Sesame"){$contains_sesame = "Yes";} else { $contains_sesame = "No";}
This grabs the new value from the form.
Which all work great, but then i am writing a script in filemaker too to enable the to and from of the different names for each checkbox state.
which is for this part 120 lines long, this is a sample which i have to repeat for each repetition of this field.
Set Variable [ $sesame; Value:GetValue ( Get ( ScriptParameter ) ; 11 ) ]
If [ $sesame = "Sesame" ]
Set Field [ Allergens::Allergens[11]; "Sesame" ] Commit Records/Requests
[ Skip data entry validation; No dialog ]
Else If [ $sesame = "No Sesame" ]
Clear [ Allergens::Allergens[11] ] [ Select ]
Commit Records/Requests
[ Skip data entry validation; No dialog ]
Refresh Window
[ Flush cached join results; Flush cached external data ]
End If
This would be far too large to write for so many records, just for these 14 fields used 120 in filemaker and 400 plus in the php.
I am not 100% sure what you are trying to do but this should work. First add an extra div that closes input and div pics like below.
foreach($result->getRecords() as $record){
$id = $record->getField('Record_ID_PHP');
$name = $record->getField('DB_Name');
$pic = $record->getField('Photo_Path');
echo <<<TEXT
'{$id}'<br>
{$name}<br>
<div>
<input type='checkbox' class='check' value='Invoices/Photos/RC_Data_FMS/Invoices_db/Photos/{$pic}'>
<div class='pics'>
<img style='width: 200px;' src='Invoices/Photos/RC_Data_FMS/Invoices_db/Photos/{$pic}'><br>
<hr>
</div>
</div>
TEXT;
}
then change your java to this
$(document).ready(function() {
$(".pics").hide();
$(".check").click(function() {
$(this).siblings().toggle();
});
});
well I hope this helps
Another alternative would be to set up a simple calculated container field in FileMaker, with a calculated value of:
If ( checkbox; imageField )
This would only pass the image when the checkbox was ticked for a record. This should be faster than handling this in JavaScript, since you'd be limiting the number of images being sent over the wire.
Note: For performance, you might try this with this calculated container field stored and unstored. I suspect stored v unstored should make little difference, in which case I'd suggest leaving this unstored to minimize disk space consumed.
You can use the toggle()function:
$(function() {
$('.pics').hide();
$(".check").is(':checked',function(e) {
e.preventDefault();
$('.pics').toggle();
});
});

Separating variables for SQL insert using PHP and JavaScript

A grid table is displayed via PHP/MySQL that has a column for a checkbox that the user will check. The name is "checkMr[]", shown here:
echo "<tr><td>
<input type=\"checkbox\" id=\"{$Row[CONTAINER_NUMBER]}\"
data-info=\"{$Row[BOL_NUMBER]}\" data-to=\"{$Row[TO_NUMBER]}\"
name=\"checkMr[]\" />
</td>";
As you will notice, there is are attributes for id, data-info, and data-to that are sent to a modal window. Here is the JavaScript that sends the attributes to the modal window:
<script type="text/javascript">
$(function()
{
$('a').click(function()
{
var selectedID = [];
var selectedBL = [];
var selectedTO = [];
$(':checkbox[name="checkMr[]"]:checked').each(function()
{
selectedID.push($(this).attr('id'))
selectedBL.push($(this).attr('data-info'))
selectedTO.push($(this).attr('data-to'))
});
$(".modal-body .containerNumber").val( selectedID );
$(".modal-body .bolNumber").val( selectedBL );
$(".modal-body .toNumber").val( selectedTO );
});
});
</script>
So far so good. The modal retrieves the attributes via javascript. I can choose to display them or not. Here is how the modal retrieves the attributes:
<div id="myModal">
<div class="modal-body">
<form action="" method="POST" name="modalForm">
<input type="hidden" name="containerNumber" class="containerNumber" id="containerNumber" />
<input type="hidden" name="bolNumber" class="bolNumber" id="bolNumber" />
<input type="hidden" name="toNumber" class="toNumber" id="toNumber" />
</form>
</div>
</div>
There are additional fields within the form that the user will enter data, I just chose not to display the code. But so far, everything works. There is a submit button that then sends the form data to PHP variables. There is a mysql INSERT statement that then updates the necessary table.
Here is the PHP code (within the modal window):
<?php
$bol = $_POST['bolNumber'];
$container = $_POST['containerNumber'];
$to = $_POST['toNumber'];
if(isset($_POST['submit'])){
$bol = mysql_real_escape_string(stripslashes($bol));
$container = mysql_real_escape_string(stripslashes($container));
$to = mysql_real_escape_string(stripslashes($to));
$sql_query_string =
"INSERT INTO myTable (bol, container_num, to_num)
VALUES ('$bol', '$container', '$to')
}
if(mysql_query($sql_query_string)){
echo ("<script language='javascript'>
window.alert('Saved')
</script>");
}
else{
echo ("<script language='javascript'>
window.alert('Not Saved')
</script>");
}
?>
All of this works. The user checks a checkbox, the modal window opens, the user fills out additional form fields, hits save, and as long as there are no issues, the appropriate window will pop and say "Saved."
Here is the issue: when the user checks MULTIPLE checkboxes, the modal does indeed retrieve multiple container numbers and I can display it. They seem to be already separated by a comma.
The problem comes when the PHP variables are holding multiple container numbers (or bol numbers). The container numbers need to be separated, and I guess there has to be a way the PHP can automatically create multiple INSERT statements for each container number.
I know the variables need to be placed in an array somehow. And then there has to be a FOR loop that will read each container and separate them if there is a comma.
I just don't know how to do this.
When you send array values over HTTP as with [], they will already be arrays in PHP, so you can already iterate over them:
foreach ($_POST['bol'] as $bol) {
"INSERT INTO bol VALUES ('$bol')";
}
Your queries are vulnerable to injection. You should be using properly parameterized queries with PDO/mysqli
Assuming the *_NUMBER variables as keys directly below are integers, use:
echo '<tr><td><input type="checkbox" value="'.json_encode(array('CONTAINER_NUMBER' => $Row[CONTAINER_NUMBER], 'BOL_NUMBER' => $Row[BOL_NUMBER], 'TO_NUMBER' => $Row[TO_NUMBER])).'" name="checkMr[]" /></td>';
Then...
$('a#specifyAnchor').click(function() {
var selectedCollection = [];
$(':checkbox[name="checkMr[]"]:checked').each(function() {
selectedCollection.push($(this).val());
});
$(".modal-body #checkboxCollections").val( selectedCollection );
});
Then...
<form action="" method="POST" name="modalForm">
<input type="hidden" name="checkboxCollections" id="checkboxCollections" />
Then...
<?php
$cc = $_POST['checkboxCollections'];
if (isset($_POST['submit'])) {
foreach ($cc as $v) {
$arr = json_decode($v);
$query = sprintf("INSERT INTO myTable (bol, container_num, to_num) VALUES ('%s', '%s', '%s')", $arr['BOL_NUMBER'], $arr['CONTAINER_NUMBER'], $arr['TO_NUMBER']);
// If query fails, do this...
// Else...
}
}
?>
Some caveats:
Notice the selector I used for your previous $('a').click() function. Do this so your form updates only when a specific link is clicked.
I removed your mysql_real_escape_string functions due to laziness. Make sure your data can be inserted into the table correctly.
Make sure you protect yourself against SQL injection vulnerabilities.
Be sure to test my code. You may have to change some things but understand the big picture here.

Categories

Resources