JQuery - Append to text area that has been modified with Jquery - javascript

I am trying to append the value of a div or a input box to my text area. I have this working no problem but if i clear the contents of the text area first with a Jquery action it doesnt allow me to use my append features.
E.g.
<script type="text/javascript">
$(document).ready(function() {
$("#Column1").click(function () {
$("#sql").append($("#Column1").val())
})
$("#Column2").click(function () {
$("#sql").append($("#Column2").html())
})
$("#reset_sql").click(function () {
$("#sql").val('SELECT ')
})
</script>
<div> <input type="checkbox" name="column1" id="column1" value="`Column1`"> column1 </div>
<div id="Column2"> Column2 </div>
<textarea rows="10" cols="80" name="sql" id="sql"><? echo $sql ;?></textarea>
<input type="submit" value="submit" />
<input type="button" value="reset sql" id="reset_sql" />
The input and div lines above are just generic examples but relate exactly to what i'm trying to do.
I dont understand that when i clear the text area with javascript that my appends wont work. I get no JS errors in firefox error console.
thank you

You have several issues with your code: you haven't closed your document.ready callback, you are using the incorrect case when refering to your ID's, and you're using some of the jQuery methods incorrectly. For example, append() appends HTML to an element, whereas you want to update the value.
Your logic isn't quite correct either, since columns won't be removed when you uncheck a checkbox, and the columns won't be comma delimited (it looks like you are building a SQL string here).
I believe something like this is what you're looking for:
$(document).ready(function() {
var $sql = $('#sql');
var initialValue = $sql.val();
$("#column1, #column2").on('change', function () {
var cols = [];
var checked = $('input[type="checkbox"]').filter(':checked').each(function() {
cols.push($(this).val());
});
$sql.val(initialValue + ' ' + cols.join(', '));
})
$("#reset_sql").on('click', function () {
$sql.val(initialValue)
})
});
Working Demo

Your checkbox has an id of 'column1', but your event handler is $("#Column1").click(function () {.
Case matters! Either change the id to 'Column1' or the event handler to look for $('#column1').
Demo

Related

Get the value of an <input type="text"> that was created dynamically inside a modal

i would like to get the value of an <input type="text"> that was created dynamically inside a modal and put it into variable "newcomment".
This is how i make the input:
var newcomment;
var p = $("<p>");
p.append("Some text");
p.append("</p>");
p.append("<input type='text'id='comment_text' value='Comment'"+"onblur=newcomment=$('#comment_text').val()"+" onfocus=if(this.value==this.defaultValue)this.value=''>"+"</input>");
$("div.modal-body").append(p);
The problem is when i write something like "ok" inside the textbox in the modal, and after i focusout from the textbox: newcomment seems not update to "ok" and still have the default "Comment" value.
1st: You need to use newcomment=this.value instead of newcomment=$('#comment_text').val()
2nd: No need to add + signs in your input html code while you not trying to concatenate string by putting variables to it
var newcomment;
var p = $("<p>");
p.append("Some text");
p.append("</p>");
p.append("<input type='text' id='comment_text' value='Comment' onblur='newcomment=this.value; alert(newcomment);' onfocus=if(this.value==this.defaultValue)this.value='' />");
$("body").append(p);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Not really the answer here, but might help you get at the root of the problem.
JS:
var newComment, defaultValue;
function doOnBlur(){
newComment = $('#comment_text').val()
}
function doOnFocus(){
if($('#comment_text').val() == defaultValue){
$('#comment_text').val('')
}
}
HTML:
<input type='text' id='comment_text' placeholder='Comment' onblur='doOnBlur()' onfocus='doOnFocus()' />
<!-- inputs dont have a close tag, also should use placeholder for temporary text -->
from here, you can set breakpoints in the debugger and see where your code is going wrong. You can also modify the functions much more easily rather than writing the executing code in the HTML

Jquery replace string in a textarea

I am trying to replace a string value in textarea while typing in textbox with jquery. I used keypress event to try achieving that. What may be the issue here in this fiddle?
<input type="text" id="textbox" />
<textarea id="txtArea">This is a sample test.</textarea>
jquery code
$("#textbox").keypress(function () {
var txtAreaValue = $('#txtArea').val();
var txtAreaValueAfterreplace = txtAreaValue.replace('sample', $(this).val());
$('#txtArea').val(txtAreaValueAfterreplace);
});
The main problem is that, when using keypress you are getting the value of the input box before it is set, so nothing appears. However even if you change it to keyup you still will only get one value because once 'sample' is replaced it is gone so therefor it cannot be replaced again.
A new logic needs to be considered if you are wanting to replace sample with the full value of the textarea. Consider the following example:
$("#add").click( function () {
$( '#txtArea' ).val( $('#txtArea').val().replace( 'sample', $("#textbox").val() ) );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="textbox" /><br>
<input type='button' id='add' value='add'>
<textarea id="txtArea">This is a sample test.</textarea>
Or we replace when the user stopped typing
var typing;
$("#textbox").keyup( function () {
// Stop the change from being made since they typed again
clearTimeout(typing);
// They typed, so set the change to queue up in a 3rd of a second
typing = setTimeout(function(){
$( '#txtArea' ).val( $('#txtArea').val().replace( 'sample', $("#textbox").val() ) );
},350);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="textbox" /><br>
<textarea id="txtArea">This is a sample test.</textarea>
You want to look for keyup, not keypress (you want to make sure you get the whole string.
You are trying to put the textbox value right? You're looking for the textarea value in line two of the javascript.
If you replace sample on the first key stroke, there won't be anything to replace the second key stroke.
You can simplify lines 3 and 4 into one line.
replace can only be used on a string. So you need to get the value first, if you're going to do it that way. txtAreaValue.val().replace('sample', $(this).val());
Feel free to play around with it on this fiddle: http://jsfiddle.net/snlacks/abc6skp9/
$("#txtBox").on('keyup', function () {
var txtValue = $(this).val();
$('#txtArea').val("this is a " + txtValue);
});
If you have a longer string, replace might work better, but you still need to store the full string somewhere.
var longString = "some really long string... sample... more...";
$("#txtBox").on('keyup', function () {
var txtValue = $(this).val();
$('#txtArea').val(longString.replace('sample', txtValue);
});

Modify the value of each textfield based on original value using jQuery

Is it possible to modify the value of each textfield present in a webpage, based on the original value, using jQuery or JavaScript?
For example, suppose I have 50 textfields in a page. I want to remove whitespace from the beginning and end of each textfield’s value. I don’t find it to be a good idea to call the function for every textfield individually. How can I do it without calling a function for each textfield?
Can just use val() with a callback argument. It will loop over all elements for you:
$('input[type=text]').val(function( index, originalValue){
return $.trim(originalValue);
});
val() API docs
You can execute this code:
$('input[type=text]').each(function (i, e) {
var $this = $(e);
$this.val($this.val().trim());
});
Get all the inputs from the page using jquery then run a loop, and for each element trim the value
<body>
<input type="text" value=" abc " >
<input type="text" value=" def " >
<input type="button" id="remove" value="Remove">
<script type="text/javascript">
$(document).ready(function(){
$('#remove').click(function(){
var inputs = $('input[type=text]');
$.each(inputs, function(index,input){
$(input).val($(input).val().trim())
});
});
});
</script>
</body>

clear text box using JS function in a href on click

I have this function:
<script>
function ClearTextBox(textbox_name) {
$(textbox_name).val("")
}
</script>
that removes values from a text input
i am trying to call it using:
Clear
but its not clearing the text box
You should use Unobtrusive JavaScript .
Try this code.
$('a').on('click',function(){
$('#customercompany1').val("");
});
It seems working fine for me.. but the console shows the following error
Uncaught SyntaxError: Unexpected token )
this is due to the javascript:void(); in your href attribute.
so i changed the mark up to
Clear
<input type="text" id="customercompany1" value="test value" />
and the script as
function ClearTextBox(textboxname) {
$(textboxname).val(" ");
return false;
}
Hope this helps....
DEMO HERE
Write your function like this:
function ClearTextBox(myInput) {
var txtBox = document.getElementById(myInput);
txtBox.value = "";
return false;
}
And write your html like this:
Clear
<input type="text" id="customercompany1" />
Need to see your HTML to be sure, but I'm guessing your text box looks like this :
<input type="text" name="customercompany1"/>
and it needs to look like this :
<input type="text" name="customercompany1" id="customercompany1"/>
The '#' jQuery selector matches on the id attribute, not the name attribute.
(This is true if you have used a textarea rather than an input)

Keyup function into form element

I have a script I am using to copy a field into another input field using keyup blur paste. This script works, however I need to modify it to also go into two different form elements which are named data-cost="" and debt="", instead of the <div id="viewer">
This is the script as I have it now :
$(function () {
$('#account_balance1').on('keyup blur paste', function() {
var self = this;
setTimeout(function() {
var str = $(self).val();
$("#viewer").text(str.replace(/^\$/, ''));
}, 0);
});
$("#viewer").text($('#Website').val().replace(/^\$/, ''));
});
This is the html :
<!--This where I get the value from -->
<input type="text" class="balance" id="account_balance1" name="cardb" value=""/>
<!--the first 2 elements are where I need the values to go -->
<input data-cost="" debt="" value="" type="checkbox" name="f_2[]"/>
if you need the two attributes (data-cost and debt) to be each set to your value you need:
$("input[data-cost][debt]").attr('data-cost',str.replace(/^\$/, ''));
$("input[data-cost][debt]").attr('debt',str.replace(/^\$/, ''));
Just use that selector then
$("input[data-cost][data-debt]")
I think you're maybe having a fundamental misunderstanding of what the data attributes are for? You're aware that they will not be posted with the form? I think what you're looking for is the data function which will allow you to set the data attributes http://api.jquery.com/data/.
Perhaps you want data-cost and data-debt?
So if your input looks like this:
<input data-cost="" data-debt="" value="" type="checkbox" name="f_2[]" id="checkboxId" />
Then you can set the values in your javascript like this:
var value1="some value";
var value2="another value";
$('#checkboxId').data('cost', value1);
$('#checkboxId').data('debt', value2);
I don't believe having an attribute named simply "debt" as you have it above is valid.
I'd do it this way (setTimeout was useless) :
$(function () {
$('#account_balance1').on('keyup blur paste', function () {
var self = this;
var nextCheckbox = $(self).next("input[type='checkbox']");
var str = $(self).val();
$("#viewer").text(str.replace(/^\$/, ''));
nextCheckbox.data({
cost: str,
debt: str
});
/*
You won't be able to see changes if you inspect element,
so just check in console
*/
console.log(nextCheckbox.data());
});
});
And your html markup must be slightly modified :
<!--This where I get the value from -->
<input type="text" class="balance" id="account_balance1" name="cardb" value="" />
<!--the first 2 elements are where I need the values to go -->
<input data-cost="" data-debt="" value="" type="checkbox" name="f_2[]" />
<!--I added the viewer to check if everything works properly -->
<div id="viewer"></div>

Categories

Resources