I scoured the the site and found a few examples, I got close but not close enough.
I have 2 checkboxes and if a user checks them they are placed in the textarea, if the user removes the check. the value is removed. I want to keep cursor position too.
I am able to add but its still clunky.
My fiddle is http://jsfiddle.net/pU2P9/18/
here is my code
Testing. Values from another field will be inserted here.
<form>
<p>Favorite Color <label><input type="checkbox" value="Green" />Green</label>
<label><input type="checkbox" value="Red" />Red</label></p>
</form>
var textarea = document.getElementById("myTextArea1");
// $('input[type=checkbox]').click(function () {
$('input[type=checkbox]').change(function () {
var $parentForm = $(this).closest("form");
// var text = $(".insert-text", $parentForm).val();
var text = $('input[type=checkbox]:checked').val() + " ";
// var text = $('input[type=checkbox]:checked', $parentForm).val() + " ";
insertAtCursor(textarea, text);
});
function insertAtCursor(myField, myValue) {
if (document.selection) {
myField.focus();
sel = document.selection.createRange();
sel.text = myValue;
}
else if (myField.selectionStart || myField.selectionStart == '0') {
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length);
}
else {
myField.value += myValue;
}
}
;
Any help would be appreciated.
Not sure exactly what you are trying to do, but it seems you're a little confused.
Try something like
$('input[type=checkbox]').change(function () {
if ($(this).is(':checked')) {
var text = $(this).val() + " ";
insertAtCursor(textarea, text);
}
});
I think you're going to drive yourself crazy trying to treat the textarea like you are. You can prepend the colors easily enough, but what do you do when the user un-checks them? For example, what if they check green, then red, then un-checks green? It's now no longer a simple matter of removing 5 characters from the textarea.
If I understand your application, though, you're combining values from different fields in the textarea, so I would do something like this:
function updateTextArea() {
var text = "";
$('input[type=checkbox]:checked').each( function() {
text += $(this).val() + " ";
});
$('input[type=text]').each( function() {
text += $(this).val() + " ";
});
$('#myTextArea1').val( text );
}
Then you can just call this every time one of your values changes. For example, when the user changes one of the check boxes:
$('input[type=checkbox]').change(function () {
updateTextArea();
});
I believe that this will be much cleaner than the approach you're outlining. You can see it in action here: http://jsfiddle.net/8y4D8/19/
Also, you could consider using Backbone.js (http://documentcloud.github.com/backbone/) or some similar Javascript MVC framework.
Related
We are trying to implement like below requirement.
Click of a button some text will be generated and it will be added into textarea.
Button is using Ng-Onclick.
Button Code is below.
<input type="submit" value="Add to form" class="btn btn-primary" ng-click="addToFormID($index)" />
But many buttons will be there like if am adding 4 components 4 buttons will be there to generate the formula.
and Here is my TextArea Code:
<textarea id="summarFormula" ng-model=".Summarisation" ng-change="setSummarisationFormulaDynamic()" cols="100" rows="4"></textarea>
and Here is my Script.
$scope.addToFormID = function(index){
if( $scope.vm.SummarisationForm==null)
{
$scope.vm.SummarisationForm ="["+ $scope.vm.Dependencies[index].NeName+":{"+$scope.vm.Dependencies[index].DbId+","+$scope.vm.Dependencies[index].VersionId+"}]";
}else
$scope.vm.Summarisation+="["+ $scope.vm.Dependencies[index].Name+":{"+$scope.vm.Dependencies[index].Id+","+$scope.vm.Dependencies[index].VersionId+"}]";
$scope.setSummarisationFormDynamic();
}
We can see that in else part $scope.vm.SummarisationForm += so it will + the next formula to previous one so i wants to modify this one and needs to add the content where i am keeping the cursor.
Now What ever I am clicking it is adding it to the end of the content , If am entering enter key keeping cursor into first line of the next line also it is adding it to the same line which already text is there so i wants to find the cursor position and insert into the text where exactly keeping cursor or entering enter key position.
I am very new to angular js so please help me with basic idea with button how can i implement and script modification how can i do it.?
Edit : It is ASP.NET MVC5 Applicaiton.
If you need further more details please let me know.
Thanks in advance to all.
Here is the hero which my issues was resolved. Who ever it is really great that he solved my problem.
and What exactly done is I created directive element as mentioned in this link and called that directive in my view .
Boom it worked.
http://plnkr.co/edit/Xx1SHwQI2t6ji31COneO?p=preview
app.directive('myText', ['$rootScope', function($rootScope) {
return {
link: function(scope, element, attrs) {
$rootScope.$on('add', function(e, val) {
var domElement = element[0];
if (document.selection) {
domElement.focus();
var sel = document.selection.createRange();
sel.text = val;
domElement.focus();
} else if (domElement.selectionStart || domElement.selectionStart === 0) {
var startPos = domElement.selectionStart;
var endPos = domElement.selectionEnd;
var scrollTop = domElement.scrollTop;
domElement.value = domElement.value.substring(0, startPos) + val + domElement.value.substring(endPos, domElement.value.length);
domElement.focus();
domElement.selectionStart = startPos + val.length;
domElement.selectionEnd = startPos + val.length;
domElement.scrollTop = scrollTop;
} else {
domElement.value += val;
domElement.focus();
}
});
}
}
}]);
View Calling like this,
directive name is , myText. so the code will be like in this view side.
<textarea my-text="">
I have a function that I want to change the font color of the user entered string if it is equal to a certain word located in an array.. So far when I step through it it says that it changes the font color but it actually never updates it to the screen and I don't know why. Here is what I have so far
function getLastWord() {
var input = document.getElementById("my_text");
//var input = document.getElementById(textArea.value);
//var lineIn = document.getElementById(my_text).innerHTML;
var inputValue = input.value;
var lastWordTyped
var changeColorOfWord;
if (input == null) {
input == " ";
}
//lastWordTyped = input.substr(input.trim().lastIndexOf(" ") + 1);
lastWordTyped = inputValue.substr(inputValue.trim().lastIndexOf(" ") + 1);
if (input != null) {
for (var i = 0; i < reservedKeyWords.length; i++) {
if (reservedKeyWords[i] === lastWordTyped) {
lastWordTyped = lastWordTyped.fontcolor("blue");
my_text.replace(inputValue, lastWordTyped);
} else {
}
}
}
}
I see two issues with the code thus far.
You are using 'fontcolor("blue")' parameter on the lastWordTyped. The proper syntax to change color is element.style.color="#CCC".
You will need to wrap the last typed word in a span so you can target it and apply the color to just that word.
string.fontcolor is legacy, and should not be used even though I could see it as a viable option in this case
Essentially, what you are doing is adding font tags around the word:
var txt = 'hello world';
txt = txt.fontcolor('blue');
//txt = '<font color="blue">hello world</font>';
You do not show what you do with the result, but if you actually put it in an HTML element it should work, even though instead of using fontcolor, I'd rather use element.style.color. This would require slightly more work though:
var ele = document.querySelector('#my_text');
ele.style.color = 'blue';
ele.innerHTML = lastWordTyped;
If you still want to go with the .fontcolor method, you could just keep what you have in the question and add
input.innerHTML = my_text;
I have the following code
$(document).ready(function () {
$('#big_1').change(function () {
var bigAmt = document.getElementById("big_1").value
+ document.getElementById("big_2").value
+ document.getElementById("big_3").value
+ document.getElementById("big_4").value
+ document.getElementById("big_5").value
+ document.getElementById("big_6").value
+ document.getElementById("big_7").value
+ document.getElementById("big_8").value
+ document.getElementById("big_9").value
+ document.getElementById("big_10").value;
var elem = document.getElementById("totalBig");
elem.value = bigAmt;
});
});
I actually wanted to add the value of big_1 to big_10 on input text value change of "big_1 to big_10" either 1 of the textfield change its value, this should be invoke.
as of now i only run on big_1 change event.
I get an javascript error by adding this way, I think the way I add them up is quite messy.
What should I do to change my code so I can sum up
big_1 to big_10 textfield value, and on change of big_1 to big_10(any of them), it will invoke this and change span id="totalBig" to the value of their sum (big_1 add until big_10)
Below is my edited extra code:
<input type="number" data-bv-digits-message="true" data-bv-threshold="1" min="0" class="form-control" name="big_1" id="big_1" size="6">
<input type="number" data-bv-digits-message="true" data-bv-threshold="1" min="0" class="form-control" name="big_2" id="big_2" size="6">
all the way until big_10
I wanna on change value of any of this big_Identifier(1-10), it will sum it up and change my
<div class="well">
Total Big: <span id="totalbig">0</span> </span>
</div>
I tried the
<script type="text/javascript">
$(document).ready(function() {
$('#html5Form').bootstrapValidator();
$('.big').change(function() {
var bigAmt = "";
$('.big').each(function () {
bigAmt += $(this).val();
})
var elem = document.getElementById("totalBig");
alert(bigAmt);
elem.value = bigAmt;
});
});
</script>
It doesn't run any alert when any of the big_ value was changed.
It would be much better if you added a big class to every single <input id="big_NUMBER">. Then you could do this:
$(document).ready(function() {
$('.big').change(function() {
var bigAmt = 0;
$('.big').each(function () {
bigAmt += Number($(this).val());
})
$("#totalBig").val(bigAmt);
});
});
That's much cleaner and easier to understand than what you had.
In order for this to work, you'll need to add a class to all your inputs:
<input type="number" data-bv-digits-message="true" data-bv-threshold="1" min="0" class="form-control big" name="big_2" id="big_2" size="6"><!-- Notice the big class-->
This is the best way to group all your inputs. They are all related, so they should share a classes. You should not be calling multiple ids for functionality that's so similar.
If you are using jquery, use it properly, it'll make your life a lot easier.
This will work for you in your case exactly
$(document).ready(function() {
$('[id^="big"').change(function(){
var total = (+$('#totalBig').val());
var currentVal = (+$(this).val());
total += currentVal;
$('#totalBig').val(total)
})
});
DEMO
Add class="bigs" to all inputs and then try this:
$(document).ready(function () {
var intTotalBig;
$('.bigs').change(function () {
intTotalBig = 0;
$('.bigs').each(function(){
$thisVal = $(this).val();
if ($.isNumeric($thisVal)){
intTotalBig += parseInt($thisVal, 10);
}
});
$("#totalBig").val(intTotalBig);
});
});
This code check all inputs on every change and sum all of them that has a number value and ignore empty or no number values.
Check JSFiddle Demo
You monitor the change event on all the input type text as follows:
$('input:text').change(
function () {
alert('text changed of any text box.');
//You can doo your code here.
});
Or...
If you want add the monitor to any selected text boxes then you will have to add any css class to those selected text boxes and then monitor those text boxes through class as follows:
$('.yourclass').change(
function () {
alert('text changed of any text box.');
//You can doo your code here.
});
this change event will fire when you lose focus from the text box after changing the text....
but if you want with loosing the focus (means if you want to update the count while typing) then you should use keyup event as stated in this answer.
$(document).ready(function() {
$('#big_1').change(function() {
var divArray = ["big_1","big_2","big_3","big_4","big_5","big_6","big_7","big_8","big_9","big_9","big_10"];
var bigAmt = 0;
for(var i = 0, n = divArray.length;i<n;i++)
{
bigAmt += parseInt($("#" + divArray[i]).val(),10);
}
$("#totalBig").val(bigAmt);
});
});
Try the above, it should do what you're looking for. You'll probably want to use parseInt as well incase the input isn't of "number" type.
*edit, forgot the # for the id.
*edit, removed comment about considering using jquery functions because people are really sensitive.
I am doing a self print function by gathering all the HTML from the users screen and putting it into a variable which then displays a pop-up screen so the user can print that information.
var disp_setting = "toolbar=no,location=no,directories=no,menubar=no,";
disp_setting += "scrollbars=yes, height=500, left=100, top=25";
var content_vlue = document.getElementById("print_content").innerHTML;
var docprint = window.open("", "", disp_setting);
docprint.document.open();
docprint.document.write('<html><head>');
docprint.document.write('</head><body text="#000000" onLoad="self.print()">');
docprint.document.write('<table>');
docprint.document.write(content_vlue);
docprint.document.write('</table>');
docprint.document.write('</body></html>');
docprint.document.close();
UPDATE:
OK thanks to many of the suggestions so far I'm starting to make some headway...
What I would like to do is instead of manipulating print_content, I would like to put print_content into a variable (i.e. content_vlue) and then manipulate content_vlue.
var content_vlue = document.getElementById("print_content").innerHTML;
$("content_vlue").find("INPUT[type='text']").each(function(i){
var input = $(this);
input.replaceWith("<span class='textinput'>" + input.val() + "</span>";
});
Is there a way to do this?
Can you use a library like jQuery? It would be pretty straight forward to replace the inputs with span tags once you'd created the page:
function cleaninputs(){
$("body").find("input").each(function(i) {
var input = $(this);
input.replaceWith("<span class='textInput'>" + input.val() + "</span>");
});
}
EDIT:
Here's a slightly refactored version which should do what you want:
function replaceInputs( _which ){
var cleanHTML = $("#"+_which).clone();
cleanHTML.find("input").each(function() {
var input = $(this);
input.replaceWith("<span class='textInput'>"+ " " + input.val() + "</span>");
});
return cleanHTML.html();
}
Then replace this line:
var content_vlue = document.getElementById("print_content").innerHTML;
with:
var content_vlue = replaceInputs("print_content");
And you should be all set. For good measure I made a jsfiddle: http://jsfiddle.net/pcsF3/1/
Using only CSS you can simply hide the border of the text boxes making it look like ordinary text:
docprint.document.write('<style type="text/css"> input { border: 0; }</style>');
I have this textarea that shows inputted text, but when the number of lines exceeds the size and width of the textarea, the user has to scroll down to see what they have last inputted.
I'd like the textarea to be set to the bottom everytime the enter button is pressed.
I've tried the following, but I can't get it to work:
function inputKeyDown(evt, input) {
if (evt.keyCode == 13) {
var textarea = document.getElementById("textarea");
textarea.value += "\n" + ">" + " " + input.value;
input.value = "";
return false;
}
var elem = document.getElementById('textarea');
elem.scrollTop = elem.scrollHeight;
}
and then I call the function keyDown in <input onKeyDown="return keyDown(event, this);" ...>
Any idea why no workie?
Try the following:
textarea.scrollTop = textarea.scrollHeight - textarea.clientHeight;
It depends on what sort of input you are looking at, but forcing the cursor back to the bottom could potentially be a serious usability problem. If you need a textarea that automatically expands, have a look at existing solutions such as this jQuery plugin
I'm not really sure if this is what you want but have a look this: http://jsfiddle.net/yV76p/
var textarea = document.getElementById("textarea");
textarea.onkeyup = function(evt) {
this.scrollTop = this.scrollHeight;
}