Say I want to target a specific letter in a textbox region and replace it with another letter using either jquery or javascript, how would I do that and still be able to target another letter afterwards, and again, and again etc.? The letter to change and what it will be changed to will be inputed from either a textbox or a dropdown (whichever is easier)
P.S I tried jQuery's replace function and it didn't work (I probably didn't use it correctly though :)
$( "button" ).click( function() {
$( "Changed" ).replaceWith( $( "New" ) );
});
$("button").click(function() {
var old = $("#Changed").val();
var replacement = $("#New").val();
var regexp = new RegExp(old, 'g');
$("#Input").val(function(i, current) {
return current.replace(regexp, replacement);
});
});
You need to use # before IDs to select them.
You need to get the values of the inputs using .val().
jQuery's .replaceWith is for replacing entire DOM elements, not changing the value of an input.
You use .val() to change the value of the input. When the argument is a function, the function gets called with the current value as a parameter, and the return value is put in its place.
The Javascript method .replace() is used to perform replacements in strings. To do multiple replacements, you need to use a RegExp with the g flag.
DEMO
Please Check following code if it helps : http://jsfiddle.net/La2y734g/2/
HTML as follows
<textarea id="Input" cols="50" rows="5">This textbox has been given a name of "myTextBox". This can be used by any script that process the contents of this textbox (once it's been submitted to the server).</textarea>
<br>Replace
<input type="text" id="replace">with
<input type="text" id="with">
<button>Detect Single Letters And Replace</button>
Javascript as follows
$("button").on("click", function () {
//$( "#Input" ).replaceWith( $( "Change" ) );
var toReplace = $('#replace').val();
var withText = $('#with').val();
var newText = $("#Input").val().replace(toReplace, withText );
$("#Input").val(newText);
});
Related
How to find the value of text field using onblur() in next input field.
I tried:
function get_value() {
var inv_nrs;
inv_nrs = document.getElementsByTagName('text1').value;
alert(inv_nrs);
}
text1 is name of input which I am trying to get value.
text2 is name of input where onblur() is triggered.
Two problems:
To get elements by their name attribute, use document.getElementsByName(), not document.getElementsByTagName.
Since these functions return a collection, not a single element, you have to index them to get a specific element.
So the function should be:
function get_value() {
var inv_nrs;
inv_nrs = document.getElementsByName('text1')[0].value;
alert(inv_nrs);
}
Here's a simple snippet which illustrates a way to do this.
(You may wish to use alert in place of console.log)
document.getElementById("text2").onblur = function() {
console.log(document.getElementById("text1").value)
}
<input type="text" id="text1" value="123" />
<input type="text" id="text2" />
Are you looking for an element with id = "text1" or real name = "text1"?
At least if it's their id try getElementById("text1"), that returns one single element. If you talking about the name-attribute, take getElementByName("text1"), this may return more than one element (if there are more then one with the same name).
i think you want this???
function get_value()
{
var inv_nrs;
inv_nrs = document.getElementById('txt1').value;
document.getElementById('txt2').value=inv_nrs;
}
<input type="text" id="txt1" >
<input type="text" id="txt2" onblur="get_value()">
If you search with tagname then you need to insert a tagname:
document.getElementsByTagName('input')[whole_number].value which also
returns a live HTMLCollection
Eg. document.getElementsByTagName("input")[0].value; ,if this is the first textbox in your page.
You can get the value of an html element also on different ways:
document.getElementsByName('text1')[whole_number].value which also
returns a live NodeList
Eg. document.getElementsByName("searchTsxt")[0].value; if this is the
first textbox with name 'searchtext' in your page.
You can also get element by Id:
document.getElementById('IDHere').value to get the value of desired
box
You can also get it by way of Classname:
Use document.getElementsByClassName('class_name')[whole_number].value
which returns a Live HTMLCollection
Good luck
This one has me stumped. I want to remove the "+" from a label element. Here's the HTML:
<label class="option" for="edit-attributes-21-33">
<input type="radio" id="edit-attributes-21-33" name="attributes[21]"
value="33" checked="checked" class="form-radio"> 4 oz, +$15.00</label>
I started with this
$(".option").each(function(index, value) {
$(this).text( $(this).text().replace("+", ""));
})
This removes the "+" but also strips out the input element. So then I tried:
$(".option").each(function(index, value) {
var oldString = $(this).html();
var newString = oldString.replace("+", "");
console.log(oldString, newString);
$(this).text(newString);
})
This makes a string of the correct html mark-up, but it's a string and is passed back to the DOM that way. I've seen another post with the same problem, but no solution.
You can achieve what you want using your code by using .html() instead of .text():
$(".option").each(function(index, value) {
var oldString = $(this).html();
var newString = oldString.replace("+", "");
console.log(oldString, newString);
$(this).html(newString);
});
Here's the JQuery .html() method ref: https://api.jquery.com/html/
Here's the Fiddle: https://jsfiddle.net/Darkseal/1c572Luw/
I also slightly modified your <input> end tag to make it XHTML compliant.
What you're looking for is called a textNode. I gave your label an ID to make it easier, but the priciple remains the same for other selectors:
var node = document.getElementById("example").childNodes[2];
node.nodeValue = node.nodeValue.replace("+", "");
With a simple demo.
You should try to use plain JS as much as you can in favour in jQuery. Plain JS is often a lot faster than jQuery is.
After the comment, if you don't know the exact position of the textnode, check this.
Late answer, just for the sake of showing a different approach using jQuery.
Here you would keep the input state, and wouldn't have the risk of replacing chars that you don't want to. Let's say you used + somewhere else, not just on the label text.
$(function () {
$('label.option').each(function () {
var label = $(this);
var input = $('input.form-radio', this);
var text = label.text();
// Clean up the label contents.
label.empty();
// Replace the char occurrences.
text = text.replace(/\+/g, "");
// Append both the input and the modified text.
label.append(input).append(text);
});
});
Demo
I know that the solution is the jQuery.on-function but it don't work as I expect it would do.
Following problem:
I pull via Websocket(JSON) data and build my page up inside the document ready function (for connection reasons).
That means I add several input fields via the jQuery.append()-function and try to access the select-input when the SET button is pressed. Accessing the select input fails.
I have selected the body as parent element, every other form field should be in it.
For demo reasons I removed the Websocket-Functions. I have hardcoded the form as it would be in real. The debug-messages are displayed in the firebug-console.
Here is the fiddle: http://jsfiddle.net/gLauohjd/
This is the way I am accessing the select input
$("body").on('click', ':button', function () {
console.log( $( this ).text() ); //Value of the pressed button
var ip = $(this).attr('ip');
var selectvalue = "#" + "modeselect" + ip;
console.log(selectvalue); //Print the selector to verify it is ok
console.log($(selectvalue).val()); //fails ->not found in DOM
Any help on that is very appreciated!
To select a tag with jQuery, use just the tag name.
$("body").on('click', 'button', function () { .. } // any button clicked on body
As for actually retrieving the values, you won't be able to do so unless you escape the dots.
$("#modeselect127\\.0\\.0\\.1").val();
You could use something like:
var selectvalue = "#" + "modeselect" + ip.replace(/\./g, "\\\\.");
Hope this helps.
I'm trying to allow users to edit the text of a paragraph in a website. I take a paragraph and replace the <p> tags with <textarea> tags using the .replaceWith() function. When I try to take the value of the textarea, it returns blank. Here's a JSfiddle.
HTML:
<p><a class="edit">Edit</a>I'm going to change this into a textarea field and retrieve the value.</p>
JS:
$(document).ready(function() {
$('.edit').hide();
var object = $('p');
object.on("mouseenter", function() {
$('.edit').show();
object.on('click','.edit',function(){
var oldText = object.text();
oldText = oldText.substr(4); // Exclude the word 'Edit'
object.replaceWith($("<textarea>").val(oldText).css("width",object.css('width')).css('height',object.css('height')));
var value = object.val();
alert("Value: "+value);
});
});
});
I'm a programming beginner, so if you have style or implementation tips, feel free to share. This is just my gut reaction to solving the problem; there may be a simpler way to accomplish the same thing.
EDIT: I should also mention that in my website, each paragraph comes from a database table that I'm displaying using an AJAX function. When the user is done editing, he can click a button, and the website will take the new value of the textarea field and UPDATE *table* SET *text*=newText WHERE *text* LIKE oldText;
Try just using contenteditable='true' instead of changing to a textarea. It will make the <p> editable.
Like this:
<p contenteditable='true'><a class="edit">Edit</a>
I'm going to change this into a textarea field and retrieve the value.</p>
If you want to make your text area editable when someone clicks 'Edit', you can create a function that sets the contenteditable attribute to true and then gives focus to the <p> element.
Your code is not trying to get the value of the <textarea>. Your call:
object.replaceWith( ... )
does not change the value of the variable "object" — it's still the jQuery object for the <p> tag, but after that it's out of the DOM. <p> tags don't have a "value" property.
It's almost always a bad idea to set up event handlers inside another event handler (well, an event handler for interaction events anyway). Event handlers accumulate, so each "mouseenter" event will add another "click" handler.
ckersch is right about an easier method being to use contenteditable, but if you're looking to a solution for your specific problem, change your selector from this:
var value = object.val();
To this:
var value = $("textarea").val();
Full code:
$(document).ready(function() {
$('.edit').hide();
var object = $('p');
object.on("mouseenter", function() {
$('.edit').show();
object.on('click','.edit',function(){
var oldText = object.text();
oldText = oldText.substr(4); // Exclude the word 'Edit'
object.replaceWith($("<textarea>").val(oldText).css("width",object.css('width')).css('height',object.css('height')));
var value = $("textarea").val();
alert("Value: "+value);
});
});
});
Fiddle
There are many ways you could make it more robust, including adding a class or id to your textarea, and then using it to be selected, such as this way:
object.replaceWith($("<textarea class='selectMe'>").val(oldText).css("width",object.css('width')).css('height',object.css('height')));
var value = $(".selectMe").val();
You are using the method replaceWith() wrong. The argument must be a string or a function that returns a string, not a jquery selector. Also, you should place the onclick event outside of the mouseenter event (this is valid for any event, never nest them)
$(document).ready(function() {
function makeTextarea(e) {
e.preventDefault();
var edit = $(e.currentTarget);
var parent = edit.parent();
edit.remove();
parent.replaceWith('<textarea>' + parent.text() + '</textarea>');
}
$('.edit').on('click', makeTextarea);
});
Fiddle: http://jsfiddle.net/U57v2/4/
"When the document is ready listen for clicks on .edit class. When clicked store a reference to the parent element (<p>) and then remove the edit element. Finally replace the parent element (<p>) with a textarea with the contents of the <p> element."
ckersh is absolutely right about the contenteditable, but if you're looking for a specific answer to your code, there are a few things you could improve.
There are a couple of issues with your code. First, you're rebinding the on('click') handler every time you mouse over the paragraph, so if you mouse over 5 times, you're executing the anonymous function 5 times. You only need to bind the on routine once. Second, the variable object never changes, so when you replace it with a textarea, you need a new selector to get the value.
I've updated your fiddle with the enhancements I've mentioned above. I also added a mouseleave event, because I figure you want to hide the "Edit" button when you leave the paragraph. The updated javascript can be seen below:
$(document).ready(function () {
$('.edit').hide();
var object = $('p');
object.on("mouseenter", function () {
$('.edit').show();
}).on("mouseleave", function () {
$('.edit').hide();
}).on("click", '.edit', function () {
var oldText = object.text();
oldText = oldText.substr(4); // Exclude the word 'Edit'
object.replaceWith($("<textarea>").val(oldText).css("width", object.css('width')).css('height', object.css('height')));
var value = $("textarea").val();
alert("Value: " + value);
});
});
<textarea id="metaSourceText" name='key' style="width:100%" class="text ui-widget-content ui-corner-all" rows="1"></textarea>
I tried
$metaSourceValue = $('metaSourceText').val();
alert($metaSourceValue);
But it shows "undefined"
Your code just needs to be tweaked, to something like this:
var metaSourceValue = $('#metaSourceText').val();
alert(metaSourceValue);
you were missing the hash before metaSourceText, signaling an ID to jQuery. And you typically don't want to start variables with $
You missed the # character in $('#metaSourceText')
.text() method will also give you value of textarea. In ready() state you can either get object of textarea using class selector or id selector.
$(document).ready(function () {
$("#submitbtn").click(function () {
var textAreaValue = $("#txtMessage").text();
alert(textAreaValue);
});
});
Check sample here: http://www.codegateway.com/2012/03/get-textarea-value-in-jquery.html
Please define the selector with '#' prefix as it is an ID you are referring.
In your case, it refers a DOM element of type metaSourceText which really does not exists..
To get a value of this text area:
you can use .text() or val();
$(function(){
var textareaContent = $('#metaSourceText').text();
alert(textareaContent);
});
fiddle link:http://jsfiddle.net/Ds4HC/1/
Javascript variables don't start with $. EDIT: They can, but usually do not. See
Why would a JavaScript variable start with a dollar sign?)
You want to try:
var metaSourceValue = $('#metaSourceText').val();
alert(metaSourceValue);
The $(...) used by jQuery is a shortcut to the jQuery function.
Also, as others mentioned, you need $('#metaSourceText') if you're trying to reference the textarea by id - you were missing the #.