I have an HTML textarea defined in index.html defined as follows:
<textarea id="myTextArea" rows="12" readonly="7" class="form-control"></textarea>
I have a JavaScript file named shared.js. Right now, shared.js only has the following:
function appendToTextArea(id, text, stayOnCurrentLine) {
var current = $(id).val();
var newText = current + ' ' + text;
if (!stayOnCurrentLine) {
newStatus += '\n';
}
$(id).val(newText);
console.log($(id).val());
}
Index.html is successfully referencing shared.js. It even calls appendToTextArea just fine. I'm calling the code from a function in index.html called myButtonClick.
function myButtonClick() {
appendToTextArea('#myTextArea', 'Hello', false);
appendToTextArea('#myTextArea', 'How', false);
appendToTextArea('#myTextArea', 'are', false);
appendToTextArea('#myTextArea', 'you', false);
}
When the above is called, the text of myTextArea is never updated. However, in the console, I see no errors. In addition, I can see the text exactly how I would expect it. What am I doing wrong?
Define newStatus as empty string and concatenate it with outputted string:
function appendToTextArea(id, text, stayOnCurrentLine) {
var current = $(id).val();
var newStatus = "";
var newText = current + ' ' + text;
if (!stayOnCurrentLine) {
newStatus += '\n';
}
$(id).val(newText + newStatus);
console.log($(id).val());
}
-jsFiddle-
Related
I Have 3 input text in a form, that i would like to joini like this after pressing a button:
TextA-TextB TextC.
I also would like that will be positioniting on th first free line of the text area.
if for eaxmple ther is this situation:
2018-12345 25.00,
i would like that inserting the datas in the 3 text, will become like this:
2018-12345 25.00
TextA-TextB TextC
I imagine that i need javascript and calling the function with event onclick on the button, but i am not into javascript, because of that i am asking for your kind help.
Thanks for the fast answer.
I tried to combine a couple of codes that i found online, but i always get error 404 when I try it on fiddle:
<script>
function fillMessage() {
var annoTA1 = document.getElementById('annoTA') + " ";
var numTess1 = document.getElementById('numTess') + " ";
var impVer1 = document.getElementById('impVer1') + " ";
msg.value = annoTA1.value + numTess1.value + impVer1.value;
var targ = event.target || event.srcElement;
document.getElementById("message").value += targ.textContent || targ.innerText;
var Message= "";
function addText(text) {
Message+= text
}
document.getElementById("message").value = Message;
} </script>
and for the onclick event I used:
<button onclick="fillMessage()">Aggiungi Nuova Tessera</button>
the original fiddle is this:
http://jsfiddle.net/qmrt7z0w/
and plus I added
var Message= "";
function addText(text) {
Message+= text to test there before.
I solved with this script:
<script>
$('#btn').on('click', function (){
var insertText = $('#annoTA').val() + " ";
insertText += $('#numTess').val() + " ";
insertText += $('#impVer').val() + " ";
if(document.getElementById("annoTAG").value == ' ')
{
$('#annoTAG').val( $('#annoTAG').val() + insertText);
}
else
{
$('#annoTAG').val( $('#annoTAG').val() + '\n' + insertText);
}
});
</script>
And for the button i had to use:
<input type="button" value="Aggiungi Nuova Tessera" id="btn" />
Otherwise is not working...
Everything works good now, just that when I am inserting. The first row, it starts with a space. I tried to adding the backspace like this:
if(document.getElementById("annoTAG").value == ' ')
{
$('#annoTAG').val( $('#annoTAG').val() + '\b '+ insertText);
}
But did not works. Any suggestions?
Thanks
I have this code to open a file in NW.JS.
function chooseFile(name, handleFile) {
var chooser = document.querySelector(name);
chooser.addEventListener("change", function(evt) {
for(var f of this.files){
console.log(f.name);
console.log(f.path);
handleFile(f.name, f.path);
}
}, false);
chooser.click();
}
chooseFile('#fileDialog', function(name, path){ ... /* do something with the file(s) */ });
I have concatenated that code into a string so that I can inject it into a div (when that div is created) from a button click that generates the above code with unique id’s thusly..
var letsDoThis = '$(".' + imgUploadClass + '").click(function(){ var leid = this.id; var theEditId = "divId" + leid.slice(5); function ' + imgUploadChoose + '(name, handleFile) { var chooser = document.querySelector(name);chooser.addEventListener("change", function(evt) { for(var f of this.files){console.log(f.name);console.log(f.path);handleFile(f.name, f.path);}}, false);chooser.click();}' + imgUploadChoose + '("#' + imgUploadzz +'", function(name, path){' + 'alert(path);' + ';});});';
When testing I can access the name and path inside the alert box! GREAT! The code I want to run where
'alert("Hello!");’
is needs to be the following (but instead of a hardcoded url I need to access “path” from the (uniquely named) chooseFile script)...
'$("#" +' + 'theEditId).css("background-image", "url(http://www.jqueryscript.net/images/Simplest-Responsive-jQuery-Image-Lightbox-Plugin-simple-lightbox.jpg)");'
I am pretty sure I am not escaping a comma or something, here is another piece of code I got to fire correctly but not being able to access “path”...
'$("#" +' + 'theEditId).css("background-color", "green");'
<script>
Croppic = function (id, options) {
var that = this;
that.id = id;
that.obj = $('#' + id);
that.outputDiv = that.obj;
};
Croppic.prototype = {
form: {}
};
init: function () {
var that = this;
var cropControlUpload = '';
if (that.options.customUploadButtonId === '') {
cropControlUpload = '<i class="cropControlUpload"></i>';
}
var cropControlRemoveCroppedImage = '<i class="cropControlRemoveCroppedImage"></i>';
if ($.isEmptyObject(that.croppedImg)) {
cropControlRemoveCroppedImage = '';
}
if (!$.isEmptyObject(that.options.loadPicture)) {
cropControlUpload = '';
}
var html = '<div class="cropControls cropControlsUpload"> ' + cropControlUpload + cropControlRemoveCroppedImage + ' </div>';
that.outputDiv.append(html);
var formHtml = '<form class="' + that.id + '_imgUploadForm" style="visibility: hidden;"> <input type="file" name="img" accept="image/*" id="' + that.id + '_imgUploadField"> </form>';
that.outputDiv.append(formHtml);
that.form = that.outputDiv.find('.' + that.id + '_imgUploadForm');
},
reset:function (){
var that=this;
that.init();//This initializes using init function
}
</script>
I have a crop module which does something like above.So everytime reset is called the module is initialized by using the init function.
However, the output is not coming as expected what is happening that when a reset is called more than twice, the form object shows this kind of behavior.
That is what console shows when reset is called the first time.Look for the property 0.
When the reset is called twice the result is something like this.Instead of removing the property 0 , it appended a new property 1.
This thing go on if i make more calls to the reset.
So when this happens Inspector in Mozilla shows more than one form when reset is called more than one time(Here i have called reset twice hence two forms in Inspector).
To overcome this problem i tried deleting the property 0 and even tried deleting the whole object and tried to create a new object but nothing helps.
if(that.form.hasOwnProperty("0"))
{
delete that.form["0"];// Here i even did this delete that.form;
that.form = that.outputDiv.find('.' + that.id + '_imgUploadForm');
}else{
that.form = that.outputDiv.find('.' + that.id + '_imgUploadForm');
}
I did everything but the same thing happens.How do i make sure it doesn't add more properties if 0 exists .If 0 exists just replace 0 by the new one.
Full Code :http://codepad.org/03EiunbL
My previous problem has been fixed, now I need to ask how to keep a textarea from resetting its input after a form is submitted. Here is the jsFiddle: http://jsfiddle.net/rz4pnumy/
Should I change the form in the HTML?
<form id="form1" method="GET">
(the form does not go into a php file or anything else, i'm using it to submit the textarea input and use the variables I made using jQuery to make a paragraph on the same page)
or something in the JS?
$(document).ready( function () {
$('#form1').on('submit', function (event) {
// If the form validation returns false, block the form from submitting by
// preventing the event's default behaviour from executing.
if (!validate()) {
event.preventDefault();
}
if(validate()) {
var adjective1 = $('#adjective1').val();
var adjective2 = $('#adjective2').val();
var pluralnoun = $('#plural-noun').val();
var verb1 = $('#verb1').val();
var edibleobject = $('#edible-object').val();
var monster1 = $('#monster1').val();
var adjective3 = $('#adjective3').val();
var monster2 = $('#monster2').val();
var verb2 = $('#verb2').val();
$('body').append(
'<div id="para">' +
'<p>Rain was still lashing the windows, which were now ' + adjective1 +', but inside all looked bright and cheerful. ' +
'The firelight glowed over the countless ' + adjective2 + '' + pluralnoun + ' where people sat ' + verb1 + ', talking, ' +
'doing homework or, in the case of Fred and George Weasley, trying to find out what would happen if you fed a ' + edibleobject +' to a ' + monster1 + '.' +
'Fred had "rescued" the ' + adjective3 + ', fire-dwelling ' + monster2 + ' from a Care of Magical Creatures class and it was now ' + verb2 + ' gently ' +
'on a table surrounded by a knot of curious people. </p>' +
'</div>'
);
}
});
function validate() {
var success = true;
$('.input').each(function(i, item) {
if ($(item).val() === "")
{
console.log("Missing textarea input");
success = false;
$(item).attr("style","border:1px solid red;");
//note it will overwrite your element style in all Input class
}
else
{
$(item).removeAttr('style')
// to remove border
}
});
return success;
}
});
The contents get emptied after pressing submit and I only see the completed paragraph for a split second.
You need to prevent the default event handler from executing whether validate passes or not, so you need to remove the if statement around the event.preventDefault() call. The preventDefault is the function that is keeping the from from submitting and re-loading your page.
Also, your Fiddle was not set to jQuery (it was set to no-library) so that may have also been causing you issues during your testing.
Edited for example of what I'm talking about:
$('#form1').on('submit', function (event) {
// block the form from submitting by
// preventing the event's default behaviour from executing.
event.preventDefault();
if(validate()) {
var adjective1 = $('#adjective1').val();
var adjective2 = $('#adjective2').val();
var pluralnoun = $('#plural-noun').val();
... etc ...
I would use php and set a variable to the GET value of the textarea and set the value of the textarea to that variable
I have created a html like this:
<body onload = callAlert();loaded()>
<ul id="thelist">
<div id = "lst"></div>
</ul>
</div>
</body>
The callAlert() is here:
function callAlert()
{
listRows = prompt("how many list row you want??");
var listText = "List Number";
for(var i = 0;i < listRows; i++)
{
if(i%2==0)
{
listText = listText +i+'<p style="background-color:#EEEEEE" id = "listNum' + i + '" onclick = itemclicked(id)>';
}
else
{
listText = listText + i+ '<p id = "listNum' + i + '" onclick = itemclicked(id)>';
}
listText = listText + i;
//document.getElementById("lst").innerHTML = listText+i+'5';
}
document.getElementById("lst").innerHTML = listText+i;
}
Inside callAlert(), I have created id runtime inside the <p> tag and at last of for loop, I have set the paragraph like this. document.getElementById("lst").innerHTML = listText+i;
Now I am confuse when listItem is clicked then how to access the value of the selected item.
I am using this:
function itemclicked(id)
{
alert("clicked at :"+id);
var pElement = document.getElementById(id).value;
alert("value of this is: "+pElement);
}
But getting value as undefined.
Any help would be grateful.
try onclick = itemclicked(this.id) instead of onclick = 'itemclicked(id)'
Dude, you should really work on you CodingStyle. Also, write simple, clean code.
First, the html-code should simply look like this:
<body onload="callAlert();loaded();">
<ul id="thelist"></ul>
</body>
No div or anything like this. ul and ol shall be used in combination with li only.
Also, you should always close the html-tags in the right order. Otherwise, like in your examle, you have different nubers of opening and closing-tags. (the closing div in the 5th line of your html-example doesn't refer to a opening div-tag)...
And here comes the fixed code:
<script type="text/javascript">
function callAlert() {
var rows = prompt('Please type in the number of required rows');
var listCode = '';
for (var i = 0; i < rows; i++) {
var listID = 'list_' + i.toString();
if (i % 2 === 0) {
listCode += '<li style="background-color:#EEEEEE" id="' + listID + '" onclick="itemClicked(this.id);">listItem# ' + i + '</li>';
}
else {
listCode += '<li id="' + listID + '" onclick="itemClicked(this.id);">listItem# ' + i + '</li>';
}
}
document.getElementById('thelist').innerHTML = listCode;
}
function itemClicked(id) {
var pElement = document.getElementById(id).innerHTML;
alert("Clicked: " + id + '\nValue: ' + pElement);
}
</script>
You can watch a working sample in this fiddle.
The problems were:
You have to commit the id of the clicked item using this.id like #Varada already mentioned.
Before that, you have to build a working id, parsing numbers to strings using .toString()
You really did write kind of messy code. What was supposed to result wasn't a list, it was various div-containers wrapped inside a ul-tag. Oh my.
BTW: Never ever check if sth. is 0 using the ==-operator. Better always use the ===-operator. Read about the problem here
BTW++: I don't know what value you wanted to read in your itemClicked()-function. I didn't test if it would read the innerHTML but generally, you can only read information from where information was written to before. In this sample, value should be empty i guess..
Hope i didn't forget about anything. The Code works right now as you can see. If you've got any further questions, just ask.
Cheers!
You can pass only the var i and search the id after like this:
Your p constructor dymanic with passing only i
<p id = "listNum' + i + '" onclick = itemclicked(' + i + ')>
function
function itemclicked(id)
{
id='listNum'+i;
alert("clicked at :"+id);
var pElement = document.getElementById(id).value;
alert("value of this is: "+pElement);
}
is what you want?
I am not sure but shouldn't the onclick function be wrapped with double quotes like so:
You have this
onclick = itemclicked(id)>'
And it should be this
onclick = "itemclicked(id)">'
You have to modify your itemclicked function to retrieve the "value" of your p element.
function itemclicked( id ) {
alert( "clicked at :" + id );
var el = document.getElementById( id );
// depending on the browser one of these will work
var pElement = el.contentText || el.innerText;
alert( "value of this is: " + pElement );
}
demo here