How to read text from textfield using jQuery to the variable? - javascript

So, I got the page on my local server, and this page contains textarea and button. I am Trying to write onclick function to button, which would read whatever I typed in text area, and make record to database. Just like when I finish typing my question here, and press Ask Question. The problem is that I can't properly read text in text area, it basically sees only what was in there at the moment of loading a page, and just rewrite it. How should I get text, that I typed right before clicking the button? I just want to know how can I copy that text to some var, which I can PUT to database.
$.getJSON('/link/' + tenderId, function (data) {
var description = '';
description += '<textarea id="description" class="form-control" rows="3">' + data.description + '</textarea>';
$('#description').html(description);
});

Use this code inside your click event
var textareaValue = $('textarea#textareaId').val();
html
<textarea id="textareaId"></textarea>
SO answer: https://stackoverflow.com/a/144836/2772017

You need to use val() (I am guessing you are using text()) to get the text of a Text Area:
$('input#mybutton').click(function() {
var text = $('textarea#mytextarea').val();
});
Of course this is just guesswork as you did not supply any code! :)
Update:
The code you added is also incorrect as it adds a duplicate id of description inside a div with an id of description! ID's need to be unique on a page.
Assuming you want a new id here is a cleaner version of your code:
$.getJSON('/link/' + tenderId, function (data) {
var $textArea = $("<textarea>", {class: "form-control", id: "descriptionText", rows: "3"}).val(data.description);
$('#description').empty().append(description);
});

I can't figure out you method logic; it seems you are pulling some json data then appending it to a textarea while in issue description you said that you are trying to save the textarea content so you have to be sending it throug a POST request.
Also does the <textarea id="description"...> element is there in your page or you will be creating it at each button click?
If such is you case, you can try with the following snippet:
$.getJSON('/link/' + tenderId, function (data) {
var $description = $("<textarea>");
$description.attr({
id:'description',
class:'form-control',
rows:'3'})
.html(data.description);
//you will have then to append this jQuery element, e.g: $("#wrapper").append($description)
});

$('button').click(function(){
var myString = $('#description').val();
})
Then use myString whereever you like.

Related

How to find a varible html element executing javascript in python

