I have a problem of clearing out of the text area in my application. The app has two methods of getting a specific data format: searching online database and using a javascript library.
First method: a user types a chemical name in a text field and presses "Search" button. If requested compound is in the database, a proper format is displayed in the text area.
Second method: if the name was not found in the database, then a user can use a JS library to generate a proper format which is displayed in the same text area.
If a user uses database first, the text area contains generated data from the database which can be replaced by data generated by JS library if a user decides to use it. The problem is that if the text area already has data generated by JS library it cannot be replaced by data from the database when first method is used. I don't know how to clear the text area containing data (generated by JS library) before inserting data from the database. Sorry if it still sounds confusing.
Here is a javascript code:
<script>
var sketcher = new ChemDoodle.SketcherCanvas('sketcher', 400, 300, {useServices:true});
var mol = sketcher.getMolecule();
var molFile = ChemDoodle.writeMOL(mol);
function myFunc($data)
{
document.getElementById('txt_area').value = $data
return false
}
</script>
<span onclick="myFunc(ChemDoodle.writeMOL(sketcher.getMolecule()));"
<button href='javascript:void(0)'; type="submit" id="get_mol">Get Mol</button>
</span>
Jquery/ajax:
$('#search').on('click', function()
{
chemical = $('#chemical').val();
$.ajax({
type: "GET",
url: "/_get_smiles",
data : { 'chemical': chemical},
success: function(data)
{
$('#txt_area').text(data.smiles);
},
error: function(error)
{
console.log(error)
}
});
});
HTML:
<input type="text" id="chemical" size="40">
<button type="submit" id="search" value="Search">Search</button>
<textarea id="txt_area" name="smiles_mol" rows="28" cols="49"></textarea>
To clear text area I the methods below but unsuscessfully:
$('#txt_area').text = "";
$('#txt_area').html = "";
$("#txt_area").attr("value", "");
Method $('#txt_area').val(""); clears the text area but prevents inserting data from database. Any comments and suggestions are highly appreciated!
I think you simply need to change the jQuery/AJAX portion to use this:
$('#txt_area').val(data.smiles);
However it's a bit confusing as to how the parts relate to one another since you seem to have two different pieces of JavaScript and two pieces of HTML but haven't written them together. Is that how the file is structured? If one is supposed to be a fallback to the other, it feels like it should be done automatically.
Edit - like this, if I'm understanding correctly:
$('#search').on('click', function() {
chemical = $('#chemical').val();
$.ajax({
type: "GET",
url: "/_get_smiles",
data: {
'chemical': chemical
},
success: function(data) {
if (data.smiles) {
$('#txt_area').val(data.smiles);
} else {
$('#txt_area').val(ChemDoodle.writeMOL(sketcher.getMolecule()));
}
},
error: function(error) {
console.log(error);
$('#txt_area').val(ChemDoodle.writeMOL(sketcher.getMolecule()));
}
});
});
How about $('#txt_area').val(null);?
That's how you clear a textbox but maybe it's something else that's preventing the library from doing its stuff.
If you're certain that there's some weirdness going on with clearing the data, you could try the following in your AJAX callback
$newTextArea = $('<textarea>').attr({ id:'txt_area', name:'smiles_mol', rows:'28', cols:'49'}).text(data.smiles)
$('#txt_area').replaceWith($newTextArea);
This replaces the old text area with a totally new text-area DOM element
Related
I am creating an application that converts an online form into various PDF forms to reduce admin burden. I am using an XML file so that users can enter a course code and the form will automatically populate some of its data to fill in the course information, however for the code below I am just using test files to figure it out first.
The user is to enter the course code in a text input and click a button to call Ajax to read the xml and create variables to populate the form. I have looked through dozens of tutorials and forums and can't seem to solve my problem - I need to filter the child nodes according to the course code entered, but I can only get it to work by entering the course code as text in the js file, when I attempt to use a variable argument it doesn't work and I have tried so many different ways.
HTML...
<html>
<head><title>XML Reader</title></head>
<body>
<input type="text" id="argumentText">
<input type="button" id="button" value="process">
<input type="text" id="outputText">
<script type="text/javascript" src="jquery-3.3.1.js"></script>
<script type="text/javascript" src="test.js"></script>
</body>
</html>
XML...
Will have more coursecodes and child nodes eventually when I can get jQuery to work
<?xml version="1.0"?>
<course type="array">
<coursecode>CWI416D01F
<description>Signmaking L2</description>
</coursecode>
<coursecode>CWI490D01F
<description>Business Admin L2</description>
</coursecode>
<coursecode>CWA061D01S
<description>Dental Nurse L3</description>
</coursecode>
</course>
My jQuery...
Note that the code below does actually work, but the outputVar that is created doesn't use the argumentVar at all...
$('#button').click(function(){
$.ajax({
url: 'test.xml',
type: 'GET',
dataType: 'xml',
success: function(data){
//an argument is taken from the argumentText field
var argumentVar = $("#argumentText").val();
//Doing it this way works
var outputVar = $(data).find('coursecode:contains(CWI416D01F)').children('description').text();
//The outputVar is output as text in the outputText field, in this case "Signmaking L2"
$('#outputText').val(outputVar);
},
error: function(){
}
}); //ajax is closed
}); //click function is closed
But I want the outputVar to take the argumentVar as the text argument in contains() rather than having to set updozens of cases in a switch, I have tried several methods, here are a couple of examples below...
var outputVar =
//Attempt 1
$(data).find('coursecode:contains(argumentVar)').children('description').text();
//Attempt 2
$(data).find('coursecode:contains('"+argumentVar+"')').children('description').text();
//Attempt 3 & 4 (I added an ID into each xml coursecode tag for this attempt)
$(data).find('coursecode[id="argumentVar"]').children('description').text();
$(data).find('coursecode[id=argumentVar]').children('description').text();
I've even tried a bunch of other different ways such as attempting to parse, if statements, filter return functions, you name it. Hopefully there is someone out there who can answer this, ideally with a really simple snippet of code.
This question was answered thanks to Ryan Wilson, here is answer in case anybody else confronting this problem...
$('#button').click(function(){
$.ajax({
url: 'test.xml',
type: 'GET',
dataType: 'xml',
success: function(data){
//an argument is taken from the argumentText field
var argumentVar = $("#argumentText").val();
//This code finds a single xml node using the argumentVar variable
var outputVar = $(data).find('coursecode:contains(' + argumentVar + ')').children('description').text();
//The outputVar is output as text in the outputText field as according to whatever argument the user entered into argumentText
$('#outputText').val(outputVar);
},
error: function(){
}
}); //ajax is closed
}); //click function is closed
I'm trying to create an upload panel like facebook, but I've got a trouble with <input type="file" />.
Here is facebook upload image panel:
My trouble is: if I click add more (like image above), that means the <input type="file" /> will be clicked again. So, the value will be overridden.
After that, if I click submit button, only 1 image can be uploaded.
My jquery code to upload looks like this:
function Upload(evt, id)
{
var file = document.getElementById("file");
var formData = new FormData();
for (i = 0; i < file.files.length; i++) {
formData.append(file.files[i].name, file.files[i]);
}
formData.append("id", id);
$.ajax({
url: "/Home/Upload",
type: "POST",
dataType: "json",
data: formData,
contentType: false,
processData: false,
success: function (data) {
alert('upload successful...');
},
error: function () {
alert('upload failed...');
}
});
}
The first line: var file = document.getElementById("file");. It means: get the latest value of <input type="file" name="file" id="file" /> (no keep the selected file before).
Can you tell me how to get all the selected files? (I don't talk about multiple).
Thank you!
"My trouble is: if I click add more (like image above), that means the will be clicked again. So, the value will be overridden."
Here's the underlying problem with your script:
"You can't set the value of a file picker from a script" so no direct manipulation of form will work
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#File_inputs
You can't manipulate file inputs from javascript in any meaningful way (for obvious security reasons), you can only read them. However, you can manipulate the DOM. What facebook and other multi-part pickers actually do is create and destroy file input elements in order to allow the flows they want, rather than try to bind anything to the file value of the input.
There are a lot of plugins that handle this complexity for you, but it's pretty doable to get it working once you understand the problem you're working around.
further clarification:
yup, it sounds like you're thinking about it right now! just think of file inputs as read-only, and use another variable to store all your values, and any function to deal with showing previews in the dom reads from that rather than binding directly from the file input.
One extra thing I would add in response to But the value can only append, not remove :((, is that you shouldn't store the values in FormData if you might need to remove values. Instead just use a regular object to store all the values you want to add/modify, and then construct the object when the user submits the form. Something along the lines of this:
var myFormDataObject = {}; // can store inputs in this
// watch onchange and add/remove from myFormDataObject
function sendStuff(){
var formData = new FormData();
for (var key in myFormDataObject) {
formData.append(key, myFormDataObject[key]);
}
// then post/put/patch/etc the form
}
This post by #BenjaminRH (How to change/edit the text of a paragraph/div using jQuery?) provides exactly the sort of functionality I'm trying to build on.
By clicking on a button, a new paragraph is created on the page, which can be edited and saved to the page.
I want to save it to a database. When I look at the page source after editing, I don't see the changes there, which doesn't surprise me... but I don't know where to "capture" the changed text so that I can validate and post to mySQL.
JQuery is a javascript library - which runs client side. If you wanted to save that data into the database - you would have to send it to the server (php/asp/mvc etc) using ajax and then insert the data into the database.
See the jquery Ajax function for details on how to accomplish sending data asynchronously.
Create the data in javascript that you want to show and save in database.
Wrap the data in JSON and use ajax to POST the data to the server side code
Server-side retrieve the posted data and parse it into something usable
Server-side write a script to insert the data into the database.
Handle any errors that may occur.
Pseudo-code:
// step 1
var someData = 'this is my data';
$("#myDiv").html(someData);
// step 2
$.ajax({
type: "POST",
dataType: 'json', // <-- if the data is complex and needs to be object-oriented
url: "some.php", // <-- that is the file that will handle the post server-side.
data: JSON.stringify({ someData }) // <-- just pass someData if your data is not complex
})
.always(function(jqXHR, textStatus) {
if (textStatus != "success") {
// step 5: handle error.
alert("Error: " + jqXHR.statusText); //error is always called .statusText
} else {
alert("Success: " + jqXHR.response); //might not always be named .response
}});
OK, I've managed to solve it for myself, without using ajax. I took the example from (How to change/edit the text of a paragraph/div using jQuery?) and modified it by placing the elements in an (html) form.
The second modification was to use <textarea> elements, not <p> elements, as <p> elements cannot be posted.
As #caspian pointed out (in the comments) those two steps do populate the $_POST array and away we go.
I have a page and I ask them zipcode. While they are filling the form right after they finish writing 5 numbers of zipcode, It will check if it is covered from my database and will show a check or cross sign near it and will disable submit.
To summarize.
Will wait for visitor to type 5 digits zip code( If we can check if customer only enters number it will be a plus and great)
It will check if it is covered in database ( I don't ask for php part. Probably we will send it as POST to a php file)
If it exists in database it will show check else it will show cross and will not allow the form to be submitted.
I checked some websites but couldn't find an exact solution.
Thank you
Probably you need have an image tag besides the zip code text box with the src attribute set to an invisible image. Then perform an ajax upon the blur event.
HTML:
<input type="text" id="zip" name="zip"> <img id="imgconf" src="images/blank.png">
Javascript:
$('#zip').blur(function() {
$.ajax({
url: "script.php",
type: "POST",
data: "zip=" + $('#zip').val(),
dataType: "text",
success: function (data){
if (data=="1"){
$('#imgconf').attr("src", "images/correct.png");
} else {
$('#imgconf').attr("src", "images/wrong.png");
}
}
});
});
For the numeric validation, you may use the same PHP script to return another flag besides "1" and display it in another span element that the data entered is not numeric. Just add another key-value pair in the data part, maybe.
You will need to use AJAX. JQuery has a built in AJAX function. On each keyup event, you can have it run this AJAX function. The PHP should return a value of either 1 or 0 to make it easy. 1 obviously is match, and 0 is no-match.
$('#YourObjectID').keyup(function (event) {
searchZips();
})
function searchZips()
{
var myJSON = $.ajax({
url: options.script + '?Q=' + curValue,
type: 'POST',
contentType: 'application/json',
success: function (msg) {
if(msg==="1"){
// CODE TO SHOW YOUR X DIV
}
}
}
You will want to also add functionality on clearing the search, checking if null or empty string, etc., etc., but this is the basics that should get you going. I use this all the time. Once you get the hang of it, it's VERY useful. Then look into building a jQuery plugin. Once you can do the above functionality, you can build it into a plugin (with tons of cool options!) GOOD LUCK and happy programming.
What I am trying to do only using XMLHttpRequest, is this:
The script downloads a web page, that has only one form in it.
The script inserts text into a field.
The script submits the form, while keeping all details about input tags.
I did the first part, but I have no idea how to finish with the next two steps.
Note: I do not have control over the page downloaded, and it is not well-formed XML/HTML.
Could someone explain to me how I can get this done?
This is for a Google Chrome extension, so I have all permissions needed.
EDIT: this is my current code:
$.ajax({ url: "http://www.mysite.com/my/testpage.aspx",
type: "POST",
data: {
html: http0.responseText.between("<body>", "</body>")
},
success: function(data) {
var dom = $(data),
form = dom.filter('form');
form.attr('onsubmit', 'document.getElementById("error").value = "I\'m done!"; document.getElementById("helpmebutton").disabled = false;');
form.attr('action', 'http://www.mysite.com/my/testpage.aspx');
$('#tempdiv').append(form);
form.find('input[name="ctl00$ctl00$cphSite$cphMySiteContent$linkLocation"]').val(document.getElementById("result").value);
form.submit();
}
});
I would really use jQuery to save yourself time and headaches.
Create a temporary div with id tempdiv and put everything in that div. Then, fill in appropriate elements and submit the form, like this:
$.ajax({ url: "http://...",
success: function(data) {
var dom = $(data),
form = dom.filter('form');
$('#tempdiv').append(form);
form.find('input:text').val(123);
// all input[type=text] get value 123
form.submit();
}
});