I'm trying to use 2Captcha service to solve an h captcha V2.
Works like this:
you get a value to solve the captcha
Then you find a textarea element in the HTML code to insert that value (here's my problem)
you insert the value in that element
You press submit button and the captcha is solved
First I'm going to present a working example, then I'll present where I have the problem.
This is the HTML code to find and insert the obtained value:
textarea id="h-captcha-response" name="h-captcha-response" style="display: none;"></textarea>
This is the python code used to insert the value:
value = get_value()
insert_solution = 'document.getElementById("h-captcha-response").innerHTML="' + value + '";'
driver.execute_script(insert_solution)
What this exactly does is taking you from this:
and this is the result:
Finally you press the submit button and it's done. This example works
This is my problem:
In my case the HTML document has a variable ID, like this one:
<textarea id="h-captcha-response-0tesbrpxsk8" name="h-captcha-response" style="display: none;"></textarea>
Notice that the id has an alphanumerical part (0tesbrpxsk8) that always changes making it more difficult to select.
I tried to find some regular expression to use inside of document.getElementById()
With no success
I also tried to use:
document.getElementByTagName("textarea").innerHTML=".....
I'm stucked here and tried other approaches with no success because I probably because I don't implement well those solutions or they just don't work.
I'll appreciate some insights, thanks
This will fill out all of those (recaptcha / hcaptcha):
driver.execute_script('''
let [captcha] = arguments
[...document.querySelectorAll('[name="h-captcha-response"],[name="g-recaptcha-response"]')].map(el => {
el.innerHTML = captcha
})
''', value)
Try this:
const textarea = document.querySelector('[id^="h-captcha-response-"]')
textarea.value = "This is inside the textarea!"
<textarea id="h-captcha-response-0tesbrpxsk8" name="h-captcha-response"></textarea>
First of all: You set the value of an textarea with textarea.value = "some value"
You should use document.querySelector() to select elements. (You have much more abilities there)
You can select id starting with, with this query: [id^="start"]

CKEditor SetData JQuery

I have a DropDownList where onChange sets the content of the TextArea which is my CKEditor control.
When the editor is not in use I run this bit of code for onChange:
$(".setBody").change(function() {
//
var className = "." + $(this).attr("sExternalId");
var text = $(this).val();
//
$(className).val(text);
});
I'm not very experienced with Javascript/JQuery and I just can't figure out how to perform the same using CKEditor's setData() function. This is what I've tried:
$(".setCKBody").change(function() {
//
var className = "." + $(this).attr("sExternalId");
var text = $(this).val();
//
var editor = $(className).ckeditorGet();
editor.setData(text, function() {
alert("The content was set");
});
});
$(".setCKBody").change(function() {
//
var className = "." + $(this).attr("sExternalId");
var text = $(this).val();
//
CKEDITOR.instances[$(className)].setData(text, function() {
alert("The content was set");
});
});
Am I close? I think one of the main limitations is that I have multiple editor controls with the same id and name, only the class can tell them apart which is why I'm using that with the JQuery. I've tried working through some examples online, but I'm not sure how to apply them to this scenario - that's probably my inexperience coming through there...
Thanks.
EDIT
This is how my textarea and dropdownlist appears in view source:
<textarea class="editArea M3" cols="20" id="Body" name="Body" rows="5">
*some text*
</textarea>
<select class="setCKBody" id="Templates" name="Templates" sExternalId="M3">
<option value="some value">Option 1</option>
<option value="some value">Option 2</option>
</select>
The onChange event above is triggered from the dropDownList changing and is linked to the textArea via the "sExternalId" attribute. I realised I used "id" as the attribute name in the example above which was in error, so I changed that.
I use this to set it as a CKEditor control:
<script>CKEDITOR.replaceAll('editArea');</script>
I have between 2 to 6 textarea controls on the same page, created with razor like this:
#Html.TextAreaFor(m => m.Body, new { #class = "span12 editArea " + Model.ExternalId, rows = 5 })
They are contained within a partial view that is used like this:
#foreach (MailTemplateModel oTemplate in Model.Templates)
{
#Html.Partial("_MailPartial", oTemplate)
}
This is why each text area has "Body" set as the id and name. I think this is the heart of the problem, with there being multiple elements with the same id and name CKEditor is not able to select the correct one. I've tried to do CKEDITOR.instances["className"] but that was undefined, whereas doing CKEDITOR.instances.Body did work, but would only ever return the same value.
I'm going to restructure the way the page is created to avoid this, hopefully my issues will be solved at the same time.
Here's a few pointers.
Use class="foo" if you have many things that you refer to as a group, like like here it looks like you would have many setCKBody elements you listen to for change events.
Use id="foo" if you have one single specific thing.
Using the same id and class for one element usually is not the right thing to do.
CKEDITOR.instances[xxx] <-- xxx should be a string, not a jquery object - so CKEDITOR.instances[className] might work better (I can't say not having seen your HTML).
It would help if we saw your HTML; textarea definitions and setCKBody definitions. Do you have many ckeditors and many setCKBody elements?
My original approach to this scenario was all wrong, I had a model that contained multiple mail templates and so I rendered each one via a partial view within the same page so that the user could click to edit any one of them and the details would appear in a modal popup - within the same window. What I wanted to avoid was forcing the user to navigate to another window to edit a mail template, but this lead to multiple elements having the same id and name attributes which prevented me from accessing them correctly.
I've now added a list box where the user can select a template to edit, the selected template is rendered underneath and so avoids the multiple name and id issue. Now I know there is only ever 1 CKEditor control so I can access it in my js like this:
var editor = CKEDITOR.instances.SelectedTemplate_Body;
SelectedTemplate_Body is the name and id of the element I made into a CKEditor control. The onChange function I wrote for the dropdownlist is now written like this:
$(document).ready(function() {
//
$(".setBody").change(function() {
//
var templateId = $(this).val();
//
$.ajax({
type: "GET",
url: msHost + "MailTemplates/UpdateBody",
data: { "templateId": templateId },
cache: false,
dataType: "text",
success: function (data) {
CKEDITOR.instances.SelectedTemplate_Body.setData(data);
}
})
});
});
The tempalteId attribute is the value associated to the dropdownlist selection, this lets me know which template to use for setting the content of my editor control.
MailTemplates/UpdateBody points to a public method in my MailTemplates controller which runs a search on available mail templates and matches against the template Id passed in, the method then returns the body of the template as a string.
public string UpdateBody(string tempalteId)
{
TemplateQuery oQuery;
//
oQuery = new TemplateQuery();
oQuery.Execute();
foreach (MailTemplate oTemplate in oQuery.Results)
if (oTemplate.Id.Equals(templateId))
return oTemplate.Body;
//
return string.Empty;
}
This line replaces the contents of the CKEditor control with the response from the controller method.
CKEDITOR.instances.SelectedTemplate_Body.setData(data);
Thanks #Nenotlep for trying to help out, you gave me a few things to think about there.

Alert with a textarea content (HTML to JavaScript)

I'm new at coding with any language and now im working (trying to) with HTML, PHP and JavaScript. My difficulty is to show through an alert in a JavaScript file the information that is in a textarea from an HTML file. The HTML code is this:
<head>
<title> My Form</title>
<script type= "text/javascript" src ="./JavaScript/validaLinha.js"></script>
</head>
<body>
<form name="Linhas" method="POST" action="Linhas-p.php">
<textarea name="descricaoLinha" onFocus="resetField('descricaoLinha')"> TEXT-TEXT-TEXT</textarea>
</form>
</body>
As you can see at the HTML code, I try to send the name of the textarea to a JavaScript function called "resetField". Let's see what the "resetField" does:
function resetField(field){
d = document.Linhas;
alert("It's entering the function."); //ANSWER = It's entering the function.
alert(field); //ANSWER = descricaoLinha
alert(d.field.value); //ANSWER = Nothing.
alert(d.getElementById(field).value); //ANSWER = Nothing.
}
I can't get the information set at the value of my textarea! The event is calling the function (First alert shows up), the string is being received by the function (Second alert shows the name of the text area) but the other two that are the ones that i need doesn't show up. I already tried to change the order of the alerts because of that JavaScript stuff that doesn't continues to read the code if an error appears.
Just to emphasize, i want the content IN the textarea. (The name of it is being received properly)
Thanks for reading! Sorry about my english. ^^
Add an ID to your textaea
<textarea id="descricaoLinha" name="descricaoLinha" onFocus="resetField('descricaoLinha')"> TEXT-TEXT-TEXT</textarea>
And then, send the ID instead of name
alert(d.getElementById(field).value);
This code can't find the element descricaoLinha because its searching for an element that has an ID = "descricaoLinha"
Your 'field' is just a string, not a javascript object and of course it does not have the name attribute;
And it is similar to the d = document.linha;
You have have to get the DOM element by its id attribute:
d = document.getElementById("Linha");
Edit: You also need add the id attribute to your field
<textarea id="descricaoLinha" name="descricaoLinha" onFocus="resetField('descricaoLinha')"> ...
One solution is: you change your JavaScript function to
function resetField(fieldId) {
var field = document.getElementById(fieldId);
alert(field); // object
alert(field.value); // text field value
// Do whatever you want with the field object here
}
You should turn on the console and using console.log('output') instead of using alert() for debugging;
You can turn on Firefox console by Ctrl + Shift + K
You should pass in this in your onfocus handler:
onFocus="resetField(this);"
Access it like:
alert("It's entering the function.");
alert(field.name);
alert(field.value);
Here's a demo: http://jsfiddle.net/RbUZr/

Need Solution on NicEdit Insert HTML text into Instance

i am using this function to insert text into NicEdit,
function insertAtCursor(editor, value){
var editor = nicEditors.findEditor(editor);
var range = editor.getRng();
var editorField = editor.selElm();
editorField.nodeValue = editorField.nodeValue.substring(0, range.startOffset) +
value +
editorField.nodeValue.substring(range.endOffset, editorField.nodeValue.length);}
This code works fine for simple text but when i pass HTML content into it, it does not render the HTML output in div instead it dumps the HTML code as it is into the Instance Div.
Example:
<div class="one">Some text here</div>
This must show in the Instance as "Some text here"
and remaining code hidden in source code.
Can any one give me a solution to fix this problem?
After working whole night and trying different solutions I had finally got it working! :)
In case any one wants to know solution for this, I had to add a Replace function
replace()
for the content and made it support HTML.
See my answer HERE. It's a plugin I created to insert html at the cursor position.

How to get a selected div portion from a variable containing html code by using javascript?

I have a variable var 'html', it contains some html codes .in it there is a div with id messages. I want to get only that div contents from the 'html' variable into another variable using javascript.
Please help . .
The easiest way with jQuery in my opinion:
var message = $('<div />').append(html).find('#message').text();
//.html();
If it's valid HTML, you don't even have to append it to the DOM:
var html = "<div id='wrapper'><div id='messages'>Messages!</div></div>";
// Create DOM node (subtree) from the string (but don't append to the document):
var node = $(html);
// Find the messages div:
var messages = node.children('#messages');
// Get the contents of the div:
var result = messages.text();
Edit: here's a working example: http://jsfiddle.net/xndKN/1/
// your html code
var html = '...';
// add a temporary div
$('<div id="temp" style="display:none">'+html+'</div>').appendTo('body');
// extract the data inside the 'message' div
var message = $('#temp #message').text();
// remove temporary div
$('#temp').remove();
Now, the variable message will contain the text inside the div with id 'message'
First of all you question is not giving enough information about your situation. You have not posted the code. Anyway if you try the following you will get access the the message div.
var o = $("<html><body><div id='parent'><div id='message'>Hello</div></div></body></html>")
$(o).children("#message").text()
I have tried it on Chrome Developer tool and it is working.
try
var myhtml = "here is my data outside div
<div id='message'>inside div with id message</div>";
var node = $(myhtml);
$(node).append(myhtml);
alert($(node).find('div#message').text());
WORKING DEMO

Categories